Index: head/sys/dev/sound/usb/uaudio.c =================================================================== --- head/sys/dev/sound/usb/uaudio.c (revision 276700) +++ head/sys/dev/sound/usb/uaudio.c (revision 276701) @@ -1,5932 +1,5932 @@ /* $NetBSD: uaudio.c,v 1.91 2004/11/05 17:46:14 kent Exp $ */ /* $FreeBSD$ */ /*- * Copyright (c) 1999 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Lennart Augustsson (lennart@augustsson.net) at * Carlstedt Research & Technology. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * USB audio specs: http://www.usb.org/developers/devclass_docs/audio10.pdf * http://www.usb.org/developers/devclass_docs/frmts10.pdf * http://www.usb.org/developers/devclass_docs/termt10.pdf */ /* * Also merged: * $NetBSD: uaudio.c,v 1.94 2005/01/15 15:19:53 kent Exp $ * $NetBSD: uaudio.c,v 1.95 2005/01/16 06:02:19 dsainty Exp $ * $NetBSD: uaudio.c,v 1.96 2005/01/16 12:46:00 kent Exp $ * $NetBSD: uaudio.c,v 1.97 2005/02/24 08:19:38 martin Exp $ */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #include #include #include #include #include #include #define USB_DEBUG_VAR uaudio_debug #include #include #include /* for bootverbose */ #ifdef HAVE_KERNEL_OPTION_HEADERS #include "opt_snd.h" #endif #include #include #include #include #include "feeder_if.h" static int uaudio_default_rate = 0; /* use rate list */ static int uaudio_default_bits = 32; static int uaudio_default_channels = 0; /* use default */ #ifdef USB_DEBUG static int uaudio_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, uaudio, CTLFLAG_RW, 0, "USB uaudio"); -SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, debug, CTLFLAG_RWTUN, &uaudio_debug, 0, "uaudio debug level"); SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_rate, CTLFLAG_RWTUN, &uaudio_default_rate, 0, "uaudio default sample rate"); SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_bits, CTLFLAG_RWTUN, &uaudio_default_bits, 0, "uaudio default sample bits"); SYSCTL_INT(_hw_usb_uaudio, OID_AUTO, default_channels, CTLFLAG_RWTUN, &uaudio_default_channels, 0, "uaudio default sample channels"); #endif #define UAUDIO_NFRAMES 64 /* must be factor of 8 due HS-USB */ #define UAUDIO_NCHANBUFS 2 /* number of outstanding request */ #define UAUDIO_RECURSE_LIMIT 255 /* rounds */ #define MAKE_WORD(h,l) (((h) << 8) | (l)) #define BIT_TEST(bm,bno) (((bm)[(bno) / 8] >> (7 - ((bno) % 8))) & 1) #define UAUDIO_MAX_CHAN(x) (x) #define MIX(sc) ((sc)->sc_mixer_node) union uaudio_asid { const struct usb_audio_streaming_interface_descriptor *v1; const struct usb_audio20_streaming_interface_descriptor *v2; }; union uaudio_asf1d { const struct usb_audio_streaming_type1_descriptor *v1; const struct usb_audio20_streaming_type1_descriptor *v2; }; union uaudio_sed { const struct usb_audio_streaming_endpoint_descriptor *v1; const struct usb_audio20_streaming_endpoint_descriptor *v2; }; struct uaudio_mixer_node { const char *name; int32_t minval; int32_t maxval; #define MIX_MAX_CHAN 16 int32_t wValue[MIX_MAX_CHAN]; /* using nchan */ uint32_t mul; uint32_t ctl; int wData[MIX_MAX_CHAN]; /* using nchan */ uint16_t wIndex; uint8_t update[(MIX_MAX_CHAN + 7) / 8]; uint8_t nchan; uint8_t type; #define MIX_ON_OFF 1 #define MIX_SIGNED_16 2 #define MIX_UNSIGNED_16 3 #define MIX_SIGNED_8 4 #define MIX_SELECTOR 5 #define MIX_UNKNOWN 6 #define MIX_SIZE(n) ((((n) == MIX_SIGNED_16) || \ ((n) == MIX_UNSIGNED_16)) ? 2 : 1) #define MIX_UNSIGNED(n) ((n) == MIX_UNSIGNED_16) #define MAX_SELECTOR_INPUT_PIN 256 uint8_t slctrtype[MAX_SELECTOR_INPUT_PIN]; uint8_t class; uint8_t val_default; uint8_t desc[64]; struct uaudio_mixer_node *next; }; struct uaudio_configure_msg { struct usb_proc_msg hdr; struct uaudio_softc *sc; }; #define CHAN_MAX_ALT 24 struct uaudio_chan_alt { union uaudio_asf1d p_asf1d; union uaudio_sed p_sed; const usb_endpoint_descriptor_audio_t *p_ed1; const struct uaudio_format *p_fmt; const struct usb_config *usb_cfg; uint32_t sample_rate; /* in Hz */ uint16_t sample_size; uint8_t iface_index; uint8_t iface_alt_index; uint8_t channels; uint8_t enable_sync; }; struct uaudio_chan { struct pcmchan_caps pcm_cap; /* capabilities */ struct uaudio_chan_alt usb_alt[CHAN_MAX_ALT]; struct snd_dbuf *pcm_buf; struct mtx *pcm_mtx; /* lock protecting this structure */ struct uaudio_softc *priv_sc; struct pcm_channel *pcm_ch; struct usb_xfer *xfer[UAUDIO_NCHANBUFS + 1]; uint8_t *buf; /* pointer to buffer */ uint8_t *start; /* upper layer buffer start */ uint8_t *end; /* upper layer buffer end */ uint8_t *cur; /* current position in upper layer * buffer */ uint32_t intr_frames; /* in units */ uint32_t frames_per_second; uint32_t sample_rem; uint32_t sample_curr; uint32_t max_buf; uint32_t pcm_format[2]; uint16_t bytes_per_frame[2]; uint8_t num_alt; uint8_t cur_alt; uint8_t set_alt; uint8_t operation; #define CHAN_OP_NONE 0 #define CHAN_OP_START 1 #define CHAN_OP_STOP 2 #define CHAN_OP_DRAIN 3 uint8_t last_sync_time; uint8_t last_sync_state; #define UAUDIO_SYNC_NONE 0 #define UAUDIO_SYNC_MORE 1 #define UAUDIO_SYNC_LESS 2 }; #define UMIDI_EMB_JACK_MAX 16 /* units */ #define UMIDI_TX_FRAMES 256 /* units */ #define UMIDI_TX_BUFFER (UMIDI_TX_FRAMES * 4) /* bytes */ enum { UMIDI_TX_TRANSFER, UMIDI_RX_TRANSFER, UMIDI_N_TRANSFER, }; struct umidi_sub_chan { struct usb_fifo_sc fifo; uint8_t *temp_cmd; uint8_t temp_0[4]; uint8_t temp_1[4]; uint8_t state; #define UMIDI_ST_UNKNOWN 0 /* scan for command */ #define UMIDI_ST_1PARAM 1 #define UMIDI_ST_2PARAM_1 2 #define UMIDI_ST_2PARAM_2 3 #define UMIDI_ST_SYSEX_0 4 #define UMIDI_ST_SYSEX_1 5 #define UMIDI_ST_SYSEX_2 6 uint8_t read_open:1; uint8_t write_open:1; uint8_t unused:6; }; struct umidi_chan { struct umidi_sub_chan sub[UMIDI_EMB_JACK_MAX]; struct mtx mtx; struct usb_xfer *xfer[UMIDI_N_TRANSFER]; uint8_t iface_index; uint8_t iface_alt_index; uint8_t read_open_refcount; uint8_t write_open_refcount; uint8_t curr_cable; uint8_t max_emb_jack; uint8_t valid; uint8_t single_command; }; struct uaudio_search_result { uint8_t bit_input[(256 + 7) / 8]; uint8_t bit_output[(256 + 7) / 8]; uint8_t recurse_level; uint8_t id_max; uint8_t is_input; }; enum { UAUDIO_HID_RX_TRANSFER, UAUDIO_HID_N_TRANSFER, }; struct uaudio_hid { struct usb_xfer *xfer[UAUDIO_HID_N_TRANSFER]; struct hid_location volume_up_loc; struct hid_location volume_down_loc; struct hid_location mute_loc; uint32_t flags; #define UAUDIO_HID_VALID 0x0001 #define UAUDIO_HID_HAS_ID 0x0002 #define UAUDIO_HID_HAS_VOLUME_UP 0x0004 #define UAUDIO_HID_HAS_VOLUME_DOWN 0x0008 #define UAUDIO_HID_HAS_MUTE 0x0010 uint8_t iface_index; uint8_t volume_up_id; uint8_t volume_down_id; uint8_t mute_id; }; struct uaudio_softc { struct sbuf sc_sndstat; struct sndcard_func sc_sndcard_func; struct uaudio_chan sc_rec_chan; struct uaudio_chan sc_play_chan; struct umidi_chan sc_midi_chan; struct uaudio_hid sc_hid; struct uaudio_search_result sc_mixer_clocks; struct uaudio_mixer_node sc_mixer_node; struct uaudio_configure_msg sc_config_msg[2]; struct mtx *sc_mixer_lock; struct snd_mixer *sc_mixer_dev; struct usb_device *sc_udev; struct usb_xfer *sc_mixer_xfer[1]; struct uaudio_mixer_node *sc_mixer_root; struct uaudio_mixer_node *sc_mixer_curr; uint32_t sc_mix_info; uint32_t sc_recsrc_info; uint16_t sc_audio_rev; uint16_t sc_mixer_count; uint8_t sc_sndstat_valid; uint8_t sc_mixer_iface_index; uint8_t sc_mixer_iface_no; uint8_t sc_mixer_chan; uint8_t sc_pcm_registered:1; uint8_t sc_mixer_init:1; uint8_t sc_uq_audio_swap_lr:1; uint8_t sc_uq_au_inp_async:1; uint8_t sc_uq_au_no_xu:1; uint8_t sc_uq_bad_adc:1; uint8_t sc_uq_au_vendor_class:1; }; struct uaudio_terminal_node { union { const struct usb_descriptor *desc; const struct usb_audio_input_terminal *it_v1; const struct usb_audio_output_terminal *ot_v1; const struct usb_audio_mixer_unit_0 *mu_v1; const struct usb_audio_selector_unit *su_v1; const struct usb_audio_feature_unit *fu_v1; const struct usb_audio_processing_unit_0 *pu_v1; const struct usb_audio_extension_unit_0 *eu_v1; const struct usb_audio20_clock_source_unit *csrc_v2; const struct usb_audio20_clock_selector_unit_0 *csel_v2; const struct usb_audio20_clock_multiplier_unit *cmul_v2; const struct usb_audio20_input_terminal *it_v2; const struct usb_audio20_output_terminal *ot_v2; const struct usb_audio20_mixer_unit_0 *mu_v2; const struct usb_audio20_selector_unit *su_v2; const struct usb_audio20_feature_unit *fu_v2; const struct usb_audio20_sample_rate_unit *ru_v2; const struct usb_audio20_processing_unit_0 *pu_v2; const struct usb_audio20_extension_unit_0 *eu_v2; const struct usb_audio20_effect_unit *ef_v2; } u; struct uaudio_search_result usr; struct uaudio_terminal_node *root; }; struct uaudio_format { uint16_t wFormat; uint8_t bPrecision; uint32_t freebsd_fmt; const char *description; }; static const struct uaudio_format uaudio10_formats[] = { {UA_FMT_PCM8, 8, AFMT_U8, "8-bit U-LE PCM"}, {UA_FMT_PCM8, 16, AFMT_U16_LE, "16-bit U-LE PCM"}, {UA_FMT_PCM8, 24, AFMT_U24_LE, "24-bit U-LE PCM"}, {UA_FMT_PCM8, 32, AFMT_U32_LE, "32-bit U-LE PCM"}, {UA_FMT_PCM, 8, AFMT_S8, "8-bit S-LE PCM"}, {UA_FMT_PCM, 16, AFMT_S16_LE, "16-bit S-LE PCM"}, {UA_FMT_PCM, 24, AFMT_S24_LE, "24-bit S-LE PCM"}, {UA_FMT_PCM, 32, AFMT_S32_LE, "32-bit S-LE PCM"}, {UA_FMT_ALAW, 8, AFMT_A_LAW, "8-bit A-Law"}, {UA_FMT_MULAW, 8, AFMT_MU_LAW, "8-bit mu-Law"}, {0, 0, 0, NULL} }; static const struct uaudio_format uaudio20_formats[] = { {UA20_FMT_PCM, 8, AFMT_S8, "8-bit S-LE PCM"}, {UA20_FMT_PCM, 16, AFMT_S16_LE, "16-bit S-LE PCM"}, {UA20_FMT_PCM, 24, AFMT_S24_LE, "24-bit S-LE PCM"}, {UA20_FMT_PCM, 32, AFMT_S32_LE, "32-bit S-LE PCM"}, {UA20_FMT_PCM8, 8, AFMT_U8, "8-bit U-LE PCM"}, {UA20_FMT_PCM8, 16, AFMT_U16_LE, "16-bit U-LE PCM"}, {UA20_FMT_PCM8, 24, AFMT_U24_LE, "24-bit U-LE PCM"}, {UA20_FMT_PCM8, 32, AFMT_U32_LE, "32-bit U-LE PCM"}, {UA20_FMT_ALAW, 8, AFMT_A_LAW, "8-bit A-Law"}, {UA20_FMT_MULAW, 8, AFMT_MU_LAW, "8-bit mu-Law"}, {0, 0, 0, NULL} }; #define UAC_OUTPUT 0 #define UAC_INPUT 1 #define UAC_EQUAL 2 #define UAC_RECORD 3 #define UAC_NCLASSES 4 #ifdef USB_DEBUG static const char *uac_names[] = { "outputs", "inputs", "equalization", "record" }; #endif /* prototypes */ static device_probe_t uaudio_probe; static device_attach_t uaudio_attach; static device_detach_t uaudio_detach; static usb_callback_t uaudio_chan_play_callback; static usb_callback_t uaudio_chan_play_sync_callback; static usb_callback_t uaudio_chan_record_callback; static usb_callback_t uaudio_chan_record_sync_callback; static usb_callback_t uaudio_mixer_write_cfg_callback; static usb_callback_t umidi_bulk_read_callback; static usb_callback_t umidi_bulk_write_callback; static usb_callback_t uaudio_hid_rx_callback; static usb_proc_callback_t uaudio_configure_msg; /* ==== USB mixer ==== */ static int uaudio_mixer_sysctl_handler(SYSCTL_HANDLER_ARGS); static void uaudio_mixer_ctl_free(struct uaudio_softc *); static void uaudio_mixer_register_sysctl(struct uaudio_softc *, device_t); static void uaudio_mixer_reload_all(struct uaudio_softc *); static void uaudio_mixer_controls_create_ftu(struct uaudio_softc *); /* ==== USB audio v1.0 ==== */ static void uaudio_mixer_add_mixer(struct uaudio_softc *, const struct uaudio_terminal_node *, int); static void uaudio_mixer_add_selector(struct uaudio_softc *, const struct uaudio_terminal_node *, int); static uint32_t uaudio_mixer_feature_get_bmaControls( const struct usb_audio_feature_unit *, uint8_t); static void uaudio_mixer_add_feature(struct uaudio_softc *, const struct uaudio_terminal_node *, int); static void uaudio_mixer_add_processing_updown(struct uaudio_softc *, const struct uaudio_terminal_node *, int); static void uaudio_mixer_add_processing(struct uaudio_softc *, const struct uaudio_terminal_node *, int); static void uaudio_mixer_add_extension(struct uaudio_softc *, const struct uaudio_terminal_node *, int); static struct usb_audio_cluster uaudio_mixer_get_cluster(uint8_t, const struct uaudio_terminal_node *); static uint16_t uaudio_mixer_determine_class(const struct uaudio_terminal_node *, struct uaudio_mixer_node *); static uint16_t uaudio_mixer_feature_name(const struct uaudio_terminal_node *, struct uaudio_mixer_node *); static void uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node *, const uint8_t *, uint8_t, struct uaudio_search_result *); static const void *uaudio_mixer_verify_desc(const void *, uint32_t); static usb_error_t uaudio_set_speed(struct usb_device *, uint8_t, uint32_t); static int uaudio_mixer_get(struct usb_device *, uint16_t, uint8_t, struct uaudio_mixer_node *); /* ==== USB audio v2.0 ==== */ static void uaudio20_mixer_add_mixer(struct uaudio_softc *, const struct uaudio_terminal_node *, int); static void uaudio20_mixer_add_selector(struct uaudio_softc *, const struct uaudio_terminal_node *, int); static void uaudio20_mixer_add_feature(struct uaudio_softc *, const struct uaudio_terminal_node *, int); static struct usb_audio20_cluster uaudio20_mixer_get_cluster(uint8_t, const struct uaudio_terminal_node *); static uint16_t uaudio20_mixer_determine_class(const struct uaudio_terminal_node *, struct uaudio_mixer_node *); static uint16_t uaudio20_mixer_feature_name(const struct uaudio_terminal_node *, struct uaudio_mixer_node *); static void uaudio20_mixer_find_inputs_sub(struct uaudio_terminal_node *, const uint8_t *, uint8_t, struct uaudio_search_result *); static const void *uaudio20_mixer_verify_desc(const void *, uint32_t); static usb_error_t uaudio20_set_speed(struct usb_device *, uint8_t, uint8_t, uint32_t); /* USB audio v1.0 and v2.0 */ static void uaudio_chan_fill_info_sub(struct uaudio_softc *, struct usb_device *, uint32_t, uint8_t, uint8_t); static void uaudio_chan_fill_info(struct uaudio_softc *, struct usb_device *); static void uaudio_mixer_add_ctl_sub(struct uaudio_softc *, struct uaudio_mixer_node *); static void uaudio_mixer_add_ctl(struct uaudio_softc *, struct uaudio_mixer_node *); static void uaudio_mixer_fill_info(struct uaudio_softc *, struct usb_device *, void *); static void uaudio_mixer_ctl_set(struct uaudio_softc *, struct uaudio_mixer_node *, uint8_t, int32_t val); static int uaudio_mixer_signext(uint8_t, int); static int uaudio_mixer_bsd2value(struct uaudio_mixer_node *, int32_t val); static void uaudio_mixer_init(struct uaudio_softc *); static const struct uaudio_terminal_node *uaudio_mixer_get_input( const struct uaudio_terminal_node *, uint8_t); static const struct uaudio_terminal_node *uaudio_mixer_get_output( const struct uaudio_terminal_node *, uint8_t); static void uaudio_mixer_find_outputs_sub(struct uaudio_terminal_node *, uint8_t, uint8_t, struct uaudio_search_result *); static uint8_t umidi_convert_to_usb(struct umidi_sub_chan *, uint8_t, uint8_t); static struct umidi_sub_chan *umidi_sub_by_fifo(struct usb_fifo *); static void umidi_start_read(struct usb_fifo *); static void umidi_stop_read(struct usb_fifo *); static void umidi_start_write(struct usb_fifo *); static void umidi_stop_write(struct usb_fifo *); static int umidi_open(struct usb_fifo *, int); static int umidi_ioctl(struct usb_fifo *, u_long cmd, void *, int); static void umidi_close(struct usb_fifo *, int); static void umidi_init(device_t dev); static int umidi_probe(device_t dev); static int umidi_detach(device_t dev); static int uaudio_hid_probe(struct uaudio_softc *sc, struct usb_attach_arg *uaa); static void uaudio_hid_detach(struct uaudio_softc *sc); #ifdef USB_DEBUG static void uaudio_chan_dump_ep_desc( const usb_endpoint_descriptor_audio_t *); #endif static const struct usb_config uaudio_cfg_record[UAUDIO_NCHANBUFS + 1] = { [0] = { .type = UE_ISOCHRONOUS, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = 0, /* use "wMaxPacketSize * frames" */ .frames = UAUDIO_NFRAMES, .flags = {.short_xfer_ok = 1,}, .callback = &uaudio_chan_record_callback, }, [1] = { .type = UE_ISOCHRONOUS, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = 0, /* use "wMaxPacketSize * frames" */ .frames = UAUDIO_NFRAMES, .flags = {.short_xfer_ok = 1,}, .callback = &uaudio_chan_record_callback, }, [2] = { .type = UE_ISOCHRONOUS, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = 0, /* use "wMaxPacketSize * frames" */ .frames = 1, .flags = {.no_pipe_ok = 1,.short_xfer_ok = 1,}, .callback = &uaudio_chan_record_sync_callback, }, }; static const struct usb_config uaudio_cfg_play[UAUDIO_NCHANBUFS + 1] = { [0] = { .type = UE_ISOCHRONOUS, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = 0, /* use "wMaxPacketSize * frames" */ .frames = UAUDIO_NFRAMES, .flags = {.short_xfer_ok = 1,}, .callback = &uaudio_chan_play_callback, }, [1] = { .type = UE_ISOCHRONOUS, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = 0, /* use "wMaxPacketSize * frames" */ .frames = UAUDIO_NFRAMES, .flags = {.short_xfer_ok = 1,}, .callback = &uaudio_chan_play_callback, }, [2] = { .type = UE_ISOCHRONOUS, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = 0, /* use "wMaxPacketSize * frames" */ .frames = 1, .flags = {.no_pipe_ok = 1,.short_xfer_ok = 1,}, .callback = &uaudio_chan_play_sync_callback, }, }; static const struct usb_config uaudio_mixer_config[1] = { [0] = { .type = UE_CONTROL, .endpoint = 0x00, /* Control pipe */ .direction = UE_DIR_ANY, .bufsize = (sizeof(struct usb_device_request) + 4), .callback = &uaudio_mixer_write_cfg_callback, .timeout = 1000, /* 1 second */ }, }; static const uint8_t umidi_cmd_to_len[16] = { [0x0] = 0, /* reserved */ [0x1] = 0, /* reserved */ [0x2] = 2, /* bytes */ [0x3] = 3, /* bytes */ [0x4] = 3, /* bytes */ [0x5] = 1, /* bytes */ [0x6] = 2, /* bytes */ [0x7] = 3, /* bytes */ [0x8] = 3, /* bytes */ [0x9] = 3, /* bytes */ [0xA] = 3, /* bytes */ [0xB] = 3, /* bytes */ [0xC] = 2, /* bytes */ [0xD] = 2, /* bytes */ [0xE] = 3, /* bytes */ [0xF] = 1, /* bytes */ }; static const struct usb_config umidi_config[UMIDI_N_TRANSFER] = { [UMIDI_TX_TRANSFER] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = UMIDI_TX_BUFFER, .callback = &umidi_bulk_write_callback, }, [UMIDI_RX_TRANSFER] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = 4, /* bytes */ .flags = {.short_xfer_ok = 1,.proxy_buffer = 1,}, .callback = &umidi_bulk_read_callback, }, }; static const struct usb_config uaudio_hid_config[UAUDIO_HID_N_TRANSFER] = { [UAUDIO_HID_RX_TRANSFER] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = 0, /* use wMaxPacketSize */ .flags = {.short_xfer_ok = 1,}, .callback = &uaudio_hid_rx_callback, }, }; static devclass_t uaudio_devclass; static device_method_t uaudio_methods[] = { DEVMETHOD(device_probe, uaudio_probe), DEVMETHOD(device_attach, uaudio_attach), DEVMETHOD(device_detach, uaudio_detach), DEVMETHOD(device_suspend, bus_generic_suspend), DEVMETHOD(device_resume, bus_generic_resume), DEVMETHOD(device_shutdown, bus_generic_shutdown), DEVMETHOD_END }; static driver_t uaudio_driver = { .name = "uaudio", .methods = uaudio_methods, .size = sizeof(struct uaudio_softc), }; /* The following table is derived from Linux's quirks-table.h */ static const STRUCT_USB_HOST_ID uaudio_vendor_midi[] = { { USB_VPI(USB_VENDOR_YAMAHA, 0x1000, 0) }, /* UX256 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1001, 0) }, /* MU1000 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1002, 0) }, /* MU2000 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1003, 0) }, /* MU500 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1004, 3) }, /* UW500 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1005, 0) }, /* MOTIF6 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1006, 0) }, /* MOTIF7 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1007, 0) }, /* MOTIF8 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1008, 0) }, /* UX96 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1009, 0) }, /* UX16 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x100a, 3) }, /* EOS BX */ { USB_VPI(USB_VENDOR_YAMAHA, 0x100c, 0) }, /* UC-MX */ { USB_VPI(USB_VENDOR_YAMAHA, 0x100d, 0) }, /* UC-KX */ { USB_VPI(USB_VENDOR_YAMAHA, 0x100e, 0) }, /* S08 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x100f, 0) }, /* CLP-150 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1010, 0) }, /* CLP-170 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1011, 0) }, /* P-250 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1012, 0) }, /* TYROS */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1013, 0) }, /* PF-500 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1014, 0) }, /* S90 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1015, 0) }, /* MOTIF-R */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1016, 0) }, /* MDP-5 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1017, 0) }, /* CVP-204 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1018, 0) }, /* CVP-206 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1019, 0) }, /* CVP-208 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x101a, 0) }, /* CVP-210 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x101b, 0) }, /* PSR-1100 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x101c, 0) }, /* PSR-2100 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x101d, 0) }, /* CLP-175 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x101e, 0) }, /* PSR-K1 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x101f, 0) }, /* EZ-J24 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1020, 0) }, /* EZ-250i */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1021, 0) }, /* MOTIF ES 6 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1022, 0) }, /* MOTIF ES 7 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1023, 0) }, /* MOTIF ES 8 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1024, 0) }, /* CVP-301 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1025, 0) }, /* CVP-303 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1026, 0) }, /* CVP-305 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1027, 0) }, /* CVP-307 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1028, 0) }, /* CVP-309 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1029, 0) }, /* CVP-309GP */ { USB_VPI(USB_VENDOR_YAMAHA, 0x102a, 0) }, /* PSR-1500 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x102b, 0) }, /* PSR-3000 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x102e, 0) }, /* ELS-01/01C */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1030, 0) }, /* PSR-295/293 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1031, 0) }, /* DGX-205/203 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1032, 0) }, /* DGX-305 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1033, 0) }, /* DGX-505 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1034, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1035, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1036, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1037, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1038, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1039, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x103a, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x103b, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x103c, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x103d, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x103e, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x103f, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1040, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1041, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1042, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1043, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1044, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1045, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x104e, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x104f, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1050, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1051, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1052, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1053, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1054, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1055, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1056, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1057, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1058, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1059, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x105a, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x105b, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x105c, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x105d, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x1503, 3) }, /* MOX6/MOX8 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x2000, 0) }, /* DGP-7 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x2001, 0) }, /* DGP-5 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x2002, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x2003, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x5000, 0) }, /* CS1D */ { USB_VPI(USB_VENDOR_YAMAHA, 0x5001, 0) }, /* DSP1D */ { USB_VPI(USB_VENDOR_YAMAHA, 0x5002, 0) }, /* DME32 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x5003, 0) }, /* DM2000 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x5004, 0) }, /* 02R96 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x5005, 0) }, /* ACU16-C */ { USB_VPI(USB_VENDOR_YAMAHA, 0x5006, 0) }, /* NHB32-C */ { USB_VPI(USB_VENDOR_YAMAHA, 0x5007, 0) }, /* DM1000 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x5008, 0) }, /* 01V96 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x5009, 0) }, /* SPX2000 */ { USB_VPI(USB_VENDOR_YAMAHA, 0x500a, 0) }, /* PM5D */ { USB_VPI(USB_VENDOR_YAMAHA, 0x500b, 0) }, /* DME64N */ { USB_VPI(USB_VENDOR_YAMAHA, 0x500c, 0) }, /* DME24N */ { USB_VPI(USB_VENDOR_YAMAHA, 0x500d, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x500e, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x500f, 0) }, /* NULL */ { USB_VPI(USB_VENDOR_YAMAHA, 0x7000, 0) }, /* DTX */ { USB_VPI(USB_VENDOR_YAMAHA, 0x7010, 0) }, /* UB99 */ }; static const STRUCT_USB_HOST_ID __used uaudio_devs[] = { /* Generic USB audio class match */ {USB_IFACE_CLASS(UICLASS_AUDIO), USB_IFACE_SUBCLASS(UISUBCLASS_AUDIOCONTROL),}, /* Generic USB MIDI class match */ {USB_IFACE_CLASS(UICLASS_AUDIO), USB_IFACE_SUBCLASS(UISUBCLASS_MIDISTREAM),}, }; static int uaudio_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); /* lookup non-standard device(s) */ if (usbd_lookup_id_by_uaa(uaudio_vendor_midi, sizeof(uaudio_vendor_midi), uaa) == 0) { return (BUS_PROBE_SPECIFIC); } if (uaa->info.bInterfaceClass != UICLASS_AUDIO) { if (uaa->info.bInterfaceClass != UICLASS_VENDOR || usb_test_quirk(uaa, UQ_AU_VENDOR_CLASS) == 0) return (ENXIO); } /* check for AUDIO control interface */ if (uaa->info.bInterfaceSubClass == UISUBCLASS_AUDIOCONTROL) { if (usb_test_quirk(uaa, UQ_BAD_AUDIO)) return (ENXIO); else return (BUS_PROBE_GENERIC); } /* check for MIDI stream */ if (uaa->info.bInterfaceSubClass == UISUBCLASS_MIDISTREAM) { if (usb_test_quirk(uaa, UQ_BAD_MIDI)) return (ENXIO); else return (BUS_PROBE_GENERIC); } return (ENXIO); } static int uaudio_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct uaudio_softc *sc = device_get_softc(dev); struct usb_interface_descriptor *id; usb_error_t err; device_t child; sc->sc_play_chan.priv_sc = sc; sc->sc_rec_chan.priv_sc = sc; sc->sc_udev = uaa->device; sc->sc_mixer_iface_index = uaa->info.bIfaceIndex; sc->sc_mixer_iface_no = uaa->info.bIfaceNum; sc->sc_config_msg[0].hdr.pm_callback = &uaudio_configure_msg; sc->sc_config_msg[0].sc = sc; sc->sc_config_msg[1].hdr.pm_callback = &uaudio_configure_msg; sc->sc_config_msg[1].sc = sc; if (usb_test_quirk(uaa, UQ_AUDIO_SWAP_LR)) sc->sc_uq_audio_swap_lr = 1; if (usb_test_quirk(uaa, UQ_AU_INP_ASYNC)) sc->sc_uq_au_inp_async = 1; if (usb_test_quirk(uaa, UQ_AU_NO_XU)) sc->sc_uq_au_no_xu = 1; if (usb_test_quirk(uaa, UQ_BAD_ADC)) sc->sc_uq_bad_adc = 1; if (usb_test_quirk(uaa, UQ_AU_VENDOR_CLASS)) sc->sc_uq_au_vendor_class = 1; umidi_init(dev); device_set_usb_desc(dev); id = usbd_get_interface_descriptor(uaa->iface); /* must fill mixer info before channel info */ uaudio_mixer_fill_info(sc, uaa->device, id); /* fill channel info */ uaudio_chan_fill_info(sc, uaa->device); DPRINTF("audio rev %d.%02x\n", sc->sc_audio_rev >> 8, sc->sc_audio_rev & 0xff); if (sc->sc_mixer_count == 0) { if (uaa->info.idVendor == USB_VENDOR_MAUDIO && (uaa->info.idProduct == USB_PRODUCT_MAUDIO_FASTTRACKULTRA || uaa->info.idProduct == USB_PRODUCT_MAUDIO_FASTTRACKULTRA8R)) { DPRINTF("Generating mixer descriptors\n"); uaudio_mixer_controls_create_ftu(sc); } } DPRINTF("%d mixer controls\n", sc->sc_mixer_count); if (sc->sc_play_chan.num_alt > 0) { uint8_t x; /* * Need to set a default alternate interface, else * some USB audio devices might go into an infinte * re-enumeration loop: */ err = usbd_set_alt_interface_index(sc->sc_udev, sc->sc_play_chan.usb_alt[0].iface_index, sc->sc_play_chan.usb_alt[0].iface_alt_index); if (err) { DPRINTF("setting of alternate index failed: %s!\n", usbd_errstr(err)); } for (x = 0; x != sc->sc_play_chan.num_alt; x++) { device_printf(dev, "Play: %d Hz, %d ch, %s format, " "2x8ms buffer.\n", sc->sc_play_chan.usb_alt[x].sample_rate, sc->sc_play_chan.usb_alt[x].channels, sc->sc_play_chan.usb_alt[x].p_fmt->description); } } else { device_printf(dev, "No playback.\n"); } if (sc->sc_rec_chan.num_alt > 0) { uint8_t x; /* * Need to set a default alternate interface, else * some USB audio devices might go into an infinte * re-enumeration loop: */ err = usbd_set_alt_interface_index(sc->sc_udev, sc->sc_rec_chan.usb_alt[0].iface_index, sc->sc_rec_chan.usb_alt[0].iface_alt_index); if (err) { DPRINTF("setting of alternate index failed: %s!\n", usbd_errstr(err)); } for (x = 0; x != sc->sc_rec_chan.num_alt; x++) { device_printf(dev, "Record: %d Hz, %d ch, %s format, " "2x8ms buffer.\n", sc->sc_rec_chan.usb_alt[x].sample_rate, sc->sc_rec_chan.usb_alt[x].channels, sc->sc_rec_chan.usb_alt[x].p_fmt->description); } } else { device_printf(dev, "No recording.\n"); } if (sc->sc_midi_chan.valid == 0) { if (usbd_lookup_id_by_uaa(uaudio_vendor_midi, sizeof(uaudio_vendor_midi), uaa) == 0) { sc->sc_midi_chan.iface_index = (uint8_t)uaa->driver_info; sc->sc_midi_chan.iface_alt_index = 0; sc->sc_midi_chan.valid = 1; } } if (sc->sc_midi_chan.valid) { if (umidi_probe(dev)) { goto detach; } device_printf(dev, "MIDI sequencer.\n"); } else { device_printf(dev, "No MIDI sequencer.\n"); } DPRINTF("doing child attach\n"); /* attach the children */ sc->sc_sndcard_func.func = SCF_PCM; /* * Only attach a PCM device if we have a playback, recording * or mixer device present: */ if (sc->sc_play_chan.num_alt > 0 || sc->sc_rec_chan.num_alt > 0 || sc->sc_mix_info) { child = device_add_child(dev, "pcm", -1); if (child == NULL) { DPRINTF("out of memory\n"); goto detach; } device_set_ivars(child, &sc->sc_sndcard_func); } if (bus_generic_attach(dev)) { DPRINTF("child attach failed\n"); goto detach; } if (uaudio_hid_probe(sc, uaa) == 0) { device_printf(dev, "HID volume keys found.\n"); } else { device_printf(dev, "No HID volume keys found.\n"); } /* reload all mixer settings */ uaudio_mixer_reload_all(sc); return (0); /* success */ detach: uaudio_detach(dev); return (ENXIO); } static void uaudio_pcm_setflags(device_t dev, uint32_t flags) { pcm_setflags(dev, pcm_getflags(dev) | flags); } int uaudio_attach_sub(device_t dev, kobj_class_t mixer_class, kobj_class_t chan_class) { struct uaudio_softc *sc = device_get_softc(device_get_parent(dev)); char status[SND_STATUSLEN]; uaudio_mixer_init(sc); if (sc->sc_uq_audio_swap_lr) { DPRINTF("hardware has swapped left and right\n"); /* uaudio_pcm_setflags(dev, SD_F_PSWAPLR); */ } if (!(sc->sc_mix_info & SOUND_MASK_PCM)) { DPRINTF("emulating master volume\n"); /* * Emulate missing pcm mixer controller * through FEEDER_VOLUME */ uaudio_pcm_setflags(dev, SD_F_SOFTPCMVOL); } if (mixer_init(dev, mixer_class, sc)) goto detach; sc->sc_mixer_init = 1; mixer_hwvol_init(dev); snprintf(status, sizeof(status), "at ? %s", PCM_KLDSTRING(snd_uaudio)); if (pcm_register(dev, sc, (sc->sc_play_chan.num_alt > 0) ? 1 : 0, (sc->sc_rec_chan.num_alt > 0) ? 1 : 0)) { goto detach; } uaudio_pcm_setflags(dev, SD_F_MPSAFE); sc->sc_pcm_registered = 1; if (sc->sc_play_chan.num_alt > 0) { pcm_addchan(dev, PCMDIR_PLAY, chan_class, sc); } if (sc->sc_rec_chan.num_alt > 0) { pcm_addchan(dev, PCMDIR_REC, chan_class, sc); } pcm_setstatus(dev, status); uaudio_mixer_register_sysctl(sc, dev); return (0); /* success */ detach: uaudio_detach_sub(dev); return (ENXIO); } int uaudio_detach_sub(device_t dev) { struct uaudio_softc *sc = device_get_softc(device_get_parent(dev)); int error = 0; repeat: if (sc->sc_pcm_registered) { error = pcm_unregister(dev); } else { if (sc->sc_mixer_init) { error = mixer_uninit(dev); } } if (error) { device_printf(dev, "Waiting for sound application to exit!\n"); usb_pause_mtx(NULL, 2 * hz); goto repeat; /* try again */ } return (0); /* success */ } static int uaudio_detach(device_t dev) { struct uaudio_softc *sc = device_get_softc(dev); /* * Stop USB transfers early so that any audio applications * will time out and close opened /dev/dspX.Y device(s), if * any. */ usb_proc_explore_lock(sc->sc_udev); sc->sc_play_chan.operation = CHAN_OP_DRAIN; sc->sc_rec_chan.operation = CHAN_OP_DRAIN; usb_proc_explore_mwait(sc->sc_udev, &sc->sc_config_msg[0], &sc->sc_config_msg[1]); usb_proc_explore_unlock(sc->sc_udev); usbd_transfer_unsetup(sc->sc_play_chan.xfer, UAUDIO_NCHANBUFS + 1); usbd_transfer_unsetup(sc->sc_rec_chan.xfer, UAUDIO_NCHANBUFS + 1); uaudio_hid_detach(sc); if (bus_generic_detach(dev) != 0) { DPRINTF("detach failed!\n"); } sbuf_delete(&sc->sc_sndstat); sc->sc_sndstat_valid = 0; umidi_detach(dev); /* free mixer data */ uaudio_mixer_ctl_free(sc); return (0); } static uint32_t uaudio_get_buffer_size(struct uaudio_chan *ch, uint8_t alt) { struct uaudio_chan_alt *chan_alt = &ch->usb_alt[alt]; /* We use 2 times 8ms of buffer */ uint32_t buf_size = (((chan_alt->sample_rate * (UAUDIO_NFRAMES / 8)) + 1000 - 1) / 1000) * chan_alt->sample_size; return (buf_size); } static void uaudio_configure_msg_sub(struct uaudio_softc *sc, struct uaudio_chan *chan, int dir) { struct uaudio_chan_alt *chan_alt; uint32_t frames; uint32_t buf_size; uint16_t fps; uint8_t set_alt; uint8_t fps_shift; uint8_t operation; usb_error_t err; if (chan->num_alt <= 0) return; DPRINTF("\n"); usb_proc_explore_lock(sc->sc_udev); operation = chan->operation; chan->operation = CHAN_OP_NONE; usb_proc_explore_unlock(sc->sc_udev); mtx_lock(chan->pcm_mtx); if (chan->cur_alt != chan->set_alt) set_alt = chan->set_alt; else set_alt = CHAN_MAX_ALT; mtx_unlock(chan->pcm_mtx); if (set_alt >= chan->num_alt) goto done; chan_alt = chan->usb_alt + set_alt; usbd_transfer_unsetup(chan->xfer, UAUDIO_NCHANBUFS + 1); err = usbd_set_alt_interface_index(sc->sc_udev, chan_alt->iface_index, chan_alt->iface_alt_index); if (err) { DPRINTF("setting of alternate index failed: %s!\n", usbd_errstr(err)); goto error; } /* * Only set the sample rate if the channel reports that it * supports the frequency control. */ if (sc->sc_audio_rev >= UAUDIO_VERSION_30) { /* FALLTHROUGH */ } else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) { unsigned int x; for (x = 0; x != 256; x++) { if (dir == PCMDIR_PLAY) { if (!(sc->sc_mixer_clocks.bit_output[x / 8] & (1 << (x % 8)))) { continue; } } else { if (!(sc->sc_mixer_clocks.bit_input[x / 8] & (1 << (x % 8)))) { continue; } } if (uaudio20_set_speed(sc->sc_udev, sc->sc_mixer_iface_no, x, chan_alt->sample_rate)) { /* * If the endpoint is adaptive setting * the speed may fail. */ DPRINTF("setting of sample rate failed! " "(continuing anyway)\n"); } } } else if (chan_alt->p_sed.v1->bmAttributes & UA_SED_FREQ_CONTROL) { if (uaudio_set_speed(sc->sc_udev, chan_alt->p_ed1->bEndpointAddress, chan_alt->sample_rate)) { /* * If the endpoint is adaptive setting the * speed may fail. */ DPRINTF("setting of sample rate failed! " "(continuing anyway)\n"); } } if (usbd_transfer_setup(sc->sc_udev, &chan_alt->iface_index, chan->xfer, chan_alt->usb_cfg, UAUDIO_NCHANBUFS + 1, chan, chan->pcm_mtx)) { DPRINTF("could not allocate USB transfers!\n"); goto error; } fps = usbd_get_isoc_fps(sc->sc_udev); if (fps < 8000) { /* FULL speed USB */ frames = 8; } else { /* HIGH speed USB */ frames = UAUDIO_NFRAMES; } fps_shift = usbd_xfer_get_fps_shift(chan->xfer[0]); /* down shift number of frames per second, if any */ fps >>= fps_shift; frames >>= fps_shift; /* bytes per frame should not be zero */ chan->bytes_per_frame[0] = ((chan_alt->sample_rate / fps) * chan_alt->sample_size); chan->bytes_per_frame[1] = (((chan_alt->sample_rate + fps - 1) / fps) * chan_alt->sample_size); /* setup data rate dithering, if any */ chan->frames_per_second = fps; chan->sample_rem = chan_alt->sample_rate % fps; chan->sample_curr = 0; chan->frames_per_second = fps; /* compute required buffer size */ buf_size = (chan->bytes_per_frame[1] * frames); if (buf_size > (chan->end - chan->start)) { DPRINTF("buffer size is too big\n"); goto error; } chan->intr_frames = frames; DPRINTF("fps=%d sample_rem=%d\n", (int)fps, (int)chan->sample_rem); if (chan->intr_frames == 0) { DPRINTF("frame shift is too high!\n"); goto error; } mtx_lock(chan->pcm_mtx); chan->cur_alt = set_alt; mtx_unlock(chan->pcm_mtx); done: #if (UAUDIO_NCHANBUFS != 2) #error "please update code" #endif switch (operation) { case CHAN_OP_START: mtx_lock(chan->pcm_mtx); usbd_transfer_start(chan->xfer[0]); usbd_transfer_start(chan->xfer[1]); mtx_unlock(chan->pcm_mtx); break; case CHAN_OP_STOP: mtx_lock(chan->pcm_mtx); usbd_transfer_stop(chan->xfer[0]); usbd_transfer_stop(chan->xfer[1]); mtx_unlock(chan->pcm_mtx); break; default: break; } return; error: usbd_transfer_unsetup(chan->xfer, UAUDIO_NCHANBUFS + 1); mtx_lock(chan->pcm_mtx); chan->cur_alt = CHAN_MAX_ALT; mtx_unlock(chan->pcm_mtx); } static void uaudio_configure_msg(struct usb_proc_msg *pm) { struct uaudio_softc *sc = ((struct uaudio_configure_msg *)pm)->sc; usb_proc_explore_unlock(sc->sc_udev); uaudio_configure_msg_sub(sc, &sc->sc_play_chan, PCMDIR_PLAY); uaudio_configure_msg_sub(sc, &sc->sc_rec_chan, PCMDIR_REC); usb_proc_explore_lock(sc->sc_udev); } /*========================================================================* * AS - Audio Stream - routines *========================================================================*/ #ifdef USB_DEBUG static void uaudio_chan_dump_ep_desc(const usb_endpoint_descriptor_audio_t *ed) { if (ed) { DPRINTF("endpoint=%p bLength=%d bDescriptorType=%d \n" "bEndpointAddress=%d bmAttributes=0x%x \n" "wMaxPacketSize=%d bInterval=%d \n" "bRefresh=%d bSynchAddress=%d\n", ed, ed->bLength, ed->bDescriptorType, ed->bEndpointAddress, ed->bmAttributes, UGETW(ed->wMaxPacketSize), ed->bInterval, UEP_HAS_REFRESH(ed) ? ed->bRefresh : 0, UEP_HAS_SYNCADDR(ed) ? ed->bSynchAddress : 0); } } #endif /* * The following is a workaround for broken no-name USB audio devices * sold by dealextreme called "3D sound". The problem is that the * manufacturer computed wMaxPacketSize is too small to hold the * actual data sent. In other words the device sometimes sends more * data than it actually reports it can send in a single isochronous * packet. */ static void uaudio_record_fix_fs(usb_endpoint_descriptor_audio_t *ep, uint32_t xps, uint32_t add) { uint32_t mps; mps = UGETW(ep->wMaxPacketSize); /* * If the device indicates it can send more data than what the * sample rate indicates, we apply the workaround. */ if (mps > xps) { /* allow additional data */ xps += add; /* check against the maximum USB 1.x length */ if (xps > 1023) xps = 1023; /* check if we should do an update */ if (mps < xps) { /* simply update the wMaxPacketSize field */ USETW(ep->wMaxPacketSize, xps); DPRINTF("Workaround: Updated wMaxPacketSize " "from %d to %d bytes.\n", (int)mps, (int)xps); } } } static usb_error_t uaudio20_check_rate(struct usb_device *udev, uint8_t iface_no, uint8_t clockid, uint32_t rate) { struct usb_device_request req; usb_error_t error; uint8_t data[255]; uint16_t actlen; uint16_t rates; uint16_t x; DPRINTFN(6, "ifaceno=%d clockid=%d rate=%u\n", iface_no, clockid, rate); req.bmRequestType = UT_READ_CLASS_INTERFACE; req.bRequest = UA20_CS_RANGE; USETW2(req.wValue, UA20_CS_SAM_FREQ_CONTROL, 0); USETW2(req.wIndex, clockid, iface_no); USETW(req.wLength, 255); error = usbd_do_request_flags(udev, NULL, &req, data, USB_SHORT_XFER_OK, &actlen, USB_DEFAULT_TIMEOUT); if (error != 0 || actlen < 2) return (USB_ERR_INVAL); rates = data[0] | (data[1] << 8); actlen = (actlen - 2) / 12; if (rates > actlen) { DPRINTF("Too many rates\n"); rates = actlen; } for (x = 0; x != rates; x++) { uint32_t min = UGETDW(data + 2 + (12 * x)); uint32_t max = UGETDW(data + 6 + (12 * x)); uint32_t res = UGETDW(data + 10 + (12 * x)); if (res == 0) { DPRINTF("Zero residue\n"); res = 1; } if (min > max) { DPRINTF("Swapped max and min\n"); uint32_t temp; temp = min; min = max; max = temp; } if (rate >= min && rate <= max && (((rate - min) % res) == 0)) { return (0); } } return (USB_ERR_INVAL); } static void uaudio_chan_fill_info_sub(struct uaudio_softc *sc, struct usb_device *udev, uint32_t rate, uint8_t channels, uint8_t bit_resolution) { struct usb_descriptor *desc = NULL; union uaudio_asid asid = { NULL }; union uaudio_asf1d asf1d = { NULL }; union uaudio_sed sed = { NULL }; struct usb_midi_streaming_endpoint_descriptor *msid = NULL; usb_endpoint_descriptor_audio_t *ed1 = NULL; const struct usb_audio_control_descriptor *acdp = NULL; struct usb_config_descriptor *cd = usbd_get_config_descriptor(udev); struct usb_interface_descriptor *id; const struct uaudio_format *p_fmt = NULL; struct uaudio_chan *chan; struct uaudio_chan_alt *chan_alt; uint32_t format; uint16_t curidx = 0xFFFF; uint16_t lastidx = 0xFFFF; uint16_t alt_index = 0; uint16_t audio_rev = 0; uint16_t x; uint8_t ep_dir; uint8_t bChannels; uint8_t bBitResolution; uint8_t audio_if = 0; uint8_t midi_if = 0; uint8_t uma_if_class; while ((desc = usb_desc_foreach(cd, desc))) { if ((desc->bDescriptorType == UDESC_INTERFACE) && (desc->bLength >= sizeof(*id))) { id = (void *)desc; if (id->bInterfaceNumber != lastidx) { lastidx = id->bInterfaceNumber; curidx++; alt_index = 0; } else { alt_index++; } if ((!(sc->sc_hid.flags & UAUDIO_HID_VALID)) && (id->bInterfaceClass == UICLASS_HID) && (id->bInterfaceSubClass == 0) && (id->bInterfaceProtocol == 0) && (alt_index == 0) && usbd_get_iface(udev, curidx) != NULL) { DPRINTF("Found HID interface at %d\n", curidx); sc->sc_hid.flags |= UAUDIO_HID_VALID; sc->sc_hid.iface_index = curidx; } uma_if_class = ((id->bInterfaceClass == UICLASS_AUDIO) || ((id->bInterfaceClass == UICLASS_VENDOR) && (sc->sc_uq_au_vendor_class != 0))); if ((uma_if_class != 0) && (id->bInterfaceSubClass == UISUBCLASS_AUDIOSTREAM)) { audio_if = 1; } else { audio_if = 0; } if ((uma_if_class != 0) && (id->bInterfaceSubClass == UISUBCLASS_MIDISTREAM)) { /* * XXX could allow multiple MIDI interfaces */ midi_if = 1; if ((sc->sc_midi_chan.valid == 0) && (usbd_get_iface(udev, curidx) != NULL)) { sc->sc_midi_chan.iface_index = curidx; sc->sc_midi_chan.iface_alt_index = alt_index; sc->sc_midi_chan.valid = 1; } } else { midi_if = 0; } asid.v1 = NULL; asf1d.v1 = NULL; ed1 = NULL; sed.v1 = NULL; } if (audio_if == 0) { if (midi_if == 0) { if ((acdp == NULL) && (desc->bDescriptorType == UDESC_CS_INTERFACE) && (desc->bDescriptorSubtype == UDESCSUB_AC_HEADER) && (desc->bLength >= sizeof(*acdp))) { acdp = (void *)desc; audio_rev = UGETW(acdp->bcdADC); } } else { msid = (void *)desc; /* get the maximum number of embedded jacks in use, if any */ if (msid->bLength >= sizeof(*msid) && msid->bDescriptorType == UDESC_CS_ENDPOINT && msid->bDescriptorSubtype == MS_GENERAL && msid->bNumEmbMIDIJack > sc->sc_midi_chan.max_emb_jack) { sc->sc_midi_chan.max_emb_jack = msid->bNumEmbMIDIJack; } } /* * Don't collect any USB audio descriptors if * this is not an USB audio stream interface. */ continue; } if ((acdp != NULL) && (desc->bDescriptorType == UDESC_CS_INTERFACE) && (desc->bDescriptorSubtype == AS_GENERAL) && (asid.v1 == NULL)) { if (audio_rev >= UAUDIO_VERSION_30) { /* FALLTHROUGH */ } else if (audio_rev >= UAUDIO_VERSION_20) { if (desc->bLength >= sizeof(*asid.v2)) { asid.v2 = (void *)desc; } } else { if (desc->bLength >= sizeof(*asid.v1)) { asid.v1 = (void *)desc; } } } if ((acdp != NULL) && (desc->bDescriptorType == UDESC_CS_INTERFACE) && (desc->bDescriptorSubtype == FORMAT_TYPE) && (asf1d.v1 == NULL)) { if (audio_rev >= UAUDIO_VERSION_30) { /* FALLTHROUGH */ } else if (audio_rev >= UAUDIO_VERSION_20) { if (desc->bLength >= sizeof(*asf1d.v2)) asf1d.v2 = (void *)desc; } else { if (desc->bLength >= sizeof(*asf1d.v1)) { asf1d.v1 = (void *)desc; if (asf1d.v1->bFormatType != FORMAT_TYPE_I) { DPRINTFN(11, "ignored bFormatType = %d\n", asf1d.v1->bFormatType); asf1d.v1 = NULL; continue; } if (desc->bLength < (sizeof(*asf1d.v1) + ((asf1d.v1->bSamFreqType == 0) ? 6 : (asf1d.v1->bSamFreqType * 3)))) { DPRINTFN(11, "invalid descriptor, " "too short\n"); asf1d.v1 = NULL; continue; } } } } if ((desc->bDescriptorType == UDESC_ENDPOINT) && (desc->bLength >= UEP_MINSIZE) && (ed1 == NULL)) { ed1 = (void *)desc; if (UE_GET_XFERTYPE(ed1->bmAttributes) != UE_ISOCHRONOUS) { ed1 = NULL; continue; } } if ((acdp != NULL) && (desc->bDescriptorType == UDESC_CS_ENDPOINT) && (desc->bDescriptorSubtype == AS_GENERAL) && (sed.v1 == NULL)) { if (audio_rev >= UAUDIO_VERSION_30) { /* FALLTHROUGH */ } else if (audio_rev >= UAUDIO_VERSION_20) { if (desc->bLength >= sizeof(*sed.v2)) sed.v2 = (void *)desc; } else { if (desc->bLength >= sizeof(*sed.v1)) sed.v1 = (void *)desc; } } if (asid.v1 == NULL || asf1d.v1 == NULL || ed1 == NULL || sed.v1 == NULL) { /* need more descriptors */ continue; } ep_dir = UE_GET_DIR(ed1->bEndpointAddress); /* We ignore sync endpoint information until further. */ if (audio_rev >= UAUDIO_VERSION_30) { goto next_ep; } else if (audio_rev >= UAUDIO_VERSION_20) { uint32_t dwFormat; dwFormat = UGETDW(asid.v2->bmFormats); bChannels = asid.v2->bNrChannels; bBitResolution = asf1d.v2->bSubslotSize * 8; if ((bChannels != channels) || (bBitResolution != bit_resolution)) { DPRINTF("Wrong number of channels\n"); goto next_ep; } for (p_fmt = uaudio20_formats; p_fmt->wFormat != 0; p_fmt++) { if ((p_fmt->wFormat & dwFormat) && (p_fmt->bPrecision == bBitResolution)) break; } if (p_fmt->wFormat == 0) { DPRINTF("Unsupported audio format\n"); goto next_ep; } for (x = 0; x != 256; x++) { if (ep_dir == UE_DIR_OUT) { if (!(sc->sc_mixer_clocks.bit_output[x / 8] & (1 << (x % 8)))) { continue; } } else { if (!(sc->sc_mixer_clocks.bit_input[x / 8] & (1 << (x % 8)))) { continue; } } DPRINTF("Checking clock ID=%d\n", x); if (uaudio20_check_rate(udev, sc->sc_mixer_iface_no, x, rate)) { DPRINTF("Unsupported sampling " "rate, id=%d\n", x); goto next_ep; } } } else { uint16_t wFormat; wFormat = UGETW(asid.v1->wFormatTag); bChannels = UAUDIO_MAX_CHAN(asf1d.v1->bNrChannels); bBitResolution = asf1d.v1->bSubFrameSize * 8; if (asf1d.v1->bSamFreqType == 0) { DPRINTFN(16, "Sample rate: %d-%dHz\n", UA_SAMP_LO(asf1d.v1), UA_SAMP_HI(asf1d.v1)); if ((rate >= UA_SAMP_LO(asf1d.v1)) && (rate <= UA_SAMP_HI(asf1d.v1))) goto found_rate; } else { for (x = 0; x < asf1d.v1->bSamFreqType; x++) { DPRINTFN(16, "Sample rate = %dHz\n", UA_GETSAMP(asf1d.v1, x)); if (rate == UA_GETSAMP(asf1d.v1, x)) goto found_rate; } } goto next_ep; found_rate: for (p_fmt = uaudio10_formats; p_fmt->wFormat != 0; p_fmt++) { if ((p_fmt->wFormat == wFormat) && (p_fmt->bPrecision == bBitResolution)) break; } if (p_fmt->wFormat == 0) { DPRINTF("Unsupported audio format\n"); goto next_ep; } if ((bChannels != channels) || (bBitResolution != bit_resolution)) { DPRINTF("Wrong number of channels\n"); goto next_ep; } } chan = (ep_dir == UE_DIR_IN) ? &sc->sc_rec_chan : &sc->sc_play_chan; if (usbd_get_iface(udev, curidx) == NULL) { DPRINTF("Interface is not valid\n"); goto next_ep; } if (chan->num_alt == CHAN_MAX_ALT) { DPRINTF("Too many alternate settings\n"); goto next_ep; } chan->set_alt = 0; chan->cur_alt = CHAN_MAX_ALT; chan_alt = &chan->usb_alt[chan->num_alt++]; #ifdef USB_DEBUG uaudio_chan_dump_ep_desc(ed1); #endif DPRINTF("Sample rate = %dHz, channels = %d, " "bits = %d, format = %s\n", rate, channels, bit_resolution, p_fmt->description); chan_alt->sample_rate = rate; chan_alt->p_asf1d = asf1d; chan_alt->p_ed1 = ed1; chan_alt->p_fmt = p_fmt; chan_alt->p_sed = sed; chan_alt->iface_index = curidx; chan_alt->iface_alt_index = alt_index; if (UEP_HAS_SYNCADDR(ed1) && ed1->bSynchAddress != 0) { DPRINTF("Sync endpoint will be used, if present\n"); chan_alt->enable_sync = 1; } else { DPRINTF("Sync endpoint will not be used\n"); chan_alt->enable_sync = 0; } usbd_set_parent_iface(sc->sc_udev, curidx, sc->sc_mixer_iface_index); if (ep_dir == UE_DIR_IN) chan_alt->usb_cfg = uaudio_cfg_record; else chan_alt->usb_cfg = uaudio_cfg_play; chan_alt->sample_size = (UAUDIO_MAX_CHAN(channels) * p_fmt->bPrecision) / 8; chan_alt->channels = channels; if (ep_dir == UE_DIR_IN && usbd_get_speed(udev) == USB_SPEED_FULL) { uaudio_record_fix_fs(ed1, chan_alt->sample_size * (rate / 1000), chan_alt->sample_size * (rate / 4000)); } /* setup play/record format */ format = chan_alt->p_fmt->freebsd_fmt; switch (chan_alt->channels) { case 2: /* stereo */ format = SND_FORMAT(format, 2, 0); break; case 1: /* mono */ format = SND_FORMAT(format, 1, 0); break; default: /* surround and more */ format = feeder_matrix_default_format( SND_FORMAT(format, chan_alt->channels, 0)); break; } /* check if format is not supported */ if (format == 0) { DPRINTF("The selected audio format is not supported\n"); chan->num_alt--; goto next_ep; } if (chan->num_alt > 1) { /* we only accumulate one format at different sample rates */ if (chan->pcm_format[0] != format) { DPRINTF("Multiple formats is not supported\n"); chan->num_alt--; goto next_ep; } /* ignore if duplicate sample rate entry */ if (rate == chan->usb_alt[chan->num_alt - 2].sample_rate) { DPRINTF("Duplicate sample rate detected\n"); chan->num_alt--; goto next_ep; } } chan->pcm_cap.fmtlist = chan->pcm_format; chan->pcm_cap.fmtlist[0] = format; if (rate < chan->pcm_cap.minspeed || chan->pcm_cap.minspeed == 0) chan->pcm_cap.minspeed = rate; if (rate > chan->pcm_cap.maxspeed || chan->pcm_cap.maxspeed == 0) chan->pcm_cap.maxspeed = rate; if (sc->sc_sndstat_valid != 0) { sbuf_printf(&sc->sc_sndstat, "\n\t" "mode %d.%d:(%s) %dch, %dbit, %s, %dHz", curidx, alt_index, (ep_dir == UE_DIR_IN) ? "input" : "output", channels, p_fmt->bPrecision, p_fmt->description, rate); } next_ep: sed.v1 = NULL; ed1 = NULL; } } /* This structure defines all the supported rates. */ static const uint32_t uaudio_rate_list[CHAN_MAX_ALT] = { 384000, 352800, 192000, 176400, 96000, 88200, 88000, 80000, 72000, 64000, 56000, 48000, 44100, 40000, 32000, 24000, 22050, 16000, 11025, 8000, 0 }; static void uaudio_chan_fill_info(struct uaudio_softc *sc, struct usb_device *udev) { uint32_t rate = uaudio_default_rate; uint8_t z; uint8_t bits = uaudio_default_bits; uint8_t y; uint8_t channels = uaudio_default_channels; uint8_t x; bits -= (bits % 8); if ((bits == 0) || (bits > 32)) { /* set a valid value */ bits = 32; } if (channels == 0) { switch (usbd_get_speed(udev)) { case USB_SPEED_LOW: case USB_SPEED_FULL: /* * Due to high bandwidth usage and problems * with HIGH-speed split transactions we * disable surround setups on FULL-speed USB * by default */ channels = 4; break; default: channels = 16; break; } } else if (channels > 16) { channels = 16; } if (sbuf_new(&sc->sc_sndstat, NULL, 4096, SBUF_AUTOEXTEND)) { sc->sc_sndstat_valid = 1; } /* try to search for a valid config */ for (x = channels; x; x--) { for (y = bits; y; y -= 8) { /* try user defined rate, if any */ if (rate != 0) uaudio_chan_fill_info_sub(sc, udev, rate, x, y); /* try find a matching rate, if any */ for (z = 0; uaudio_rate_list[z]; z++) uaudio_chan_fill_info_sub(sc, udev, uaudio_rate_list[z], x, y); } } if (sc->sc_sndstat_valid) sbuf_finish(&sc->sc_sndstat); } static void uaudio_chan_play_sync_callback(struct usb_xfer *xfer, usb_error_t error) { struct uaudio_chan *ch = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint64_t sample_rate = ch->usb_alt[ch->cur_alt].sample_rate; uint8_t buf[4]; uint64_t temp; int len; int actlen; int nframes; usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(6, "transferred %d bytes\n", actlen); if (nframes == 0) break; len = usbd_xfer_frame_len(xfer, 0); if (len == 0) break; if (len > sizeof(buf)) len = sizeof(buf); memset(buf, 0, sizeof(buf)); pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, buf, len); temp = UGETDW(buf); DPRINTF("Value = 0x%08x\n", (int)temp); /* auto-detect SYNC format */ if (len == 4) temp &= 0x0fffffff; /* check for no data */ if (temp == 0) break; /* correctly scale value */ temp = (temp * 125ULL) - 64; /* auto adjust */ while (temp < (sample_rate - (sample_rate / 4))) temp *= 2; while (temp > (sample_rate + (sample_rate / 2))) temp /= 2; /* compare */ DPRINTF("Comparing %d < %d\n", (int)temp, (int)sample_rate); if (temp == sample_rate) ch->last_sync_state = UAUDIO_SYNC_NONE; else if (temp > sample_rate) ch->last_sync_state = UAUDIO_SYNC_MORE; else ch->last_sync_state = UAUDIO_SYNC_LESS; break; case USB_ST_SETUP: usbd_xfer_set_frames(xfer, 1); usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_framelen(xfer)); usbd_transfer_submit(xfer); break; default: /* Error */ break; } } static void uaudio_chan_play_callback(struct usb_xfer *xfer, usb_error_t error) { struct uaudio_chan *ch = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint32_t sample_size = ch->usb_alt[ch->cur_alt].sample_size; uint32_t mfl; uint32_t total; uint32_t blockcount; uint32_t n; uint32_t offset; int actlen; int sumlen; usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL); if (ch->end == ch->start) { DPRINTF("no buffer!\n"); return; } switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: tr_transferred: if (actlen < sumlen) { DPRINTF("short transfer, " "%d of %d bytes\n", actlen, sumlen); } chn_intr(ch->pcm_ch); /* start SYNC transfer, if any */ if (ch->usb_alt[ch->cur_alt].enable_sync != 0) { if ((ch->last_sync_time++ & 7) == 0) usbd_transfer_start(ch->xfer[UAUDIO_NCHANBUFS]); } case USB_ST_SETUP: mfl = usbd_xfer_max_framelen(xfer); if (ch->bytes_per_frame[1] > mfl) { DPRINTF("bytes per transfer, %d, " "exceeds maximum, %d!\n", ch->bytes_per_frame[1], mfl); break; } blockcount = ch->intr_frames; /* setup number of frames */ usbd_xfer_set_frames(xfer, blockcount); /* reset total length */ total = 0; /* setup frame lengths */ for (n = 0; n != blockcount; n++) { uint32_t frame_len; ch->sample_curr += ch->sample_rem; if (ch->sample_curr >= ch->frames_per_second) { ch->sample_curr -= ch->frames_per_second; frame_len = ch->bytes_per_frame[1]; } else { frame_len = ch->bytes_per_frame[0]; } if (n == (blockcount - 1)) { switch (ch->last_sync_state) { case UAUDIO_SYNC_MORE: DPRINTFN(6, "sending one sample more\n"); if ((frame_len + sample_size) <= mfl) frame_len += sample_size; ch->last_sync_state = UAUDIO_SYNC_NONE; break; case UAUDIO_SYNC_LESS: DPRINTFN(6, "sending one sample less\n"); if (frame_len >= sample_size) frame_len -= sample_size; ch->last_sync_state = UAUDIO_SYNC_NONE; break; default: break; } } usbd_xfer_set_frame_len(xfer, n, frame_len); total += frame_len; } DPRINTFN(6, "transfer %d bytes\n", total); offset = 0; pc = usbd_xfer_get_frame(xfer, 0); while (total > 0) { n = (ch->end - ch->cur); if (n > total) { n = total; } usbd_copy_in(pc, offset, ch->cur, n); total -= n; ch->cur += n; offset += n; if (ch->cur >= ch->end) { ch->cur = ch->start; } } usbd_transfer_submit(xfer); break; default: /* Error */ if (error == USB_ERR_CANCELLED) { break; } goto tr_transferred; } } static void uaudio_chan_record_sync_callback(struct usb_xfer *xfer, usb_error_t error) { /* TODO */ } static void uaudio_chan_record_callback(struct usb_xfer *xfer, usb_error_t error) { struct uaudio_chan *ch = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint32_t offset0; uint32_t offset1; uint32_t mfl; int m; int n; int len; int actlen; int nframes; int blockcount; usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes); mfl = usbd_xfer_max_framelen(xfer); if (ch->end == ch->start) { DPRINTF("no buffer!\n"); return; } switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(6, "transferred %d bytes\n", actlen); offset0 = 0; pc = usbd_xfer_get_frame(xfer, 0); for (n = 0; n != nframes; n++) { offset1 = offset0; len = usbd_xfer_frame_len(xfer, n); while (len > 0) { m = (ch->end - ch->cur); if (m > len) m = len; usbd_copy_out(pc, offset1, ch->cur, m); len -= m; offset1 += m; ch->cur += m; if (ch->cur >= ch->end) { ch->cur = ch->start; } } offset0 += mfl; } chn_intr(ch->pcm_ch); case USB_ST_SETUP: tr_setup: blockcount = ch->intr_frames; usbd_xfer_set_frames(xfer, blockcount); for (n = 0; n < blockcount; n++) { usbd_xfer_set_frame_len(xfer, n, mfl); } usbd_transfer_submit(xfer); break; default: /* Error */ if (error == USB_ERR_CANCELLED) { break; } goto tr_setup; } } void * uaudio_chan_init(struct uaudio_softc *sc, struct snd_dbuf *b, struct pcm_channel *c, int dir) { struct uaudio_chan *ch = ((dir == PCMDIR_PLAY) ? &sc->sc_play_chan : &sc->sc_rec_chan); uint32_t buf_size; uint8_t x; /* store mutex and PCM channel */ ch->pcm_ch = c; ch->pcm_mtx = c->lock; /* compute worst case buffer */ buf_size = 0; for (x = 0; x != ch->num_alt; x++) { uint32_t temp = uaudio_get_buffer_size(ch, x); if (temp > buf_size) buf_size = temp; } /* allow double buffering */ buf_size *= 2; DPRINTF("Worst case buffer is %d bytes\n", (int)buf_size); ch->buf = malloc(buf_size, M_DEVBUF, M_WAITOK | M_ZERO); if (ch->buf == NULL) goto error; if (sndbuf_setup(b, ch->buf, buf_size) != 0) goto error; ch->start = ch->buf; ch->end = ch->buf + buf_size; ch->cur = ch->buf; ch->pcm_buf = b; ch->max_buf = buf_size; if (ch->pcm_mtx == NULL) { DPRINTF("ERROR: PCM channels does not have a mutex!\n"); goto error; } return (ch); error: uaudio_chan_free(ch); return (NULL); } int uaudio_chan_free(struct uaudio_chan *ch) { if (ch->buf != NULL) { free(ch->buf, M_DEVBUF); ch->buf = NULL; } usbd_transfer_unsetup(ch->xfer, UAUDIO_NCHANBUFS + 1); ch->num_alt = 0; return (0); } int uaudio_chan_set_param_blocksize(struct uaudio_chan *ch, uint32_t blocksize) { uint32_t temp = 2 * uaudio_get_buffer_size(ch, ch->set_alt); sndbuf_setup(ch->pcm_buf, ch->buf, temp); ch->start = ch->buf; ch->end = ch->buf + temp; ch->cur = ch->buf; return (temp / 2); } int uaudio_chan_set_param_fragments(struct uaudio_chan *ch, uint32_t blocksize, uint32_t blockcount) { return (1); } int uaudio_chan_set_param_speed(struct uaudio_chan *ch, uint32_t speed) { uint8_t x; for (x = 0; x < ch->num_alt; x++) { if (ch->usb_alt[x].sample_rate < speed) { /* sample rate is too low */ break; } } if (x != 0) x--; ch->set_alt = x; DPRINTF("Selecting alt %d\n", (int)x); return (ch->usb_alt[x].sample_rate); } int uaudio_chan_getptr(struct uaudio_chan *ch) { return (ch->cur - ch->start); } struct pcmchan_caps * uaudio_chan_getcaps(struct uaudio_chan *ch) { return (&ch->pcm_cap); } static struct pcmchan_matrix uaudio_chan_matrix_swap_2_0 = { .id = SND_CHN_MATRIX_DRV, .channels = 2, .ext = 0, .map = { /* Right */ [0] = { .type = SND_CHN_T_FR, .members = SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FC | SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BR | SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SR }, /* Left */ [1] = { .type = SND_CHN_T_FL, .members = SND_CHN_T_MASK_FL | SND_CHN_T_MASK_FC | SND_CHN_T_MASK_LF | SND_CHN_T_MASK_BL | SND_CHN_T_MASK_BC | SND_CHN_T_MASK_SL }, [2] = { .type = SND_CHN_T_MAX, .members = 0 } }, .mask = SND_CHN_T_MASK_FR | SND_CHN_T_MASK_FL, .offset = { 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } }; struct pcmchan_matrix * uaudio_chan_getmatrix(struct uaudio_chan *ch, uint32_t format) { struct uaudio_softc *sc; sc = ch->priv_sc; if (sc != NULL && sc->sc_uq_audio_swap_lr != 0 && AFMT_CHANNEL(format) == 2) return (&uaudio_chan_matrix_swap_2_0); return (feeder_matrix_format_map(format)); } int uaudio_chan_set_param_format(struct uaudio_chan *ch, uint32_t format) { DPRINTF("Selecting format 0x%08x\n", (unsigned int)format); return (0); } int uaudio_chan_start(struct uaudio_chan *ch) { struct uaudio_softc *sc = ch->priv_sc; int do_start = 0; usb_proc_explore_lock(sc->sc_udev); if (ch->operation != CHAN_OP_DRAIN) { if (ch->cur_alt == ch->set_alt && ch->operation == CHAN_OP_NONE) { /* save doing the explore task */ do_start = 1; } else { ch->operation = CHAN_OP_START; (void)usb_proc_explore_msignal(sc->sc_udev, &sc->sc_config_msg[0], &sc->sc_config_msg[1]); } } usb_proc_explore_unlock(sc->sc_udev); if (do_start) { usbd_transfer_start(ch->xfer[0]); usbd_transfer_start(ch->xfer[1]); } return (0); } int uaudio_chan_stop(struct uaudio_chan *ch) { struct uaudio_softc *sc = ch->priv_sc; int do_stop = 0; usb_proc_explore_lock(sc->sc_udev); if (ch->operation != CHAN_OP_DRAIN) { if (ch->cur_alt == ch->set_alt && ch->operation == CHAN_OP_NONE) { /* save doing the explore task */ do_stop = 1; } else { ch->operation = CHAN_OP_STOP; (void)usb_proc_explore_msignal(sc->sc_udev, &sc->sc_config_msg[0], &sc->sc_config_msg[1]); } } usb_proc_explore_unlock(sc->sc_udev); if (do_stop) { usbd_transfer_stop(ch->xfer[0]); usbd_transfer_stop(ch->xfer[1]); } return (0); } /*========================================================================* * AC - Audio Controller - routines *========================================================================*/ static int uaudio_mixer_sysctl_handler(SYSCTL_HANDLER_ARGS) { struct uaudio_softc *sc; struct uaudio_mixer_node *pmc; int hint; int error; int temp = 0; int chan = 0; sc = (struct uaudio_softc *)oidp->oid_arg1; hint = oidp->oid_arg2; if (sc->sc_mixer_lock == NULL) return (ENXIO); /* lookup mixer node */ mtx_lock(sc->sc_mixer_lock); for (pmc = sc->sc_mixer_root; pmc != NULL; pmc = pmc->next) { for (chan = 0; chan != (int)pmc->nchan; chan++) { if (pmc->wValue[chan] != -1 && pmc->wValue[chan] == hint) { temp = pmc->wData[chan]; goto found; } } } found: mtx_unlock(sc->sc_mixer_lock); error = sysctl_handle_int(oidp, &temp, 0, req); if (error != 0 || req->newptr == NULL) return (error); /* update mixer value */ mtx_lock(sc->sc_mixer_lock); if (pmc != NULL && temp >= pmc->minval && temp <= pmc->maxval) { pmc->wData[chan] = temp; pmc->update[(chan / 8)] |= (1 << (chan % 8)); /* start the transfer, if not already started */ usbd_transfer_start(sc->sc_mixer_xfer[0]); } mtx_unlock(sc->sc_mixer_lock); return (0); } static void uaudio_mixer_ctl_free(struct uaudio_softc *sc) { struct uaudio_mixer_node *p_mc; while ((p_mc = sc->sc_mixer_root) != NULL) { sc->sc_mixer_root = p_mc->next; free(p_mc, M_USBDEV); } } static void uaudio_mixer_register_sysctl(struct uaudio_softc *sc, device_t dev) { struct uaudio_mixer_node *pmc; struct sysctl_oid *mixer_tree; struct sysctl_oid *control_tree; char buf[32]; int chan; int n; mixer_tree = SYSCTL_ADD_NODE(device_get_sysctl_ctx(dev), SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "mixer", CTLFLAG_RD, NULL, ""); if (mixer_tree == NULL) return; for (n = 0, pmc = sc->sc_mixer_root; pmc != NULL; pmc = pmc->next, n++) { for (chan = 0; chan < pmc->nchan; chan++) { if (pmc->nchan > 1) { snprintf(buf, sizeof(buf), "%s_%d_%d", pmc->name, n, chan); } else { snprintf(buf, sizeof(buf), "%s_%d", pmc->name, n); } control_tree = SYSCTL_ADD_NODE(device_get_sysctl_ctx(dev), SYSCTL_CHILDREN(mixer_tree), OID_AUTO, buf, CTLFLAG_RD, NULL, "Mixer control nodes"); if (control_tree == NULL) continue; SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev), SYSCTL_CHILDREN(control_tree), - OID_AUTO, "val", CTLTYPE_INT | CTLFLAG_RW, sc, + OID_AUTO, "val", CTLTYPE_INT | CTLFLAG_RWTUN, sc, pmc->wValue[chan], uaudio_mixer_sysctl_handler, "I", "Current value"); SYSCTL_ADD_INT(device_get_sysctl_ctx(dev), SYSCTL_CHILDREN(control_tree), OID_AUTO, "min", CTLFLAG_RD, 0, pmc->minval, "Minimum value"); SYSCTL_ADD_INT(device_get_sysctl_ctx(dev), SYSCTL_CHILDREN(control_tree), OID_AUTO, "max", CTLFLAG_RD, 0, pmc->maxval, "Maximum value"); SYSCTL_ADD_STRING(device_get_sysctl_ctx(dev), SYSCTL_CHILDREN(control_tree), OID_AUTO, "desc", CTLFLAG_RD, pmc->desc, 0, "Description"); } } } /* M-Audio FastTrack Ultra Mixer Description */ /* Origin: Linux USB Audio driver */ static void uaudio_mixer_controls_create_ftu(struct uaudio_softc *sc) { int chx; int chy; memset(&MIX(sc), 0, sizeof(MIX(sc))); MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no); MIX(sc).wValue[0] = MAKE_WORD(8, 0); MIX(sc).class = UAC_OUTPUT; MIX(sc).type = MIX_UNSIGNED_16; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; MIX(sc).name = "effect"; MIX(sc).minval = 0; MIX(sc).maxval = 7; MIX(sc).mul = 7; MIX(sc).nchan = 1; MIX(sc).update[0] = 1; strlcpy(MIX(sc).desc, "Room1,2,3,Hall1,2,Plate,Delay,Echo", sizeof(MIX(sc).desc)); uaudio_mixer_add_ctl_sub(sc, &MIX(sc)); memset(&MIX(sc), 0, sizeof(MIX(sc))); MIX(sc).wIndex = MAKE_WORD(5, sc->sc_mixer_iface_no); for (chx = 0; chx != 8; chx++) { for (chy = 0; chy != 8; chy++) { MIX(sc).wValue[0] = MAKE_WORD(chx + 1, chy + 1); MIX(sc).type = MIX_SIGNED_16; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; MIX(sc).name = "mix_rec"; MIX(sc).nchan = 1; MIX(sc).update[0] = 1; MIX(sc).val_default = 0; snprintf(MIX(sc).desc, sizeof(MIX(sc).desc), "AIn%d - Out%d Record Volume", chy + 1, chx + 1); uaudio_mixer_add_ctl(sc, &MIX(sc)); MIX(sc).wValue[0] = MAKE_WORD(chx + 1, chy + 1 + 8); MIX(sc).type = MIX_SIGNED_16; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; MIX(sc).name = "mix_play"; MIX(sc).nchan = 1; MIX(sc).update[0] = 1; MIX(sc).val_default = (chx == chy) ? 2 : 0; snprintf(MIX(sc).desc, sizeof(MIX(sc).desc), "DIn%d - Out%d Playback Volume", chy + 1, chx + 1); uaudio_mixer_add_ctl(sc, &MIX(sc)); } } memset(&MIX(sc), 0, sizeof(MIX(sc))); MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no); MIX(sc).wValue[0] = MAKE_WORD(2, 0); MIX(sc).class = UAC_OUTPUT; MIX(sc).type = MIX_SIGNED_8; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; MIX(sc).name = "effect_vol"; MIX(sc).nchan = 1; MIX(sc).update[0] = 1; MIX(sc).minval = 0; MIX(sc).maxval = 0x7f; MIX(sc).mul = 0x7f; MIX(sc).nchan = 1; MIX(sc).update[0] = 1; strlcpy(MIX(sc).desc, "Effect Volume", sizeof(MIX(sc).desc)); uaudio_mixer_add_ctl_sub(sc, &MIX(sc)); memset(&MIX(sc), 0, sizeof(MIX(sc))); MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no); MIX(sc).wValue[0] = MAKE_WORD(3, 0); MIX(sc).class = UAC_OUTPUT; MIX(sc).type = MIX_SIGNED_16; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; MIX(sc).name = "effect_dur"; MIX(sc).nchan = 1; MIX(sc).update[0] = 1; MIX(sc).minval = 0; MIX(sc).maxval = 0x7f00; MIX(sc).mul = 0x7f00; MIX(sc).nchan = 1; MIX(sc).update[0] = 1; strlcpy(MIX(sc).desc, "Effect Duration", sizeof(MIX(sc).desc)); uaudio_mixer_add_ctl_sub(sc, &MIX(sc)); memset(&MIX(sc), 0, sizeof(MIX(sc))); MIX(sc).wIndex = MAKE_WORD(6, sc->sc_mixer_iface_no); MIX(sc).wValue[0] = MAKE_WORD(4, 0); MIX(sc).class = UAC_OUTPUT; MIX(sc).type = MIX_SIGNED_8; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; MIX(sc).name = "effect_fb"; MIX(sc).nchan = 1; MIX(sc).update[0] = 1; MIX(sc).minval = 0; MIX(sc).maxval = 0x7f; MIX(sc).mul = 0x7f; MIX(sc).nchan = 1; MIX(sc).update[0] = 1; strlcpy(MIX(sc).desc, "Effect Feedback Volume", sizeof(MIX(sc).desc)); uaudio_mixer_add_ctl_sub(sc, &MIX(sc)); memset(&MIX(sc), 0, sizeof(MIX(sc))); MIX(sc).wIndex = MAKE_WORD(7, sc->sc_mixer_iface_no); for (chy = 0; chy != 4; chy++) { MIX(sc).wValue[0] = MAKE_WORD(7, chy + 1); MIX(sc).type = MIX_SIGNED_16; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; MIX(sc).name = "effect_ret"; MIX(sc).nchan = 1; MIX(sc).update[0] = 1; snprintf(MIX(sc).desc, sizeof(MIX(sc).desc), "Effect Return %d Volume", chy + 1); uaudio_mixer_add_ctl(sc, &MIX(sc)); } memset(&MIX(sc), 0, sizeof(MIX(sc))); MIX(sc).wIndex = MAKE_WORD(5, sc->sc_mixer_iface_no); for (chy = 0; chy != 8; chy++) { MIX(sc).wValue[0] = MAKE_WORD(9, chy + 1); MIX(sc).type = MIX_SIGNED_16; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; MIX(sc).name = "effect_send"; MIX(sc).nchan = 1; MIX(sc).update[0] = 1; snprintf(MIX(sc).desc, sizeof(MIX(sc).desc), "Effect Send AIn%d Volume", chy + 1); uaudio_mixer_add_ctl(sc, &MIX(sc)); MIX(sc).wValue[0] = MAKE_WORD(9, chy + 1 + 8); MIX(sc).type = MIX_SIGNED_16; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; MIX(sc).name = "effect_send"; MIX(sc).nchan = 1; MIX(sc).update[0] = 1; snprintf(MIX(sc).desc, sizeof(MIX(sc).desc), "Effect Send DIn%d Volume", chy + 1); uaudio_mixer_add_ctl(sc, &MIX(sc)); } } static void uaudio_mixer_reload_all(struct uaudio_softc *sc) { struct uaudio_mixer_node *pmc; int chan; if (sc->sc_mixer_lock == NULL) return; mtx_lock(sc->sc_mixer_lock); for (pmc = sc->sc_mixer_root; pmc != NULL; pmc = pmc->next) { /* use reset defaults for non-oss controlled settings */ if (pmc->ctl == SOUND_MIXER_NRDEVICES) continue; for (chan = 0; chan < pmc->nchan; chan++) pmc->update[chan / 8] |= (1 << (chan % 8)); } usbd_transfer_start(sc->sc_mixer_xfer[0]); /* start HID volume keys, if any */ usbd_transfer_start(sc->sc_hid.xfer[0]); mtx_unlock(sc->sc_mixer_lock); } static void uaudio_mixer_add_ctl_sub(struct uaudio_softc *sc, struct uaudio_mixer_node *mc) { struct uaudio_mixer_node *p_mc_new = malloc(sizeof(*p_mc_new), M_USBDEV, M_WAITOK); int ch; if (p_mc_new != NULL) { memcpy(p_mc_new, mc, sizeof(*p_mc_new)); p_mc_new->next = sc->sc_mixer_root; sc->sc_mixer_root = p_mc_new; sc->sc_mixer_count++; /* set default value for all channels */ for (ch = 0; ch < p_mc_new->nchan; ch++) { switch (p_mc_new->val_default) { case 1: /* 50% */ p_mc_new->wData[ch] = (p_mc_new->maxval + p_mc_new->minval) / 2; break; case 2: /* 100% */ p_mc_new->wData[ch] = p_mc_new->maxval; break; default: /* 0% */ p_mc_new->wData[ch] = p_mc_new->minval; break; } } } else { DPRINTF("out of memory\n"); } } static void uaudio_mixer_add_ctl(struct uaudio_softc *sc, struct uaudio_mixer_node *mc) { int32_t res; if (mc->class < UAC_NCLASSES) { DPRINTF("adding %s.%d\n", uac_names[mc->class], mc->ctl); } else { DPRINTF("adding %d\n", mc->ctl); } if (mc->type == MIX_ON_OFF) { mc->minval = 0; mc->maxval = 1; } else if (mc->type == MIX_SELECTOR) { } else { /* determine min and max values */ mc->minval = uaudio_mixer_get(sc->sc_udev, sc->sc_audio_rev, GET_MIN, mc); mc->maxval = uaudio_mixer_get(sc->sc_udev, sc->sc_audio_rev, GET_MAX, mc); /* check if max and min was swapped */ if (mc->maxval < mc->minval) { res = mc->maxval; mc->maxval = mc->minval; mc->minval = res; } /* compute value range */ mc->mul = mc->maxval - mc->minval; if (mc->mul == 0) mc->mul = 1; /* compute value alignment */ res = uaudio_mixer_get(sc->sc_udev, sc->sc_audio_rev, GET_RES, mc); DPRINTF("Resolution = %d\n", (int)res); } uaudio_mixer_add_ctl_sub(sc, mc); #ifdef USB_DEBUG if (uaudio_debug > 2) { uint8_t i; for (i = 0; i < mc->nchan; i++) { DPRINTF("[mix] wValue=%04x\n", mc->wValue[0]); } DPRINTF("[mix] wIndex=%04x type=%d ctl='%d' " "min=%d max=%d\n", mc->wIndex, mc->type, mc->ctl, mc->minval, mc->maxval); } #endif } static void uaudio_mixer_add_mixer(struct uaudio_softc *sc, const struct uaudio_terminal_node *iot, int id) { const struct usb_audio_mixer_unit_0 *d0 = iot[id].u.mu_v1; const struct usb_audio_mixer_unit_1 *d1; uint32_t bno; /* bit number */ uint32_t p; /* bit number accumulator */ uint32_t mo; /* matching outputs */ uint32_t mc; /* matching channels */ uint32_t ichs; /* input channels */ uint32_t ochs; /* output channels */ uint32_t c; uint32_t chs; /* channels */ uint32_t i; uint32_t o; DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n", d0->bUnitId, d0->bNrInPins); /* compute the number of input channels */ ichs = 0; for (i = 0; i < d0->bNrInPins; i++) { ichs += uaudio_mixer_get_cluster( d0->baSourceId[i], iot).bNrChannels; } d1 = (const void *)(d0->baSourceId + d0->bNrInPins); /* and the number of output channels */ ochs = d1->bNrChannels; DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs); memset(&MIX(sc), 0, sizeof(MIX(sc))); MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no); uaudio_mixer_determine_class(&iot[id], &MIX(sc)); MIX(sc).type = MIX_SIGNED_16; if (uaudio_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL) return; for (p = i = 0; i < d0->bNrInPins; i++) { chs = uaudio_mixer_get_cluster( d0->baSourceId[i], iot).bNrChannels; mc = 0; for (c = 0; c < chs; c++) { mo = 0; for (o = 0; o < ochs; o++) { bno = ((p + c) * ochs) + o; if (BIT_TEST(d1->bmControls, bno)) mo++; } if (mo == 1) mc++; } if ((mc == chs) && (chs <= MIX_MAX_CHAN)) { /* repeat bit-scan */ mc = 0; for (c = 0; c < chs; c++) { for (o = 0; o < ochs; o++) { bno = ((p + c) * ochs) + o; if (BIT_TEST(d1->bmControls, bno)) MIX(sc).wValue[mc++] = MAKE_WORD(p + c + 1, o + 1); } } MIX(sc).nchan = chs; uaudio_mixer_add_ctl(sc, &MIX(sc)); } p += chs; } } static void uaudio20_mixer_add_mixer(struct uaudio_softc *sc, const struct uaudio_terminal_node *iot, int id) { const struct usb_audio20_mixer_unit_0 *d0 = iot[id].u.mu_v2; const struct usb_audio20_mixer_unit_1 *d1; uint32_t bno; /* bit number */ uint32_t p; /* bit number accumulator */ uint32_t mo; /* matching outputs */ uint32_t mc; /* matching channels */ uint32_t ichs; /* input channels */ uint32_t ochs; /* output channels */ uint32_t c; uint32_t chs; /* channels */ uint32_t i; uint32_t o; DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n", d0->bUnitId, d0->bNrInPins); /* compute the number of input channels */ ichs = 0; for (i = 0; i < d0->bNrInPins; i++) { ichs += uaudio20_mixer_get_cluster( d0->baSourceId[i], iot).bNrChannels; } d1 = (const void *)(d0->baSourceId + d0->bNrInPins); /* and the number of output channels */ ochs = d1->bNrChannels; DPRINTFN(3, "ichs=%d ochs=%d\n", ichs, ochs); memset(&MIX(sc), 0, sizeof(MIX(sc))); MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no); uaudio20_mixer_determine_class(&iot[id], &MIX(sc)); MIX(sc).type = MIX_SIGNED_16; if (uaudio20_mixer_verify_desc(d0, ((ichs * ochs) + 7) / 8) == NULL) return; for (p = i = 0; i < d0->bNrInPins; i++) { chs = uaudio20_mixer_get_cluster( d0->baSourceId[i], iot).bNrChannels; mc = 0; for (c = 0; c < chs; c++) { mo = 0; for (o = 0; o < ochs; o++) { bno = ((p + c) * ochs) + o; if (BIT_TEST(d1->bmControls, bno)) mo++; } if (mo == 1) mc++; } if ((mc == chs) && (chs <= MIX_MAX_CHAN)) { /* repeat bit-scan */ mc = 0; for (c = 0; c < chs; c++) { for (o = 0; o < ochs; o++) { bno = ((p + c) * ochs) + o; if (BIT_TEST(d1->bmControls, bno)) MIX(sc).wValue[mc++] = MAKE_WORD(p + c + 1, o + 1); } } MIX(sc).nchan = chs; uaudio_mixer_add_ctl(sc, &MIX(sc)); } p += chs; } } static void uaudio_mixer_add_selector(struct uaudio_softc *sc, const struct uaudio_terminal_node *iot, int id) { const struct usb_audio_selector_unit *d = iot[id].u.su_v1; uint16_t i; DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n", d->bUnitId, d->bNrInPins); if (d->bNrInPins == 0) return; memset(&MIX(sc), 0, sizeof(MIX(sc))); MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no); MIX(sc).wValue[0] = MAKE_WORD(0, 0); uaudio_mixer_determine_class(&iot[id], &MIX(sc)); MIX(sc).nchan = 1; MIX(sc).type = MIX_SELECTOR; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; MIX(sc).minval = 1; MIX(sc).maxval = d->bNrInPins; MIX(sc).name = "selector"; i = d->baSourceId[d->bNrInPins]; if (i == 0 || usbd_req_get_string_any(sc->sc_udev, NULL, MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) { MIX(sc).desc[0] = 0; } if (MIX(sc).maxval > MAX_SELECTOR_INPUT_PIN) { MIX(sc).maxval = MAX_SELECTOR_INPUT_PIN; } MIX(sc).mul = (MIX(sc).maxval - MIX(sc).minval); for (i = 0; i < MAX_SELECTOR_INPUT_PIN; i++) { MIX(sc).slctrtype[i] = SOUND_MIXER_NRDEVICES; } for (i = 0; i < MIX(sc).maxval; i++) { MIX(sc).slctrtype[i] = uaudio_mixer_feature_name( &iot[d->baSourceId[i]], &MIX(sc)); } MIX(sc).class = 0; /* not used */ uaudio_mixer_add_ctl(sc, &MIX(sc)); } static void uaudio20_mixer_add_selector(struct uaudio_softc *sc, const struct uaudio_terminal_node *iot, int id) { const struct usb_audio20_selector_unit *d = iot[id].u.su_v2; uint16_t i; DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n", d->bUnitId, d->bNrInPins); if (d->bNrInPins == 0) return; memset(&MIX(sc), 0, sizeof(MIX(sc))); MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no); MIX(sc).wValue[0] = MAKE_WORD(0, 0); uaudio20_mixer_determine_class(&iot[id], &MIX(sc)); MIX(sc).nchan = 1; MIX(sc).type = MIX_SELECTOR; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; MIX(sc).minval = 1; MIX(sc).maxval = d->bNrInPins; MIX(sc).name = "selector"; i = d->baSourceId[d->bNrInPins]; if (i == 0 || usbd_req_get_string_any(sc->sc_udev, NULL, MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) { MIX(sc).desc[0] = 0; } if (MIX(sc).maxval > MAX_SELECTOR_INPUT_PIN) MIX(sc).maxval = MAX_SELECTOR_INPUT_PIN; MIX(sc).mul = (MIX(sc).maxval - MIX(sc).minval); for (i = 0; i < MAX_SELECTOR_INPUT_PIN; i++) MIX(sc).slctrtype[i] = SOUND_MIXER_NRDEVICES; for (i = 0; i < MIX(sc).maxval; i++) { MIX(sc).slctrtype[i] = uaudio20_mixer_feature_name( &iot[d->baSourceId[i]], &MIX(sc)); } MIX(sc).class = 0; /* not used */ uaudio_mixer_add_ctl(sc, &MIX(sc)); } static uint32_t uaudio_mixer_feature_get_bmaControls(const struct usb_audio_feature_unit *d, uint8_t i) { uint32_t temp = 0; uint32_t offset = (i * d->bControlSize); if (d->bControlSize > 0) { temp |= d->bmaControls[offset]; if (d->bControlSize > 1) { temp |= d->bmaControls[offset + 1] << 8; if (d->bControlSize > 2) { temp |= d->bmaControls[offset + 2] << 16; if (d->bControlSize > 3) { temp |= d->bmaControls[offset + 3] << 24; } } } } return (temp); } static void uaudio_mixer_add_feature(struct uaudio_softc *sc, const struct uaudio_terminal_node *iot, int id) { const struct usb_audio_feature_unit *d = iot[id].u.fu_v1; uint32_t fumask; uint32_t mmask; uint32_t cmask; uint16_t mixernumber; uint8_t nchan; uint8_t chan; uint8_t ctl; uint8_t i; if (d->bControlSize == 0) return; memset(&MIX(sc), 0, sizeof(MIX(sc))); nchan = (d->bLength - 7) / d->bControlSize; mmask = uaudio_mixer_feature_get_bmaControls(d, 0); cmask = 0; if (nchan == 0) return; /* figure out what we can control */ for (chan = 1; chan < nchan; chan++) { DPRINTFN(10, "chan=%d mask=%x\n", chan, uaudio_mixer_feature_get_bmaControls(d, chan)); cmask |= uaudio_mixer_feature_get_bmaControls(d, chan); } if (nchan > MIX_MAX_CHAN) { nchan = MIX_MAX_CHAN; } MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no); i = d->bmaControls[d->bControlSize]; if (i == 0 || usbd_req_get_string_any(sc->sc_udev, NULL, MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) { MIX(sc).desc[0] = 0; } for (ctl = 1; ctl <= LOUDNESS_CONTROL; ctl++) { fumask = FU_MASK(ctl); DPRINTFN(5, "ctl=%d fumask=0x%04x\n", ctl, fumask); if (mmask & fumask) { MIX(sc).nchan = 1; MIX(sc).wValue[0] = MAKE_WORD(ctl, 0); } else if (cmask & fumask) { MIX(sc).nchan = nchan - 1; for (i = 1; i < nchan; i++) { if (uaudio_mixer_feature_get_bmaControls(d, i) & fumask) MIX(sc).wValue[i - 1] = MAKE_WORD(ctl, i); else MIX(sc).wValue[i - 1] = -1; } } else { continue; } mixernumber = uaudio_mixer_feature_name(&iot[id], &MIX(sc)); switch (ctl) { case MUTE_CONTROL: MIX(sc).type = MIX_ON_OFF; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; MIX(sc).name = "mute"; break; case VOLUME_CONTROL: MIX(sc).type = MIX_SIGNED_16; MIX(sc).ctl = mixernumber; MIX(sc).name = "vol"; break; case BASS_CONTROL: MIX(sc).type = MIX_SIGNED_8; MIX(sc).ctl = SOUND_MIXER_BASS; MIX(sc).name = "bass"; break; case MID_CONTROL: MIX(sc).type = MIX_SIGNED_8; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; /* XXXXX */ MIX(sc).name = "mid"; break; case TREBLE_CONTROL: MIX(sc).type = MIX_SIGNED_8; MIX(sc).ctl = SOUND_MIXER_TREBLE; MIX(sc).name = "treble"; break; case GRAPHIC_EQUALIZER_CONTROL: continue; /* XXX don't add anything */ case AGC_CONTROL: MIX(sc).type = MIX_ON_OFF; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; /* XXXXX */ MIX(sc).name = "agc"; break; case DELAY_CONTROL: MIX(sc).type = MIX_UNSIGNED_16; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; /* XXXXX */ MIX(sc).name = "delay"; break; case BASS_BOOST_CONTROL: MIX(sc).type = MIX_ON_OFF; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; /* XXXXX */ MIX(sc).name = "boost"; break; case LOUDNESS_CONTROL: MIX(sc).type = MIX_ON_OFF; MIX(sc).ctl = SOUND_MIXER_LOUD; /* Is this correct ? */ MIX(sc).name = "loudness"; break; default: MIX(sc).type = MIX_UNKNOWN; break; } if (MIX(sc).type != MIX_UNKNOWN) uaudio_mixer_add_ctl(sc, &MIX(sc)); } } static void uaudio20_mixer_add_feature(struct uaudio_softc *sc, const struct uaudio_terminal_node *iot, int id) { const struct usb_audio20_feature_unit *d = iot[id].u.fu_v2; uint32_t ctl; uint32_t mmask; uint32_t cmask; uint16_t mixernumber; uint8_t nchan; uint8_t chan; uint8_t i; uint8_t what; if (UGETDW(d->bmaControls[0]) == 0) return; memset(&MIX(sc), 0, sizeof(MIX(sc))); nchan = (d->bLength - 6) / 4; mmask = UGETDW(d->bmaControls[0]); cmask = 0; if (nchan == 0) return; /* figure out what we can control */ for (chan = 1; chan < nchan; chan++) cmask |= UGETDW(d->bmaControls[chan]); if (nchan > MIX_MAX_CHAN) nchan = MIX_MAX_CHAN; MIX(sc).wIndex = MAKE_WORD(d->bUnitId, sc->sc_mixer_iface_no); i = d->bmaControls[nchan][0]; if (i == 0 || usbd_req_get_string_any(sc->sc_udev, NULL, MIX(sc).desc, sizeof(MIX(sc).desc), i) != 0) { MIX(sc).desc[0] = 0; } for (ctl = 3; ctl != 0; ctl <<= 2) { mixernumber = uaudio20_mixer_feature_name(&iot[id], &MIX(sc)); switch (ctl) { case (3 << 0): MIX(sc).type = MIX_ON_OFF; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; MIX(sc).name = "mute"; what = MUTE_CONTROL; break; case (3 << 2): MIX(sc).type = MIX_SIGNED_16; MIX(sc).ctl = mixernumber; MIX(sc).name = "vol"; what = VOLUME_CONTROL; break; case (3 << 4): MIX(sc).type = MIX_SIGNED_8; MIX(sc).ctl = SOUND_MIXER_BASS; MIX(sc).name = "bass"; what = BASS_CONTROL; break; case (3 << 6): MIX(sc).type = MIX_SIGNED_8; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; /* XXXXX */ MIX(sc).name = "mid"; what = MID_CONTROL; break; case (3 << 8): MIX(sc).type = MIX_SIGNED_8; MIX(sc).ctl = SOUND_MIXER_TREBLE; MIX(sc).name = "treble"; what = TREBLE_CONTROL; break; case (3 << 12): MIX(sc).type = MIX_ON_OFF; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; /* XXXXX */ MIX(sc).name = "agc"; what = AGC_CONTROL; break; case (3 << 14): MIX(sc).type = MIX_UNSIGNED_16; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; /* XXXXX */ MIX(sc).name = "delay"; what = DELAY_CONTROL; break; case (3 << 16): MIX(sc).type = MIX_ON_OFF; MIX(sc).ctl = SOUND_MIXER_NRDEVICES; /* XXXXX */ MIX(sc).name = "boost"; what = BASS_BOOST_CONTROL; break; case (3 << 18): MIX(sc).type = MIX_ON_OFF; MIX(sc).ctl = SOUND_MIXER_LOUD; /* Is this correct ? */ MIX(sc).name = "loudness"; what = LOUDNESS_CONTROL; break; case (3 << 20): MIX(sc).type = MIX_SIGNED_16; MIX(sc).ctl = mixernumber; MIX(sc).name = "igain"; what = INPUT_GAIN_CONTROL; break; case (3 << 22): MIX(sc).type = MIX_SIGNED_16; MIX(sc).ctl = mixernumber; MIX(sc).name = "igainpad"; what = INPUT_GAIN_PAD_CONTROL; break; default: continue; } if ((mmask & ctl) == ctl) { MIX(sc).nchan = 1; MIX(sc).wValue[0] = MAKE_WORD(what, 0); } else if ((cmask & ctl) == ctl) { MIX(sc).nchan = nchan - 1; for (i = 1; i < nchan; i++) { if ((UGETDW(d->bmaControls[i]) & ctl) == ctl) MIX(sc).wValue[i - 1] = MAKE_WORD(what, i); else MIX(sc).wValue[i - 1] = -1; } } else { continue; } if (MIX(sc).type != MIX_UNKNOWN) uaudio_mixer_add_ctl(sc, &MIX(sc)); } } static void uaudio_mixer_add_processing_updown(struct uaudio_softc *sc, const struct uaudio_terminal_node *iot, int id) { const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu_v1; const struct usb_audio_processing_unit_1 *d1 = (const void *)(d0->baSourceId + d0->bNrInPins); const struct usb_audio_processing_unit_updown *ud = (const void *)(d1->bmControls + d1->bControlSize); uint8_t i; if (uaudio_mixer_verify_desc(d0, sizeof(*ud)) == NULL) { return; } if (uaudio_mixer_verify_desc(d0, sizeof(*ud) + (2 * ud->bNrModes)) == NULL) { return; } DPRINTFN(3, "bUnitId=%d bNrModes=%d\n", d0->bUnitId, ud->bNrModes); if (!(d1->bmControls[0] & UA_PROC_MASK(UD_MODE_SELECT_CONTROL))) { DPRINTF("no mode select\n"); return; } memset(&MIX(sc), 0, sizeof(MIX(sc))); MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no); MIX(sc).nchan = 1; MIX(sc).wValue[0] = MAKE_WORD(UD_MODE_SELECT_CONTROL, 0); uaudio_mixer_determine_class(&iot[id], &MIX(sc)); MIX(sc).type = MIX_ON_OFF; /* XXX */ for (i = 0; i < ud->bNrModes; i++) { DPRINTFN(3, "i=%d bm=0x%x\n", i, UGETW(ud->waModes[i])); /* XXX */ } uaudio_mixer_add_ctl(sc, &MIX(sc)); } static void uaudio_mixer_add_processing(struct uaudio_softc *sc, const struct uaudio_terminal_node *iot, int id) { const struct usb_audio_processing_unit_0 *d0 = iot[id].u.pu_v1; const struct usb_audio_processing_unit_1 *d1 = (const void *)(d0->baSourceId + d0->bNrInPins); uint16_t ptype; memset(&MIX(sc), 0, sizeof(MIX(sc))); ptype = UGETW(d0->wProcessType); DPRINTFN(3, "wProcessType=%d bUnitId=%d " "bNrInPins=%d\n", ptype, d0->bUnitId, d0->bNrInPins); if (d1->bControlSize == 0) { return; } if (d1->bmControls[0] & UA_PROC_ENABLE_MASK) { MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no); MIX(sc).nchan = 1; MIX(sc).wValue[0] = MAKE_WORD(XX_ENABLE_CONTROL, 0); uaudio_mixer_determine_class(&iot[id], &MIX(sc)); MIX(sc).type = MIX_ON_OFF; uaudio_mixer_add_ctl(sc, &MIX(sc)); } switch (ptype) { case UPDOWNMIX_PROCESS: uaudio_mixer_add_processing_updown(sc, iot, id); break; case DOLBY_PROLOGIC_PROCESS: case P3D_STEREO_EXTENDER_PROCESS: case REVERBATION_PROCESS: case CHORUS_PROCESS: case DYN_RANGE_COMP_PROCESS: default: DPRINTF("unit %d, type=%d is not implemented\n", d0->bUnitId, ptype); break; } } static void uaudio_mixer_add_extension(struct uaudio_softc *sc, const struct uaudio_terminal_node *iot, int id) { const struct usb_audio_extension_unit_0 *d0 = iot[id].u.eu_v1; const struct usb_audio_extension_unit_1 *d1 = (const void *)(d0->baSourceId + d0->bNrInPins); DPRINTFN(3, "bUnitId=%d bNrInPins=%d\n", d0->bUnitId, d0->bNrInPins); if (sc->sc_uq_au_no_xu) { return; } if (d1->bControlSize == 0) { return; } if (d1->bmControls[0] & UA_EXT_ENABLE_MASK) { memset(&MIX(sc), 0, sizeof(MIX(sc))); MIX(sc).wIndex = MAKE_WORD(d0->bUnitId, sc->sc_mixer_iface_no); MIX(sc).nchan = 1; MIX(sc).wValue[0] = MAKE_WORD(UA_EXT_ENABLE, 0); uaudio_mixer_determine_class(&iot[id], &MIX(sc)); MIX(sc).type = MIX_ON_OFF; uaudio_mixer_add_ctl(sc, &MIX(sc)); } } static const void * uaudio_mixer_verify_desc(const void *arg, uint32_t len) { const struct usb_audio_mixer_unit_1 *d1; const struct usb_audio_extension_unit_1 *e1; const struct usb_audio_processing_unit_1 *u1; union { const struct usb_descriptor *desc; const struct usb_audio_input_terminal *it; const struct usb_audio_output_terminal *ot; const struct usb_audio_mixer_unit_0 *mu; const struct usb_audio_selector_unit *su; const struct usb_audio_feature_unit *fu; const struct usb_audio_processing_unit_0 *pu; const struct usb_audio_extension_unit_0 *eu; } u; u.desc = arg; if (u.desc == NULL) { goto error; } if (u.desc->bDescriptorType != UDESC_CS_INTERFACE) { goto error; } switch (u.desc->bDescriptorSubtype) { case UDESCSUB_AC_INPUT: len += sizeof(*u.it); break; case UDESCSUB_AC_OUTPUT: len += sizeof(*u.ot); break; case UDESCSUB_AC_MIXER: len += sizeof(*u.mu); if (u.desc->bLength < len) { goto error; } len += u.mu->bNrInPins; if (u.desc->bLength < len) { goto error; } d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins); len += sizeof(*d1); break; case UDESCSUB_AC_SELECTOR: len += sizeof(*u.su); if (u.desc->bLength < len) { goto error; } len += u.su->bNrInPins + 1; break; case UDESCSUB_AC_FEATURE: len += sizeof(*u.fu) + 1; if (u.desc->bLength < len) goto error; len += u.fu->bControlSize; break; case UDESCSUB_AC_PROCESSING: len += sizeof(*u.pu); if (u.desc->bLength < len) { goto error; } len += u.pu->bNrInPins; if (u.desc->bLength < len) { goto error; } u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins); len += sizeof(*u1); if (u.desc->bLength < len) { goto error; } len += u1->bControlSize; break; case UDESCSUB_AC_EXTENSION: len += sizeof(*u.eu); if (u.desc->bLength < len) { goto error; } len += u.eu->bNrInPins; if (u.desc->bLength < len) { goto error; } e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins); len += sizeof(*e1); if (u.desc->bLength < len) { goto error; } len += e1->bControlSize; break; default: goto error; } if (u.desc->bLength < len) { goto error; } return (u.desc); error: if (u.desc) { DPRINTF("invalid descriptor, type=%d, " "sub_type=%d, len=%d of %d bytes\n", u.desc->bDescriptorType, u.desc->bDescriptorSubtype, u.desc->bLength, len); } return (NULL); } static const void * uaudio20_mixer_verify_desc(const void *arg, uint32_t len) { const struct usb_audio20_mixer_unit_1 *d1; const struct usb_audio20_extension_unit_1 *e1; const struct usb_audio20_processing_unit_1 *u1; const struct usb_audio20_clock_selector_unit_1 *c1; union { const struct usb_descriptor *desc; const struct usb_audio20_clock_source_unit *csrc; const struct usb_audio20_clock_selector_unit_0 *csel; const struct usb_audio20_clock_multiplier_unit *cmul; const struct usb_audio20_input_terminal *it; const struct usb_audio20_output_terminal *ot; const struct usb_audio20_mixer_unit_0 *mu; const struct usb_audio20_selector_unit *su; const struct usb_audio20_feature_unit *fu; const struct usb_audio20_sample_rate_unit *ru; const struct usb_audio20_processing_unit_0 *pu; const struct usb_audio20_extension_unit_0 *eu; const struct usb_audio20_effect_unit *ef; } u; u.desc = arg; if (u.desc == NULL) goto error; if (u.desc->bDescriptorType != UDESC_CS_INTERFACE) goto error; switch (u.desc->bDescriptorSubtype) { case UDESCSUB_AC_INPUT: len += sizeof(*u.it); break; case UDESCSUB_AC_OUTPUT: len += sizeof(*u.ot); break; case UDESCSUB_AC_MIXER: len += sizeof(*u.mu); if (u.desc->bLength < len) goto error; len += u.mu->bNrInPins; if (u.desc->bLength < len) goto error; d1 = (const void *)(u.mu->baSourceId + u.mu->bNrInPins); len += sizeof(*d1) + d1->bNrChannels; break; case UDESCSUB_AC_SELECTOR: len += sizeof(*u.su); if (u.desc->bLength < len) goto error; len += u.su->bNrInPins + 1; break; case UDESCSUB_AC_FEATURE: len += sizeof(*u.fu) + 1; break; case UDESCSUB_AC_EFFECT: len += sizeof(*u.ef) + 4; break; case UDESCSUB_AC_PROCESSING_V2: len += sizeof(*u.pu); if (u.desc->bLength < len) goto error; len += u.pu->bNrInPins; if (u.desc->bLength < len) goto error; u1 = (const void *)(u.pu->baSourceId + u.pu->bNrInPins); len += sizeof(*u1); break; case UDESCSUB_AC_EXTENSION_V2: len += sizeof(*u.eu); if (u.desc->bLength < len) goto error; len += u.eu->bNrInPins; if (u.desc->bLength < len) goto error; e1 = (const void *)(u.eu->baSourceId + u.eu->bNrInPins); len += sizeof(*e1); break; case UDESCSUB_AC_CLOCK_SRC: len += sizeof(*u.csrc); break; case UDESCSUB_AC_CLOCK_SEL: len += sizeof(*u.csel); if (u.desc->bLength < len) goto error; len += u.csel->bNrInPins; if (u.desc->bLength < len) goto error; c1 = (const void *)(u.csel->baCSourceId + u.csel->bNrInPins); len += sizeof(*c1); break; case UDESCSUB_AC_CLOCK_MUL: len += sizeof(*u.cmul); break; case UDESCSUB_AC_SAMPLE_RT: len += sizeof(*u.ru); break; default: goto error; } if (u.desc->bLength < len) goto error; return (u.desc); error: if (u.desc) { DPRINTF("invalid descriptor, type=%d, " "sub_type=%d, len=%d of %d bytes\n", u.desc->bDescriptorType, u.desc->bDescriptorSubtype, u.desc->bLength, len); } return (NULL); } static struct usb_audio_cluster uaudio_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot) { struct usb_audio_cluster r; const struct usb_descriptor *dp; uint8_t i; for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) { /* avoid infinite loops */ dp = iot[id].u.desc; if (dp == NULL) { goto error; } switch (dp->bDescriptorSubtype) { case UDESCSUB_AC_INPUT: r.bNrChannels = iot[id].u.it_v1->bNrChannels; r.wChannelConfig[0] = iot[id].u.it_v1->wChannelConfig[0]; r.wChannelConfig[1] = iot[id].u.it_v1->wChannelConfig[1]; r.iChannelNames = iot[id].u.it_v1->iChannelNames; goto done; case UDESCSUB_AC_OUTPUT: id = iot[id].u.ot_v1->bSourceId; break; case UDESCSUB_AC_MIXER: r = *(const struct usb_audio_cluster *) &iot[id].u.mu_v1->baSourceId[ iot[id].u.mu_v1->bNrInPins]; goto done; case UDESCSUB_AC_SELECTOR: if (iot[id].u.su_v1->bNrInPins > 0) { /* XXX This is not really right */ id = iot[id].u.su_v1->baSourceId[0]; } break; case UDESCSUB_AC_FEATURE: id = iot[id].u.fu_v1->bSourceId; break; case UDESCSUB_AC_PROCESSING: r = *((const struct usb_audio_cluster *) &iot[id].u.pu_v1->baSourceId[ iot[id].u.pu_v1->bNrInPins]); goto done; case UDESCSUB_AC_EXTENSION: r = *((const struct usb_audio_cluster *) &iot[id].u.eu_v1->baSourceId[ iot[id].u.eu_v1->bNrInPins]); goto done; default: goto error; } } error: DPRINTF("bad data\n"); memset(&r, 0, sizeof(r)); done: return (r); } static struct usb_audio20_cluster uaudio20_mixer_get_cluster(uint8_t id, const struct uaudio_terminal_node *iot) { struct usb_audio20_cluster r; const struct usb_descriptor *dp; uint8_t i; for (i = 0; i < UAUDIO_RECURSE_LIMIT; i++) { /* avoid infinite loops */ dp = iot[id].u.desc; if (dp == NULL) goto error; switch (dp->bDescriptorSubtype) { case UDESCSUB_AC_INPUT: r.bNrChannels = iot[id].u.it_v2->bNrChannels; r.bmChannelConfig[0] = iot[id].u.it_v2->bmChannelConfig[0]; r.bmChannelConfig[1] = iot[id].u.it_v2->bmChannelConfig[1]; r.bmChannelConfig[2] = iot[id].u.it_v2->bmChannelConfig[2]; r.bmChannelConfig[3] = iot[id].u.it_v2->bmChannelConfig[3]; r.iChannelNames = iot[id].u.it_v2->iTerminal; goto done; case UDESCSUB_AC_OUTPUT: id = iot[id].u.ot_v2->bSourceId; break; case UDESCSUB_AC_MIXER: r = *(const struct usb_audio20_cluster *) &iot[id].u.mu_v2->baSourceId[ iot[id].u.mu_v2->bNrInPins]; goto done; case UDESCSUB_AC_SELECTOR: if (iot[id].u.su_v2->bNrInPins > 0) { /* XXX This is not really right */ id = iot[id].u.su_v2->baSourceId[0]; } break; case UDESCSUB_AC_SAMPLE_RT: id = iot[id].u.ru_v2->bSourceId; break; case UDESCSUB_AC_EFFECT: id = iot[id].u.ef_v2->bSourceId; break; case UDESCSUB_AC_FEATURE: id = iot[id].u.fu_v2->bSourceId; break; case UDESCSUB_AC_PROCESSING_V2: r = *((const struct usb_audio20_cluster *) &iot[id].u.pu_v2->baSourceId[ iot[id].u.pu_v2->bNrInPins]); goto done; case UDESCSUB_AC_EXTENSION_V2: r = *((const struct usb_audio20_cluster *) &iot[id].u.eu_v2->baSourceId[ iot[id].u.eu_v2->bNrInPins]); goto done; default: goto error; } } error: DPRINTF("Bad data!\n"); memset(&r, 0, sizeof(r)); done: return (r); } static uint16_t uaudio_mixer_determine_class(const struct uaudio_terminal_node *iot, struct uaudio_mixer_node *mix) { uint16_t terminal_type = 0x0000; const struct uaudio_terminal_node *input[2]; const struct uaudio_terminal_node *output[2]; input[0] = uaudio_mixer_get_input(iot, 0); input[1] = uaudio_mixer_get_input(iot, 1); output[0] = uaudio_mixer_get_output(iot, 0); output[1] = uaudio_mixer_get_output(iot, 1); /* * check if there is only * one output terminal: */ if (output[0] && (!output[1])) { terminal_type = UGETW(output[0]->u.ot_v1->wTerminalType); } /* * If the only output terminal is USB, * the class is UAC_RECORD. */ if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) { mix->class = UAC_RECORD; if (input[0] && (!input[1])) { terminal_type = UGETW(input[0]->u.it_v1->wTerminalType); } else { terminal_type = 0; } goto done; } /* * if the unit is connected to just * one input terminal, the * class is UAC_INPUT: */ if (input[0] && (!input[1])) { mix->class = UAC_INPUT; terminal_type = UGETW(input[0]->u.it_v1->wTerminalType); goto done; } /* * Otherwise, the class is UAC_OUTPUT. */ mix->class = UAC_OUTPUT; done: return (terminal_type); } static uint16_t uaudio20_mixer_determine_class(const struct uaudio_terminal_node *iot, struct uaudio_mixer_node *mix) { uint16_t terminal_type = 0x0000; const struct uaudio_terminal_node *input[2]; const struct uaudio_terminal_node *output[2]; input[0] = uaudio_mixer_get_input(iot, 0); input[1] = uaudio_mixer_get_input(iot, 1); output[0] = uaudio_mixer_get_output(iot, 0); output[1] = uaudio_mixer_get_output(iot, 1); /* * check if there is only * one output terminal: */ if (output[0] && (!output[1])) terminal_type = UGETW(output[0]->u.ot_v2->wTerminalType); /* * If the only output terminal is USB, * the class is UAC_RECORD. */ if ((terminal_type & 0xff00) == (UAT_UNDEFINED & 0xff00)) { mix->class = UAC_RECORD; if (input[0] && (!input[1])) { terminal_type = UGETW(input[0]->u.it_v2->wTerminalType); } else { terminal_type = 0; } goto done; } /* * if the unit is connected to just * one input terminal, the * class is UAC_INPUT: */ if (input[0] && (!input[1])) { mix->class = UAC_INPUT; terminal_type = UGETW(input[0]->u.it_v2->wTerminalType); goto done; } /* * Otherwise, the class is UAC_OUTPUT. */ mix->class = UAC_OUTPUT; done: return (terminal_type); } struct uaudio_tt_to_feature { uint16_t terminal_type; uint16_t feature; }; static const struct uaudio_tt_to_feature uaudio_tt_to_feature[] = { {UAT_STREAM, SOUND_MIXER_PCM}, {UATI_MICROPHONE, SOUND_MIXER_MIC}, {UATI_DESKMICROPHONE, SOUND_MIXER_MIC}, {UATI_PERSONALMICROPHONE, SOUND_MIXER_MIC}, {UATI_OMNIMICROPHONE, SOUND_MIXER_MIC}, {UATI_MICROPHONEARRAY, SOUND_MIXER_MIC}, {UATI_PROCMICROPHONEARR, SOUND_MIXER_MIC}, {UATO_SPEAKER, SOUND_MIXER_SPEAKER}, {UATO_DESKTOPSPEAKER, SOUND_MIXER_SPEAKER}, {UATO_ROOMSPEAKER, SOUND_MIXER_SPEAKER}, {UATO_COMMSPEAKER, SOUND_MIXER_SPEAKER}, {UATE_ANALOGCONN, SOUND_MIXER_LINE}, {UATE_LINECONN, SOUND_MIXER_LINE}, {UATE_LEGACYCONN, SOUND_MIXER_LINE}, {UATE_DIGITALAUIFC, SOUND_MIXER_ALTPCM}, {UATE_SPDIF, SOUND_MIXER_ALTPCM}, {UATE_1394DA, SOUND_MIXER_ALTPCM}, {UATE_1394DV, SOUND_MIXER_ALTPCM}, {UATF_CDPLAYER, SOUND_MIXER_CD}, {UATF_SYNTHESIZER, SOUND_MIXER_SYNTH}, {UATF_VIDEODISCAUDIO, SOUND_MIXER_VIDEO}, {UATF_DVDAUDIO, SOUND_MIXER_VIDEO}, {UATF_TVTUNERAUDIO, SOUND_MIXER_VIDEO}, /* telephony terminal types */ {UATT_UNDEFINED, SOUND_MIXER_PHONEIN}, /* SOUND_MIXER_PHONEOUT */ {UATT_PHONELINE, SOUND_MIXER_PHONEIN}, /* SOUND_MIXER_PHONEOUT */ {UATT_TELEPHONE, SOUND_MIXER_PHONEIN}, /* SOUND_MIXER_PHONEOUT */ {UATT_DOWNLINEPHONE, SOUND_MIXER_PHONEIN}, /* SOUND_MIXER_PHONEOUT */ {UATF_RADIORECV, SOUND_MIXER_RADIO}, {UATF_RADIOXMIT, SOUND_MIXER_RADIO}, {UAT_UNDEFINED, SOUND_MIXER_VOLUME}, {UAT_VENDOR, SOUND_MIXER_VOLUME}, {UATI_UNDEFINED, SOUND_MIXER_VOLUME}, /* output terminal types */ {UATO_UNDEFINED, SOUND_MIXER_VOLUME}, {UATO_DISPLAYAUDIO, SOUND_MIXER_VOLUME}, {UATO_SUBWOOFER, SOUND_MIXER_VOLUME}, {UATO_HEADPHONES, SOUND_MIXER_VOLUME}, /* bidir terminal types */ {UATB_UNDEFINED, SOUND_MIXER_VOLUME}, {UATB_HANDSET, SOUND_MIXER_VOLUME}, {UATB_HEADSET, SOUND_MIXER_VOLUME}, {UATB_SPEAKERPHONE, SOUND_MIXER_VOLUME}, {UATB_SPEAKERPHONEESUP, SOUND_MIXER_VOLUME}, {UATB_SPEAKERPHONEECANC, SOUND_MIXER_VOLUME}, /* external terminal types */ {UATE_UNDEFINED, SOUND_MIXER_VOLUME}, /* embedded function terminal types */ {UATF_UNDEFINED, SOUND_MIXER_VOLUME}, {UATF_CALIBNOISE, SOUND_MIXER_VOLUME}, {UATF_EQUNOISE, SOUND_MIXER_VOLUME}, {UATF_DAT, SOUND_MIXER_VOLUME}, {UATF_DCC, SOUND_MIXER_VOLUME}, {UATF_MINIDISK, SOUND_MIXER_VOLUME}, {UATF_ANALOGTAPE, SOUND_MIXER_VOLUME}, {UATF_PHONOGRAPH, SOUND_MIXER_VOLUME}, {UATF_VCRAUDIO, SOUND_MIXER_VOLUME}, {UATF_SATELLITE, SOUND_MIXER_VOLUME}, {UATF_CABLETUNER, SOUND_MIXER_VOLUME}, {UATF_DSS, SOUND_MIXER_VOLUME}, {UATF_MULTITRACK, SOUND_MIXER_VOLUME}, {0xffff, SOUND_MIXER_VOLUME}, /* default */ {0x0000, SOUND_MIXER_VOLUME}, }; static uint16_t uaudio_mixer_feature_name(const struct uaudio_terminal_node *iot, struct uaudio_mixer_node *mix) { const struct uaudio_tt_to_feature *uat = uaudio_tt_to_feature; uint16_t terminal_type = uaudio_mixer_determine_class(iot, mix); if ((mix->class == UAC_RECORD) && (terminal_type == 0)) { return (SOUND_MIXER_IMIX); } while (uat->terminal_type) { if (uat->terminal_type == terminal_type) { break; } uat++; } DPRINTF("terminal_type=0x%04x -> %d\n", terminal_type, uat->feature); return (uat->feature); } static uint16_t uaudio20_mixer_feature_name(const struct uaudio_terminal_node *iot, struct uaudio_mixer_node *mix) { const struct uaudio_tt_to_feature *uat; uint16_t terminal_type = uaudio20_mixer_determine_class(iot, mix); if ((mix->class == UAC_RECORD) && (terminal_type == 0)) return (SOUND_MIXER_IMIX); for (uat = uaudio_tt_to_feature; uat->terminal_type != 0; uat++) { if (uat->terminal_type == terminal_type) break; } DPRINTF("terminal_type=0x%04x -> %d\n", terminal_type, uat->feature); return (uat->feature); } static const struct uaudio_terminal_node * uaudio_mixer_get_input(const struct uaudio_terminal_node *iot, uint8_t i) { struct uaudio_terminal_node *root = iot->root; uint8_t n; n = iot->usr.id_max; do { if (iot->usr.bit_input[n / 8] & (1 << (n % 8))) { if (!i--) return (root + n); } } while (n--); return (NULL); } static const struct uaudio_terminal_node * uaudio_mixer_get_output(const struct uaudio_terminal_node *iot, uint8_t i) { struct uaudio_terminal_node *root = iot->root; uint8_t n; n = iot->usr.id_max; do { if (iot->usr.bit_output[n / 8] & (1 << (n % 8))) { if (!i--) return (root + n); } } while (n--); return (NULL); } static void uaudio_mixer_find_inputs_sub(struct uaudio_terminal_node *root, const uint8_t *p_id, uint8_t n_id, struct uaudio_search_result *info) { struct uaudio_terminal_node *iot; uint8_t n; uint8_t i; uint8_t is_last; top: for (n = 0; n < n_id; n++) { i = p_id[n]; if (info->recurse_level == UAUDIO_RECURSE_LIMIT) { DPRINTF("avoided going into a circle at id=%d!\n", i); return; } info->recurse_level++; iot = (root + i); if (iot->u.desc == NULL) continue; is_last = ((n + 1) == n_id); switch (iot->u.desc->bDescriptorSubtype) { case UDESCSUB_AC_INPUT: info->bit_input[i / 8] |= (1 << (i % 8)); break; case UDESCSUB_AC_FEATURE: if (is_last) { p_id = &iot->u.fu_v1->bSourceId; n_id = 1; goto top; } uaudio_mixer_find_inputs_sub( root, &iot->u.fu_v1->bSourceId, 1, info); break; case UDESCSUB_AC_OUTPUT: if (is_last) { p_id = &iot->u.ot_v1->bSourceId; n_id = 1; goto top; } uaudio_mixer_find_inputs_sub( root, &iot->u.ot_v1->bSourceId, 1, info); break; case UDESCSUB_AC_MIXER: if (is_last) { p_id = iot->u.mu_v1->baSourceId; n_id = iot->u.mu_v1->bNrInPins; goto top; } uaudio_mixer_find_inputs_sub( root, iot->u.mu_v1->baSourceId, iot->u.mu_v1->bNrInPins, info); break; case UDESCSUB_AC_SELECTOR: if (is_last) { p_id = iot->u.su_v1->baSourceId; n_id = iot->u.su_v1->bNrInPins; goto top; } uaudio_mixer_find_inputs_sub( root, iot->u.su_v1->baSourceId, iot->u.su_v1->bNrInPins, info); break; case UDESCSUB_AC_PROCESSING: if (is_last) { p_id = iot->u.pu_v1->baSourceId; n_id = iot->u.pu_v1->bNrInPins; goto top; } uaudio_mixer_find_inputs_sub( root, iot->u.pu_v1->baSourceId, iot->u.pu_v1->bNrInPins, info); break; case UDESCSUB_AC_EXTENSION: if (is_last) { p_id = iot->u.eu_v1->baSourceId; n_id = iot->u.eu_v1->bNrInPins; goto top; } uaudio_mixer_find_inputs_sub( root, iot->u.eu_v1->baSourceId, iot->u.eu_v1->bNrInPins, info); break; default: break; } } } static void uaudio20_mixer_find_inputs_sub(struct uaudio_terminal_node *root, const uint8_t *p_id, uint8_t n_id, struct uaudio_search_result *info) { struct uaudio_terminal_node *iot; uint8_t n; uint8_t i; uint8_t is_last; top: for (n = 0; n < n_id; n++) { i = p_id[n]; if (info->recurse_level == UAUDIO_RECURSE_LIMIT) { DPRINTF("avoided going into a circle at id=%d!\n", i); return; } info->recurse_level++; iot = (root + i); if (iot->u.desc == NULL) continue; is_last = ((n + 1) == n_id); switch (iot->u.desc->bDescriptorSubtype) { case UDESCSUB_AC_INPUT: info->bit_input[i / 8] |= (1 << (i % 8)); break; case UDESCSUB_AC_OUTPUT: if (is_last) { p_id = &iot->u.ot_v2->bSourceId; n_id = 1; goto top; } uaudio20_mixer_find_inputs_sub( root, &iot->u.ot_v2->bSourceId, 1, info); break; case UDESCSUB_AC_MIXER: if (is_last) { p_id = iot->u.mu_v2->baSourceId; n_id = iot->u.mu_v2->bNrInPins; goto top; } uaudio20_mixer_find_inputs_sub( root, iot->u.mu_v2->baSourceId, iot->u.mu_v2->bNrInPins, info); break; case UDESCSUB_AC_SELECTOR: if (is_last) { p_id = iot->u.su_v2->baSourceId; n_id = iot->u.su_v2->bNrInPins; goto top; } uaudio20_mixer_find_inputs_sub( root, iot->u.su_v2->baSourceId, iot->u.su_v2->bNrInPins, info); break; case UDESCSUB_AC_SAMPLE_RT: if (is_last) { p_id = &iot->u.ru_v2->bSourceId; n_id = 1; goto top; } uaudio20_mixer_find_inputs_sub( root, &iot->u.ru_v2->bSourceId, 1, info); break; case UDESCSUB_AC_EFFECT: if (is_last) { p_id = &iot->u.ef_v2->bSourceId; n_id = 1; goto top; } uaudio20_mixer_find_inputs_sub( root, &iot->u.ef_v2->bSourceId, 1, info); break; case UDESCSUB_AC_FEATURE: if (is_last) { p_id = &iot->u.fu_v2->bSourceId; n_id = 1; goto top; } uaudio20_mixer_find_inputs_sub( root, &iot->u.fu_v2->bSourceId, 1, info); break; case UDESCSUB_AC_PROCESSING_V2: if (is_last) { p_id = iot->u.pu_v2->baSourceId; n_id = iot->u.pu_v2->bNrInPins; goto top; } uaudio20_mixer_find_inputs_sub( root, iot->u.pu_v2->baSourceId, iot->u.pu_v2->bNrInPins, info); break; case UDESCSUB_AC_EXTENSION_V2: if (is_last) { p_id = iot->u.eu_v2->baSourceId; n_id = iot->u.eu_v2->bNrInPins; goto top; } uaudio20_mixer_find_inputs_sub( root, iot->u.eu_v2->baSourceId, iot->u.eu_v2->bNrInPins, info); break; default: break; } } } static void uaudio20_mixer_find_clocks_sub(struct uaudio_terminal_node *root, const uint8_t *p_id, uint8_t n_id, struct uaudio_search_result *info) { struct uaudio_terminal_node *iot; uint8_t n; uint8_t i; uint8_t is_last; uint8_t id; top: for (n = 0; n < n_id; n++) { i = p_id[n]; if (info->recurse_level == UAUDIO_RECURSE_LIMIT) { DPRINTF("avoided going into a circle at id=%d!\n", i); return; } info->recurse_level++; iot = (root + i); if (iot->u.desc == NULL) continue; is_last = ((n + 1) == n_id); switch (iot->u.desc->bDescriptorSubtype) { case UDESCSUB_AC_INPUT: info->is_input = 1; if (is_last) { p_id = &iot->u.it_v2->bCSourceId; n_id = 1; goto top; } uaudio20_mixer_find_clocks_sub(root, &iot->u.it_v2->bCSourceId, 1, info); break; case UDESCSUB_AC_OUTPUT: info->is_input = 0; if (is_last) { p_id = &iot->u.ot_v2->bCSourceId; n_id = 1; goto top; } uaudio20_mixer_find_clocks_sub(root, &iot->u.ot_v2->bCSourceId, 1, info); break; case UDESCSUB_AC_CLOCK_SEL: if (is_last) { p_id = iot->u.csel_v2->baCSourceId; n_id = iot->u.csel_v2->bNrInPins; goto top; } uaudio20_mixer_find_clocks_sub(root, iot->u.csel_v2->baCSourceId, iot->u.csel_v2->bNrInPins, info); break; case UDESCSUB_AC_CLOCK_MUL: if (is_last) { p_id = &iot->u.cmul_v2->bCSourceId; n_id = 1; goto top; } uaudio20_mixer_find_clocks_sub(root, &iot->u.cmul_v2->bCSourceId, 1, info); break; case UDESCSUB_AC_CLOCK_SRC: id = iot->u.csrc_v2->bClockId; switch (info->is_input) { case 0: info->bit_output[id / 8] |= (1 << (id % 8)); break; case 1: info->bit_input[id / 8] |= (1 << (id % 8)); break; default: break; } break; default: break; } } } static void uaudio_mixer_find_outputs_sub(struct uaudio_terminal_node *root, uint8_t id, uint8_t n_id, struct uaudio_search_result *info) { struct uaudio_terminal_node *iot = (root + id); uint8_t j; j = n_id; do { if ((j != id) && ((root + j)->u.desc) && ((root + j)->u.desc->bDescriptorSubtype == UDESCSUB_AC_OUTPUT)) { /* * "j" (output) <--- virtual wire <--- "id" (input) * * if "j" has "id" on the input, then "id" have "j" on * the output, because they are connected: */ if ((root + j)->usr.bit_input[id / 8] & (1 << (id % 8))) { iot->usr.bit_output[j / 8] |= (1 << (j % 8)); } } } while (j--); } static void uaudio_mixer_fill_info(struct uaudio_softc *sc, struct usb_device *udev, void *desc) { const struct usb_audio_control_descriptor *acdp; struct usb_config_descriptor *cd = usbd_get_config_descriptor(udev); const struct usb_descriptor *dp; const struct usb_audio_unit *au; struct uaudio_terminal_node *iot = NULL; uint16_t wTotalLen; uint8_t ID_max = 0; /* inclusive */ uint8_t i; desc = usb_desc_foreach(cd, desc); if (desc == NULL) { DPRINTF("no Audio Control header\n"); goto done; } acdp = desc; if ((acdp->bLength < sizeof(*acdp)) || (acdp->bDescriptorType != UDESC_CS_INTERFACE) || (acdp->bDescriptorSubtype != UDESCSUB_AC_HEADER)) { DPRINTF("invalid Audio Control header\n"); goto done; } /* "wTotalLen" is allowed to be corrupt */ wTotalLen = UGETW(acdp->wTotalLength) - acdp->bLength; /* get USB audio revision */ sc->sc_audio_rev = UGETW(acdp->bcdADC); DPRINTFN(3, "found AC header, vers=%03x, len=%d\n", sc->sc_audio_rev, wTotalLen); iot = malloc(sizeof(struct uaudio_terminal_node) * 256, M_TEMP, M_WAITOK | M_ZERO); if (iot == NULL) { DPRINTF("no memory!\n"); goto done; } while ((desc = usb_desc_foreach(cd, desc))) { dp = desc; if (dp->bLength > wTotalLen) { break; } else { wTotalLen -= dp->bLength; } if (sc->sc_audio_rev >= UAUDIO_VERSION_30) au = NULL; else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) au = uaudio20_mixer_verify_desc(dp, 0); else au = uaudio_mixer_verify_desc(dp, 0); if (au) { iot[au->bUnitId].u.desc = (const void *)au; if (au->bUnitId > ID_max) ID_max = au->bUnitId; } } DPRINTF("Maximum ID=%d\n", ID_max); /* * determine sourcing inputs for * all nodes in the tree: */ i = ID_max; do { if (sc->sc_audio_rev >= UAUDIO_VERSION_30) { /* FALLTHROUGH */ } else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) { uaudio20_mixer_find_inputs_sub(iot, &i, 1, &((iot + i)->usr)); sc->sc_mixer_clocks.is_input = 255; sc->sc_mixer_clocks.recurse_level = 0; uaudio20_mixer_find_clocks_sub(iot, &i, 1, &sc->sc_mixer_clocks); } else { uaudio_mixer_find_inputs_sub(iot, &i, 1, &((iot + i)->usr)); } } while (i--); /* * determine outputs for * all nodes in the tree: */ i = ID_max; do { uaudio_mixer_find_outputs_sub(iot, i, ID_max, &((iot + i)->usr)); } while (i--); /* set "id_max" and "root" */ i = ID_max; do { (iot + i)->usr.id_max = ID_max; (iot + i)->root = iot; } while (i--); /* * Scan the config to create a linked list of "mixer" nodes: */ i = ID_max; do { dp = iot[i].u.desc; if (dp == NULL) continue; DPRINTFN(11, "id=%d subtype=%d\n", i, dp->bDescriptorSubtype); if (sc->sc_audio_rev >= UAUDIO_VERSION_30) { continue; } else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) { switch (dp->bDescriptorSubtype) { case UDESCSUB_AC_HEADER: DPRINTF("unexpected AC header\n"); break; case UDESCSUB_AC_INPUT: case UDESCSUB_AC_OUTPUT: case UDESCSUB_AC_PROCESSING_V2: case UDESCSUB_AC_EXTENSION_V2: case UDESCSUB_AC_EFFECT: case UDESCSUB_AC_CLOCK_SRC: case UDESCSUB_AC_CLOCK_SEL: case UDESCSUB_AC_CLOCK_MUL: case UDESCSUB_AC_SAMPLE_RT: break; case UDESCSUB_AC_MIXER: uaudio20_mixer_add_mixer(sc, iot, i); break; case UDESCSUB_AC_SELECTOR: uaudio20_mixer_add_selector(sc, iot, i); break; case UDESCSUB_AC_FEATURE: uaudio20_mixer_add_feature(sc, iot, i); break; default: DPRINTF("bad AC desc subtype=0x%02x\n", dp->bDescriptorSubtype); break; } continue; } switch (dp->bDescriptorSubtype) { case UDESCSUB_AC_HEADER: DPRINTF("unexpected AC header\n"); break; case UDESCSUB_AC_INPUT: case UDESCSUB_AC_OUTPUT: break; case UDESCSUB_AC_MIXER: uaudio_mixer_add_mixer(sc, iot, i); break; case UDESCSUB_AC_SELECTOR: uaudio_mixer_add_selector(sc, iot, i); break; case UDESCSUB_AC_FEATURE: uaudio_mixer_add_feature(sc, iot, i); break; case UDESCSUB_AC_PROCESSING: uaudio_mixer_add_processing(sc, iot, i); break; case UDESCSUB_AC_EXTENSION: uaudio_mixer_add_extension(sc, iot, i); break; default: DPRINTF("bad AC desc subtype=0x%02x\n", dp->bDescriptorSubtype); break; } } while (i--); done: free(iot, M_TEMP); } static int uaudio_mixer_get(struct usb_device *udev, uint16_t audio_rev, uint8_t what, struct uaudio_mixer_node *mc) { struct usb_device_request req; int val; uint8_t data[2 + (2 * 3)]; usb_error_t err; if (mc->wValue[0] == -1) return (0); if (audio_rev >= UAUDIO_VERSION_30) return (0); else if (audio_rev >= UAUDIO_VERSION_20) { if (what == GET_CUR) { req.bRequest = UA20_CS_CUR; USETW(req.wLength, 2); } else { req.bRequest = UA20_CS_RANGE; USETW(req.wLength, 8); } } else { uint16_t len = MIX_SIZE(mc->type); req.bRequest = what; USETW(req.wLength, len); } req.bmRequestType = UT_READ_CLASS_INTERFACE; USETW(req.wValue, mc->wValue[0]); USETW(req.wIndex, mc->wIndex); memset(data, 0, sizeof(data)); err = usbd_do_request(udev, NULL, &req, data); if (err) { DPRINTF("err=%s\n", usbd_errstr(err)); return (0); } if (audio_rev >= UAUDIO_VERSION_30) { val = 0; } else if (audio_rev >= UAUDIO_VERSION_20) { switch (what) { case GET_CUR: val = (data[0] | (data[1] << 8)); break; case GET_MIN: val = (data[2] | (data[3] << 8)); break; case GET_MAX: val = (data[4] | (data[5] << 8)); break; case GET_RES: val = (data[6] | (data[7] << 8)); break; default: val = 0; break; } } else { val = (data[0] | (data[1] << 8)); } if (what == GET_CUR || what == GET_MIN || what == GET_MAX) val = uaudio_mixer_signext(mc->type, val); DPRINTFN(3, "val=%d\n", val); return (val); } static void uaudio_mixer_write_cfg_callback(struct usb_xfer *xfer, usb_error_t error) { struct usb_device_request req; struct uaudio_softc *sc = usbd_xfer_softc(xfer); struct uaudio_mixer_node *mc = sc->sc_mixer_curr; struct usb_page_cache *pc; uint16_t len; uint8_t repeat = 1; uint8_t update; uint8_t chan; uint8_t buf[2]; DPRINTF("\n"); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: tr_transferred: case USB_ST_SETUP: tr_setup: if (mc == NULL) { mc = sc->sc_mixer_root; sc->sc_mixer_curr = mc; sc->sc_mixer_chan = 0; repeat = 0; } while (mc) { while (sc->sc_mixer_chan < mc->nchan) { chan = sc->sc_mixer_chan; sc->sc_mixer_chan++; update = ((mc->update[chan / 8] & (1 << (chan % 8))) && (mc->wValue[chan] != -1)); mc->update[chan / 8] &= ~(1 << (chan % 8)); if (update) { req.bmRequestType = UT_WRITE_CLASS_INTERFACE; USETW(req.wValue, mc->wValue[chan]); USETW(req.wIndex, mc->wIndex); if (sc->sc_audio_rev >= UAUDIO_VERSION_30) { return; } else if (sc->sc_audio_rev >= UAUDIO_VERSION_20) { len = 2; req.bRequest = UA20_CS_CUR; USETW(req.wLength, len); } else { len = MIX_SIZE(mc->type); req.bRequest = SET_CUR; USETW(req.wLength, len); } buf[0] = (mc->wData[chan] & 0xFF); buf[1] = (mc->wData[chan] >> 8) & 0xFF; pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, &req, sizeof(req)); pc = usbd_xfer_get_frame(xfer, 1); usbd_copy_in(pc, 0, buf, len); usbd_xfer_set_frame_len(xfer, 0, sizeof(req)); usbd_xfer_set_frame_len(xfer, 1, len); usbd_xfer_set_frames(xfer, len ? 2 : 1); usbd_transfer_submit(xfer); return; } } mc = mc->next; sc->sc_mixer_curr = mc; sc->sc_mixer_chan = 0; } if (repeat) { goto tr_setup; } break; default: /* Error */ DPRINTF("error=%s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) { /* do nothing - we are detaching */ break; } goto tr_transferred; } } static usb_error_t uaudio_set_speed(struct usb_device *udev, uint8_t endpt, uint32_t speed) { struct usb_device_request req; uint8_t data[3]; DPRINTFN(6, "endpt=%d speed=%u\n", endpt, speed); req.bmRequestType = UT_WRITE_CLASS_ENDPOINT; req.bRequest = SET_CUR; USETW2(req.wValue, SAMPLING_FREQ_CONTROL, 0); USETW(req.wIndex, endpt); USETW(req.wLength, 3); data[0] = speed; data[1] = speed >> 8; data[2] = speed >> 16; return (usbd_do_request(udev, NULL, &req, data)); } static usb_error_t uaudio20_set_speed(struct usb_device *udev, uint8_t iface_no, uint8_t clockid, uint32_t speed) { struct usb_device_request req; uint8_t data[4]; DPRINTFN(6, "ifaceno=%d clockid=%d speed=%u\n", iface_no, clockid, speed); req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UA20_CS_CUR; USETW2(req.wValue, UA20_CS_SAM_FREQ_CONTROL, 0); USETW2(req.wIndex, clockid, iface_no); USETW(req.wLength, 4); data[0] = speed; data[1] = speed >> 8; data[2] = speed >> 16; data[3] = speed >> 24; return (usbd_do_request(udev, NULL, &req, data)); } static int uaudio_mixer_signext(uint8_t type, int val) { if (!MIX_UNSIGNED(type)) { if (MIX_SIZE(type) == 2) { val = (int16_t)val; } else { val = (int8_t)val; } } return (val); } static int uaudio_mixer_bsd2value(struct uaudio_mixer_node *mc, int32_t val) { if (mc->type == MIX_ON_OFF) { val = (val != 0); } else if (mc->type == MIX_SELECTOR) { if ((val < mc->minval) || (val > mc->maxval)) { val = mc->minval; } } else { /* compute actual volume */ val = (val * mc->mul) / 255; /* add lower offset */ val = val + mc->minval; /* make sure we don't write a value out of range */ if (val > mc->maxval) val = mc->maxval; else if (val < mc->minval) val = mc->minval; } DPRINTFN(6, "type=0x%03x val=%d min=%d max=%d val=%d\n", mc->type, val, mc->minval, mc->maxval, val); return (val); } static void uaudio_mixer_ctl_set(struct uaudio_softc *sc, struct uaudio_mixer_node *mc, uint8_t chan, int32_t val) { val = uaudio_mixer_bsd2value(mc, val); mc->update[chan / 8] |= (1 << (chan % 8)); mc->wData[chan] = val; /* start the transfer, if not already started */ usbd_transfer_start(sc->sc_mixer_xfer[0]); } static void uaudio_mixer_init(struct uaudio_softc *sc) { struct uaudio_mixer_node *mc; int32_t i; for (mc = sc->sc_mixer_root; mc; mc = mc->next) { if (mc->ctl != SOUND_MIXER_NRDEVICES) { /* * Set device mask bits. See * /usr/include/machine/soundcard.h */ sc->sc_mix_info |= (1 << mc->ctl); } if ((mc->ctl == SOUND_MIXER_NRDEVICES) && (mc->type == MIX_SELECTOR)) { for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) { if (mc->slctrtype[i - 1] == SOUND_MIXER_NRDEVICES) { continue; } sc->sc_recsrc_info |= 1 << mc->slctrtype[i - 1]; } } } } int uaudio_mixer_init_sub(struct uaudio_softc *sc, struct snd_mixer *m) { DPRINTF("\n"); sc->sc_mixer_lock = mixer_get_lock(m); sc->sc_mixer_dev = m; if (usbd_transfer_setup(sc->sc_udev, &sc->sc_mixer_iface_index, sc->sc_mixer_xfer, uaudio_mixer_config, 1, sc, sc->sc_mixer_lock)) { DPRINTFN(0, "could not allocate USB " "transfer for audio mixer!\n"); return (ENOMEM); } if (!(sc->sc_mix_info & SOUND_MASK_VOLUME)) { mix_setparentchild(m, SOUND_MIXER_VOLUME, SOUND_MASK_PCM); mix_setrealdev(m, SOUND_MIXER_VOLUME, SOUND_MIXER_NONE); } mix_setdevs(m, sc->sc_mix_info); mix_setrecdevs(m, sc->sc_recsrc_info); return (0); } int uaudio_mixer_uninit_sub(struct uaudio_softc *sc) { DPRINTF("\n"); usbd_transfer_unsetup(sc->sc_mixer_xfer, 1); sc->sc_mixer_lock = NULL; return (0); } void uaudio_mixer_set(struct uaudio_softc *sc, unsigned type, unsigned left, unsigned right) { struct uaudio_mixer_node *mc; int chan; for (mc = sc->sc_mixer_root; mc != NULL; mc = mc->next) { if (mc->ctl == type) { for (chan = 0; chan < mc->nchan; chan++) { uaudio_mixer_ctl_set(sc, mc, chan, (int)((chan == 0 ? left : right) * 255) / 100); } } } } uint32_t uaudio_mixer_setrecsrc(struct uaudio_softc *sc, uint32_t src) { struct uaudio_mixer_node *mc; uint32_t mask; uint32_t temp; int32_t i; for (mc = sc->sc_mixer_root; mc; mc = mc->next) { if ((mc->ctl == SOUND_MIXER_NRDEVICES) && (mc->type == MIX_SELECTOR)) { /* compute selector mask */ mask = 0; for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) { mask |= (1 << mc->slctrtype[i - 1]); } temp = mask & src; if (temp == 0) { continue; } /* find the first set bit */ temp = (-temp) & temp; /* update "src" */ src &= ~mask; src |= temp; for (i = mc->minval; (i > 0) && (i <= mc->maxval); i++) { if (temp != (1 << mc->slctrtype[i - 1])) { continue; } uaudio_mixer_ctl_set(sc, mc, 0, i); break; } } } return (src); } /*========================================================================* * MIDI support routines *========================================================================*/ static void umidi_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct umidi_chan *chan = usbd_xfer_softc(xfer); struct umidi_sub_chan *sub; struct usb_page_cache *pc; uint8_t buf[4]; uint8_t cmd_len; uint8_t cn; uint16_t pos; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTF("actlen=%d bytes\n", actlen); pos = 0; pc = usbd_xfer_get_frame(xfer, 0); while (actlen >= 4) { /* copy out the MIDI data */ usbd_copy_out(pc, pos, buf, 4); /* command length */ cmd_len = umidi_cmd_to_len[buf[0] & 0xF]; /* cable number */ cn = buf[0] >> 4; /* * Lookup sub-channel. The index is range * checked below. */ sub = &chan->sub[cn]; if ((cmd_len != 0) && (cn < chan->max_emb_jack) && (sub->read_open != 0)) { /* Send data to the application */ usb_fifo_put_data_linear( sub->fifo.fp[USB_FIFO_RX], buf + 1, cmd_len, 1); } actlen -= 4; pos += 4; } case USB_ST_SETUP: DPRINTF("start\n"); tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: DPRINTF("error=%s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } /* * The following statemachine, that converts MIDI commands to * USB MIDI packets, derives from Linux's usbmidi.c, which * was written by "Clemens Ladisch": * * Returns: * 0: No command * Else: Command is complete */ static uint8_t umidi_convert_to_usb(struct umidi_sub_chan *sub, uint8_t cn, uint8_t b) { uint8_t p0 = (cn << 4); if (b >= 0xf8) { sub->temp_0[0] = p0 | 0x0f; sub->temp_0[1] = b; sub->temp_0[2] = 0; sub->temp_0[3] = 0; sub->temp_cmd = sub->temp_0; return (1); } else if (b >= 0xf0) { switch (b) { case 0xf0: /* system exclusive begin */ sub->temp_1[1] = b; sub->state = UMIDI_ST_SYSEX_1; break; case 0xf1: /* MIDI time code */ case 0xf3: /* song select */ sub->temp_1[1] = b; sub->state = UMIDI_ST_1PARAM; break; case 0xf2: /* song position pointer */ sub->temp_1[1] = b; sub->state = UMIDI_ST_2PARAM_1; break; case 0xf4: /* unknown */ case 0xf5: /* unknown */ sub->state = UMIDI_ST_UNKNOWN; break; case 0xf6: /* tune request */ sub->temp_1[0] = p0 | 0x05; sub->temp_1[1] = 0xf6; sub->temp_1[2] = 0; sub->temp_1[3] = 0; sub->temp_cmd = sub->temp_1; sub->state = UMIDI_ST_UNKNOWN; return (1); case 0xf7: /* system exclusive end */ switch (sub->state) { case UMIDI_ST_SYSEX_0: sub->temp_1[0] = p0 | 0x05; sub->temp_1[1] = 0xf7; sub->temp_1[2] = 0; sub->temp_1[3] = 0; sub->temp_cmd = sub->temp_1; sub->state = UMIDI_ST_UNKNOWN; return (1); case UMIDI_ST_SYSEX_1: sub->temp_1[0] = p0 | 0x06; sub->temp_1[2] = 0xf7; sub->temp_1[3] = 0; sub->temp_cmd = sub->temp_1; sub->state = UMIDI_ST_UNKNOWN; return (1); case UMIDI_ST_SYSEX_2: sub->temp_1[0] = p0 | 0x07; sub->temp_1[3] = 0xf7; sub->temp_cmd = sub->temp_1; sub->state = UMIDI_ST_UNKNOWN; return (1); } sub->state = UMIDI_ST_UNKNOWN; break; } } else if (b >= 0x80) { sub->temp_1[1] = b; if ((b >= 0xc0) && (b <= 0xdf)) { sub->state = UMIDI_ST_1PARAM; } else { sub->state = UMIDI_ST_2PARAM_1; } } else { /* b < 0x80 */ switch (sub->state) { case UMIDI_ST_1PARAM: if (sub->temp_1[1] < 0xf0) { p0 |= sub->temp_1[1] >> 4; } else { p0 |= 0x02; sub->state = UMIDI_ST_UNKNOWN; } sub->temp_1[0] = p0; sub->temp_1[2] = b; sub->temp_1[3] = 0; sub->temp_cmd = sub->temp_1; return (1); case UMIDI_ST_2PARAM_1: sub->temp_1[2] = b; sub->state = UMIDI_ST_2PARAM_2; break; case UMIDI_ST_2PARAM_2: if (sub->temp_1[1] < 0xf0) { p0 |= sub->temp_1[1] >> 4; sub->state = UMIDI_ST_2PARAM_1; } else { p0 |= 0x03; sub->state = UMIDI_ST_UNKNOWN; } sub->temp_1[0] = p0; sub->temp_1[3] = b; sub->temp_cmd = sub->temp_1; return (1); case UMIDI_ST_SYSEX_0: sub->temp_1[1] = b; sub->state = UMIDI_ST_SYSEX_1; break; case UMIDI_ST_SYSEX_1: sub->temp_1[2] = b; sub->state = UMIDI_ST_SYSEX_2; break; case UMIDI_ST_SYSEX_2: sub->temp_1[0] = p0 | 0x04; sub->temp_1[3] = b; sub->temp_cmd = sub->temp_1; sub->state = UMIDI_ST_SYSEX_0; return (1); default: break; } } return (0); } static void umidi_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct umidi_chan *chan = usbd_xfer_softc(xfer); struct umidi_sub_chan *sub; struct usb_page_cache *pc; uint32_t actlen; uint16_t nframes; uint8_t buf; uint8_t start_cable; uint8_t tr_any; int len; usbd_xfer_status(xfer, &len, NULL, NULL, NULL); /* * NOTE: Some MIDI devices only accept 4 bytes of data per * short terminated USB transfer. */ switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTF("actlen=%d bytes\n", len); case USB_ST_SETUP: tr_setup: DPRINTF("start\n"); nframes = 0; /* reset */ start_cable = chan->curr_cable; tr_any = 0; pc = usbd_xfer_get_frame(xfer, 0); while (1) { /* round robin de-queueing */ sub = &chan->sub[chan->curr_cable]; if (sub->write_open) { usb_fifo_get_data_linear(sub->fifo.fp[USB_FIFO_TX], &buf, 1, &actlen, 0); } else { actlen = 0; } if (actlen) { tr_any = 1; DPRINTF("byte=0x%02x from FIFO %u\n", buf, (unsigned int)chan->curr_cable); if (umidi_convert_to_usb(sub, chan->curr_cable, buf)) { DPRINTF("sub=0x%02x 0x%02x 0x%02x 0x%02x\n", sub->temp_cmd[0], sub->temp_cmd[1], sub->temp_cmd[2], sub->temp_cmd[3]); usbd_copy_in(pc, nframes * 4, sub->temp_cmd, 4); nframes++; if ((nframes >= UMIDI_TX_FRAMES) || (chan->single_command != 0)) break; } else { continue; } } chan->curr_cable++; if (chan->curr_cable >= chan->max_emb_jack) chan->curr_cable = 0; if (chan->curr_cable == start_cable) { if (tr_any == 0) break; tr_any = 0; } } if (nframes != 0) { DPRINTF("Transferring %d frames\n", (int)nframes); usbd_xfer_set_frame_len(xfer, 0, 4 * nframes); usbd_transfer_submit(xfer); } break; default: /* Error */ DPRINTF("error=%s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static struct umidi_sub_chan * umidi_sub_by_fifo(struct usb_fifo *fifo) { struct umidi_chan *chan = usb_fifo_softc(fifo); struct umidi_sub_chan *sub; uint32_t n; for (n = 0; n < UMIDI_EMB_JACK_MAX; n++) { sub = &chan->sub[n]; if ((sub->fifo.fp[USB_FIFO_RX] == fifo) || (sub->fifo.fp[USB_FIFO_TX] == fifo)) { return (sub); } } panic("%s:%d cannot find usb_fifo!\n", __FILE__, __LINE__); return (NULL); } static void umidi_start_read(struct usb_fifo *fifo) { struct umidi_chan *chan = usb_fifo_softc(fifo); usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]); } static void umidi_stop_read(struct usb_fifo *fifo) { struct umidi_chan *chan = usb_fifo_softc(fifo); struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo); DPRINTF("\n"); sub->read_open = 0; if (--(chan->read_open_refcount) == 0) { /* * XXX don't stop the read transfer here, hence that causes * problems with some MIDI adapters */ DPRINTF("(stopping read transfer)\n"); } } static void umidi_start_write(struct usb_fifo *fifo) { struct umidi_chan *chan = usb_fifo_softc(fifo); usbd_transfer_start(chan->xfer[UMIDI_TX_TRANSFER]); } static void umidi_stop_write(struct usb_fifo *fifo) { struct umidi_chan *chan = usb_fifo_softc(fifo); struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo); DPRINTF("\n"); sub->write_open = 0; if (--(chan->write_open_refcount) == 0) { DPRINTF("(stopping write transfer)\n"); usbd_transfer_stop(chan->xfer[UMIDI_TX_TRANSFER]); } } static int umidi_open(struct usb_fifo *fifo, int fflags) { struct umidi_chan *chan = usb_fifo_softc(fifo); struct umidi_sub_chan *sub = umidi_sub_by_fifo(fifo); if (fflags & FREAD) { if (usb_fifo_alloc_buffer(fifo, 4, (1024 / 4))) { return (ENOMEM); } mtx_lock(&chan->mtx); chan->read_open_refcount++; sub->read_open = 1; mtx_unlock(&chan->mtx); } if (fflags & FWRITE) { if (usb_fifo_alloc_buffer(fifo, 32, (1024 / 32))) { return (ENOMEM); } /* clear stall first */ mtx_lock(&chan->mtx); chan->write_open_refcount++; sub->write_open = 1; /* reset */ sub->state = UMIDI_ST_UNKNOWN; mtx_unlock(&chan->mtx); } return (0); /* success */ } static void umidi_close(struct usb_fifo *fifo, int fflags) { if (fflags & FREAD) { usb_fifo_free_buffer(fifo); } if (fflags & FWRITE) { usb_fifo_free_buffer(fifo); } } static int umidi_ioctl(struct usb_fifo *fifo, u_long cmd, void *data, int fflags) { return (ENODEV); } static void umidi_init(device_t dev) { struct uaudio_softc *sc = device_get_softc(dev); struct umidi_chan *chan = &sc->sc_midi_chan; mtx_init(&chan->mtx, "umidi lock", NULL, MTX_DEF | MTX_RECURSE); } static struct usb_fifo_methods umidi_fifo_methods = { .f_start_read = &umidi_start_read, .f_start_write = &umidi_start_write, .f_stop_read = &umidi_stop_read, .f_stop_write = &umidi_stop_write, .f_open = &umidi_open, .f_close = &umidi_close, .f_ioctl = &umidi_ioctl, .basename[0] = "umidi", }; static int umidi_probe(device_t dev) { struct uaudio_softc *sc = device_get_softc(dev); struct usb_attach_arg *uaa = device_get_ivars(dev); struct umidi_chan *chan = &sc->sc_midi_chan; struct umidi_sub_chan *sub; int unit = device_get_unit(dev); int error; uint32_t n; if (usb_test_quirk(uaa, UQ_SINGLE_CMD_MIDI)) chan->single_command = 1; if (usbd_set_alt_interface_index(sc->sc_udev, chan->iface_index, chan->iface_alt_index)) { DPRINTF("setting of alternate index failed!\n"); goto detach; } usbd_set_parent_iface(sc->sc_udev, chan->iface_index, sc->sc_mixer_iface_index); error = usbd_transfer_setup(uaa->device, &chan->iface_index, chan->xfer, umidi_config, UMIDI_N_TRANSFER, chan, &chan->mtx); if (error) { DPRINTF("error=%s\n", usbd_errstr(error)); goto detach; } /* * Some USB MIDI device makers couldn't resist using * wMaxPacketSize = 4 for RX and TX BULK endpoints, although * that size is an unsupported value for FULL speed BULK * endpoints. The same applies to some HIGH speed MIDI devices * which are using a wMaxPacketSize different from 512 bytes. * * Refer to section 5.8.3 in USB 2.0 PDF: Cite: "All Host * Controllers are required to have support for 8-, 16-, 32-, * and 64-byte maximum packet sizes for full-speed bulk * endpoints and 512 bytes for high-speed bulk endpoints." */ if (usbd_xfer_maxp_was_clamped(chan->xfer[UMIDI_TX_TRANSFER])) chan->single_command = 1; if (chan->single_command != 0) device_printf(dev, "Single command MIDI quirk enabled\n"); if ((chan->max_emb_jack == 0) || (chan->max_emb_jack > UMIDI_EMB_JACK_MAX)) { chan->max_emb_jack = UMIDI_EMB_JACK_MAX; } for (n = 0; n < chan->max_emb_jack; n++) { sub = &chan->sub[n]; error = usb_fifo_attach(sc->sc_udev, chan, &chan->mtx, &umidi_fifo_methods, &sub->fifo, unit, n, chan->iface_index, UID_ROOT, GID_OPERATOR, 0644); if (error) { goto detach; } } mtx_lock(&chan->mtx); /* * NOTE: At least one device will not work properly unless the * BULK IN pipe is open all the time. This might have to do * about that the internal queues of the device overflow if we * don't read them regularly. */ usbd_transfer_start(chan->xfer[UMIDI_RX_TRANSFER]); mtx_unlock(&chan->mtx); return (0); /* success */ detach: return (ENXIO); /* failure */ } static int umidi_detach(device_t dev) { struct uaudio_softc *sc = device_get_softc(dev); struct umidi_chan *chan = &sc->sc_midi_chan; uint32_t n; for (n = 0; n < UMIDI_EMB_JACK_MAX; n++) usb_fifo_detach(&chan->sub[n].fifo); mtx_lock(&chan->mtx); usbd_transfer_stop(chan->xfer[UMIDI_RX_TRANSFER]); mtx_unlock(&chan->mtx); usbd_transfer_unsetup(chan->xfer, UMIDI_N_TRANSFER); mtx_destroy(&chan->mtx); return (0); } static void uaudio_hid_rx_callback(struct usb_xfer *xfer, usb_error_t error) { struct uaudio_softc *sc = usbd_xfer_softc(xfer); const uint8_t *buffer = usbd_xfer_get_frame_buffer(xfer, 0); struct snd_mixer *m; uint8_t id; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTF("actlen=%d\n", actlen); if (actlen != 0 && (sc->sc_hid.flags & UAUDIO_HID_HAS_ID)) { id = *buffer; buffer++; actlen--; } else { id = 0; } m = sc->sc_mixer_dev; if ((sc->sc_hid.flags & UAUDIO_HID_HAS_MUTE) && (sc->sc_hid.mute_id == id) && hid_get_data(buffer, actlen, &sc->sc_hid.mute_loc)) { DPRINTF("Mute toggle\n"); mixer_hwvol_mute_locked(m); } if ((sc->sc_hid.flags & UAUDIO_HID_HAS_VOLUME_UP) && (sc->sc_hid.volume_up_id == id) && hid_get_data(buffer, actlen, &sc->sc_hid.volume_up_loc)) { DPRINTF("Volume Up\n"); mixer_hwvol_step_locked(m, 1, 1); } if ((sc->sc_hid.flags & UAUDIO_HID_HAS_VOLUME_DOWN) && (sc->sc_hid.volume_down_id == id) && hid_get_data(buffer, actlen, &sc->sc_hid.volume_down_loc)) { DPRINTF("Volume Down\n"); mixer_hwvol_step_locked(m, -1, -1); } case USB_ST_SETUP: tr_setup: /* check if we can put more data into the FIFO */ usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: /* Error */ DPRINTF("error=%s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static int uaudio_hid_probe(struct uaudio_softc *sc, struct usb_attach_arg *uaa) { void *d_ptr; uint32_t flags; uint16_t d_len; uint8_t id; int error; if (!(sc->sc_hid.flags & UAUDIO_HID_VALID)) return (-1); if (sc->sc_mixer_lock == NULL) return (-1); /* Get HID descriptor */ error = usbd_req_get_hid_desc(uaa->device, NULL, &d_ptr, &d_len, M_TEMP, sc->sc_hid.iface_index); if (error) { DPRINTF("error reading report description\n"); return (-1); } /* check if there is an ID byte */ hid_report_size(d_ptr, d_len, hid_input, &id); if (id != 0) sc->sc_hid.flags |= UAUDIO_HID_HAS_ID; if (hid_locate(d_ptr, d_len, HID_USAGE2(HUP_CONSUMER, 0xE9 /* Volume Increment */), hid_input, 0, &sc->sc_hid.volume_up_loc, &flags, &sc->sc_hid.volume_up_id)) { if (flags & HIO_VARIABLE) sc->sc_hid.flags |= UAUDIO_HID_HAS_VOLUME_UP; DPRINTFN(1, "Found Volume Up key\n"); } if (hid_locate(d_ptr, d_len, HID_USAGE2(HUP_CONSUMER, 0xEA /* Volume Decrement */), hid_input, 0, &sc->sc_hid.volume_down_loc, &flags, &sc->sc_hid.volume_down_id)) { if (flags & HIO_VARIABLE) sc->sc_hid.flags |= UAUDIO_HID_HAS_VOLUME_DOWN; DPRINTFN(1, "Found Volume Down key\n"); } if (hid_locate(d_ptr, d_len, HID_USAGE2(HUP_CONSUMER, 0xE2 /* Mute */), hid_input, 0, &sc->sc_hid.mute_loc, &flags, &sc->sc_hid.mute_id)) { if (flags & HIO_VARIABLE) sc->sc_hid.flags |= UAUDIO_HID_HAS_MUTE; DPRINTFN(1, "Found Mute key\n"); } free(d_ptr, M_TEMP); if (!(sc->sc_hid.flags & (UAUDIO_HID_HAS_VOLUME_UP | UAUDIO_HID_HAS_VOLUME_DOWN | UAUDIO_HID_HAS_MUTE))) { DPRINTFN(1, "Did not find any volume related keys\n"); return (-1); } /* prevent the uhid driver from attaching */ usbd_set_parent_iface(uaa->device, sc->sc_hid.iface_index, sc->sc_mixer_iface_index); /* allocate USB transfers */ error = usbd_transfer_setup(uaa->device, &sc->sc_hid.iface_index, sc->sc_hid.xfer, uaudio_hid_config, UAUDIO_HID_N_TRANSFER, sc, sc->sc_mixer_lock); if (error) { DPRINTF("error=%s\n", usbd_errstr(error)); return (-1); } return (0); } static void uaudio_hid_detach(struct uaudio_softc *sc) { usbd_transfer_unsetup(sc->sc_hid.xfer, UAUDIO_HID_N_TRANSFER); } DRIVER_MODULE_ORDERED(uaudio, uhub, uaudio_driver, uaudio_devclass, NULL, 0, SI_ORDER_ANY); MODULE_DEPEND(uaudio, usb, 1, 1, 1); MODULE_DEPEND(uaudio, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER); MODULE_VERSION(uaudio, 1); Index: head/sys/dev/usb/controller/at91dci.c =================================================================== --- head/sys/dev/usb/controller/at91dci.c (revision 276700) +++ head/sys/dev/usb/controller/at91dci.c (revision 276701) @@ -1,2380 +1,2380 @@ /* $FreeBSD$ */ /*- * Copyright (c) 2007-2008 Hans Petter Selasky. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * This file contains the driver for the AT91 series USB Device * Controller */ /* * Thanks to "David Brownell" for helping out regarding the hardware * endpoint profiles. */ /* * NOTE: The "fifo_bank" is not reset in hardware when the endpoint is * reset. * * NOTE: When the chip detects BUS-reset it will also reset the * endpoints, Function-address and more. */ #ifdef USB_GLOBAL_INCLUDE_FILE #include USB_GLOBAL_INCLUDE_FILE #else #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define USB_DEBUG_VAR at91dcidebug #include #include #include #include #include #include #include #include #include #include #endif /* USB_GLOBAL_INCLUDE_FILE */ #include #define AT9100_DCI_BUS2SC(bus) \ ((struct at91dci_softc *)(((uint8_t *)(bus)) - \ ((uint8_t *)&(((struct at91dci_softc *)0)->sc_bus)))) #define AT9100_DCI_PC2SC(pc) \ AT9100_DCI_BUS2SC(USB_DMATAG_TO_XROOT((pc)->tag_parent)->bus) #define AT9100_DCI_THREAD_IRQ \ (AT91_UDP_INT_BUS | AT91_UDP_INT_END_BR | AT91_UDP_INT_RXRSM | AT91_UDP_INT_RXSUSP) #ifdef USB_DEBUG static int at91dcidebug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, at91dci, CTLFLAG_RW, 0, "USB at91dci"); -SYSCTL_INT(_hw_usb_at91dci, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_at91dci, OID_AUTO, debug, CTLFLAG_RWTUN, &at91dcidebug, 0, "at91dci debug level"); #endif #define AT9100_DCI_INTR_ENDPT 1 /* prototypes */ static const struct usb_bus_methods at91dci_bus_methods; static const struct usb_pipe_methods at91dci_device_bulk_methods; static const struct usb_pipe_methods at91dci_device_ctrl_methods; static const struct usb_pipe_methods at91dci_device_intr_methods; static const struct usb_pipe_methods at91dci_device_isoc_fs_methods; static at91dci_cmd_t at91dci_setup_rx; static at91dci_cmd_t at91dci_data_rx; static at91dci_cmd_t at91dci_data_tx; static at91dci_cmd_t at91dci_data_tx_sync; static void at91dci_device_done(struct usb_xfer *, usb_error_t); static void at91dci_do_poll(struct usb_bus *); static void at91dci_standard_done(struct usb_xfer *); static void at91dci_root_intr(struct at91dci_softc *sc); /* * NOTE: Some of the bits in the CSR register have inverse meaning so * we need a helper macro when acknowledging events: */ #define AT91_CSR_ACK(csr, what) do { \ (csr) &= ~((AT91_UDP_CSR_FORCESTALL| \ AT91_UDP_CSR_TXPKTRDY| \ AT91_UDP_CSR_RXBYTECNT) ^ (what));\ (csr) |= ((AT91_UDP_CSR_RX_DATA_BK0| \ AT91_UDP_CSR_RX_DATA_BK1| \ AT91_UDP_CSR_TXCOMP| \ AT91_UDP_CSR_RXSETUP| \ AT91_UDP_CSR_STALLSENT) ^ (what)); \ } while (0) /* * Here is a list of what the chip supports. * Probably it supports more than listed here! */ static const struct usb_hw_ep_profile at91dci_ep_profile[AT91_UDP_EP_MAX] = { [0] = { .max_in_frame_size = 8, .max_out_frame_size = 8, .is_simplex = 1, .support_control = 1, }, [1] = { .max_in_frame_size = 64, .max_out_frame_size = 64, .is_simplex = 1, .support_multi_buffer = 1, .support_bulk = 1, .support_interrupt = 1, .support_isochronous = 1, .support_in = 1, .support_out = 1, }, [2] = { .max_in_frame_size = 64, .max_out_frame_size = 64, .is_simplex = 1, .support_multi_buffer = 1, .support_bulk = 1, .support_interrupt = 1, .support_isochronous = 1, .support_in = 1, .support_out = 1, }, [3] = { /* can also do BULK */ .max_in_frame_size = 8, .max_out_frame_size = 8, .is_simplex = 1, .support_interrupt = 1, .support_in = 1, .support_out = 1, }, [4] = { .max_in_frame_size = 256, .max_out_frame_size = 256, .is_simplex = 1, .support_multi_buffer = 1, .support_bulk = 1, .support_interrupt = 1, .support_isochronous = 1, .support_in = 1, .support_out = 1, }, [5] = { .max_in_frame_size = 256, .max_out_frame_size = 256, .is_simplex = 1, .support_multi_buffer = 1, .support_bulk = 1, .support_interrupt = 1, .support_isochronous = 1, .support_in = 1, .support_out = 1, }, }; static void at91dci_get_hw_ep_profile(struct usb_device *udev, const struct usb_hw_ep_profile **ppf, uint8_t ep_addr) { if (ep_addr < AT91_UDP_EP_MAX) { *ppf = (at91dci_ep_profile + ep_addr); } else { *ppf = NULL; } } static void at91dci_clocks_on(struct at91dci_softc *sc) { if (sc->sc_flags.clocks_off && sc->sc_flags.port_powered) { DPRINTFN(5, "\n"); if (sc->sc_clocks_on) { (sc->sc_clocks_on) (sc->sc_clocks_arg); } sc->sc_flags.clocks_off = 0; /* enable Transceiver */ AT91_UDP_WRITE_4(sc, AT91_UDP_TXVC, 0); } } static void at91dci_clocks_off(struct at91dci_softc *sc) { if (!sc->sc_flags.clocks_off) { DPRINTFN(5, "\n"); /* disable Transceiver */ AT91_UDP_WRITE_4(sc, AT91_UDP_TXVC, AT91_UDP_TXVC_DIS); if (sc->sc_clocks_off) { (sc->sc_clocks_off) (sc->sc_clocks_arg); } sc->sc_flags.clocks_off = 1; } } static void at91dci_pull_up(struct at91dci_softc *sc) { /* pullup D+, if possible */ if (!sc->sc_flags.d_pulled_up && sc->sc_flags.port_powered) { sc->sc_flags.d_pulled_up = 1; (sc->sc_pull_up) (sc->sc_pull_arg); } } static void at91dci_pull_down(struct at91dci_softc *sc) { /* pulldown D+, if possible */ if (sc->sc_flags.d_pulled_up) { sc->sc_flags.d_pulled_up = 0; (sc->sc_pull_down) (sc->sc_pull_arg); } } static void at91dci_wakeup_peer(struct at91dci_softc *sc) { if (!(sc->sc_flags.status_suspend)) { return; } AT91_UDP_WRITE_4(sc, AT91_UDP_GSTATE, AT91_UDP_GSTATE_ESR); /* wait 8 milliseconds */ /* Wait for reset to complete. */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 125); AT91_UDP_WRITE_4(sc, AT91_UDP_GSTATE, 0); } static void at91dci_set_address(struct at91dci_softc *sc, uint8_t addr) { DPRINTFN(5, "addr=%d\n", addr); AT91_UDP_WRITE_4(sc, AT91_UDP_FADDR, addr | AT91_UDP_FADDR_EN); } static uint8_t at91dci_setup_rx(struct at91dci_softc *sc, struct at91dci_td *td) { struct usb_device_request req; uint32_t csr; uint32_t temp; uint16_t count; /* read out FIFO status */ csr = AT91_UDP_READ_4(sc, td->status_reg); DPRINTFN(5, "csr=0x%08x rem=%u\n", csr, td->remainder); temp = csr; temp &= (AT91_UDP_CSR_RX_DATA_BK0 | AT91_UDP_CSR_RX_DATA_BK1 | AT91_UDP_CSR_STALLSENT | AT91_UDP_CSR_RXSETUP | AT91_UDP_CSR_TXCOMP); if (!(csr & AT91_UDP_CSR_RXSETUP)) { goto not_complete; } /* clear did stall */ td->did_stall = 0; /* get the packet byte count */ count = (csr & AT91_UDP_CSR_RXBYTECNT) >> 16; /* verify data length */ if (count != td->remainder) { DPRINTFN(0, "Invalid SETUP packet " "length, %d bytes\n", count); goto not_complete; } if (count != sizeof(req)) { DPRINTFN(0, "Unsupported SETUP packet " "length, %d bytes\n", count); goto not_complete; } /* receive data */ bus_space_read_multi_1(sc->sc_io_tag, sc->sc_io_hdl, td->fifo_reg, (void *)&req, sizeof(req)); /* copy data into real buffer */ usbd_copy_in(td->pc, 0, &req, sizeof(req)); td->offset = sizeof(req); td->remainder = 0; /* sneak peek the set address */ if ((req.bmRequestType == UT_WRITE_DEVICE) && (req.bRequest == UR_SET_ADDRESS)) { sc->sc_dv_addr = req.wValue[0] & 0x7F; } else { sc->sc_dv_addr = 0xFF; } /* sneak peek the endpoint direction */ if (req.bmRequestType & UE_DIR_IN) { csr |= AT91_UDP_CSR_DIR; } else { csr &= ~AT91_UDP_CSR_DIR; } /* write the direction of the control transfer */ AT91_CSR_ACK(csr, temp); AT91_UDP_WRITE_4(sc, td->status_reg, csr); return (0); /* complete */ not_complete: /* abort any ongoing transfer */ if (!td->did_stall) { DPRINTFN(5, "stalling\n"); temp |= AT91_UDP_CSR_FORCESTALL; td->did_stall = 1; } /* clear interrupts, if any */ if (temp) { DPRINTFN(5, "clearing 0x%08x\n", temp); AT91_CSR_ACK(csr, temp); AT91_UDP_WRITE_4(sc, td->status_reg, csr); } return (1); /* not complete */ } static uint8_t at91dci_data_rx(struct at91dci_softc *sc, struct at91dci_td *td) { struct usb_page_search buf_res; uint32_t csr; uint32_t temp; uint16_t count; uint8_t to; uint8_t got_short; to = 2; /* don't loop forever! */ got_short = 0; /* check if any of the FIFO banks have data */ repeat: /* read out FIFO status */ csr = AT91_UDP_READ_4(sc, td->status_reg); DPRINTFN(5, "csr=0x%08x rem=%u\n", csr, td->remainder); if (csr & AT91_UDP_CSR_RXSETUP) { if (td->remainder == 0) { /* * We are actually complete and have * received the next SETUP */ DPRINTFN(5, "faking complete\n"); return (0); /* complete */ } /* * USB Host Aborted the transfer. */ td->error = 1; return (0); /* complete */ } /* Make sure that "STALLSENT" gets cleared */ temp = csr; temp &= AT91_UDP_CSR_STALLSENT; /* check status */ if (!(csr & (AT91_UDP_CSR_RX_DATA_BK0 | AT91_UDP_CSR_RX_DATA_BK1))) { if (temp) { /* write command */ AT91_CSR_ACK(csr, temp); AT91_UDP_WRITE_4(sc, td->status_reg, csr); } return (1); /* not complete */ } /* get the packet byte count */ count = (csr & AT91_UDP_CSR_RXBYTECNT) >> 16; /* verify the packet byte count */ if (count != td->max_packet_size) { if (count < td->max_packet_size) { /* we have a short packet */ td->short_pkt = 1; got_short = 1; } else { /* invalid USB packet */ td->error = 1; return (0); /* we are complete */ } } /* verify the packet byte count */ if (count > td->remainder) { /* invalid USB packet */ td->error = 1; return (0); /* we are complete */ } while (count > 0) { usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* receive data */ bus_space_read_multi_1(sc->sc_io_tag, sc->sc_io_hdl, td->fifo_reg, buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* clear status bits */ if (td->support_multi_buffer) { if (td->fifo_bank) { td->fifo_bank = 0; temp |= AT91_UDP_CSR_RX_DATA_BK1; } else { td->fifo_bank = 1; temp |= AT91_UDP_CSR_RX_DATA_BK0; } } else { temp |= (AT91_UDP_CSR_RX_DATA_BK0 | AT91_UDP_CSR_RX_DATA_BK1); } /* write command */ AT91_CSR_ACK(csr, temp); AT91_UDP_WRITE_4(sc, td->status_reg, csr); /* * NOTE: We may have to delay a little bit before * proceeding after clearing the DATA_BK bits. */ /* check if we are complete */ if ((td->remainder == 0) || got_short) { if (td->short_pkt) { /* we are complete */ return (0); } /* else need to receive a zero length packet */ } if (--to) { goto repeat; } return (1); /* not complete */ } static uint8_t at91dci_data_tx(struct at91dci_softc *sc, struct at91dci_td *td) { struct usb_page_search buf_res; uint32_t csr; uint32_t temp; uint16_t count; uint8_t to; to = 2; /* don't loop forever! */ repeat: /* read out FIFO status */ csr = AT91_UDP_READ_4(sc, td->status_reg); DPRINTFN(5, "csr=0x%08x rem=%u\n", csr, td->remainder); if (csr & AT91_UDP_CSR_RXSETUP) { /* * The current transfer was aborted * by the USB Host */ td->error = 1; return (0); /* complete */ } /* Make sure that "STALLSENT" gets cleared */ temp = csr; temp &= AT91_UDP_CSR_STALLSENT; if (csr & AT91_UDP_CSR_TXPKTRDY) { if (temp) { /* write command */ AT91_CSR_ACK(csr, temp); AT91_UDP_WRITE_4(sc, td->status_reg, csr); } return (1); /* not complete */ } else { /* clear TXCOMP and set TXPKTRDY */ temp |= (AT91_UDP_CSR_TXCOMP | AT91_UDP_CSR_TXPKTRDY); } count = td->max_packet_size; if (td->remainder < count) { /* we have a short packet */ td->short_pkt = 1; count = td->remainder; } while (count > 0) { usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* transmit data */ bus_space_write_multi_1(sc->sc_io_tag, sc->sc_io_hdl, td->fifo_reg, buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* write command */ AT91_CSR_ACK(csr, temp); AT91_UDP_WRITE_4(sc, td->status_reg, csr); /* check remainder */ if (td->remainder == 0) { if (td->short_pkt) { return (0); /* complete */ } /* else we need to transmit a short packet */ } if (--to) { goto repeat; } return (1); /* not complete */ } static uint8_t at91dci_data_tx_sync(struct at91dci_softc *sc, struct at91dci_td *td) { uint32_t csr; uint32_t temp; /* read out FIFO status */ csr = AT91_UDP_READ_4(sc, td->status_reg); DPRINTFN(5, "csr=0x%08x\n", csr); if (csr & AT91_UDP_CSR_RXSETUP) { DPRINTFN(5, "faking complete\n"); /* Race condition */ return (0); /* complete */ } temp = csr; temp &= (AT91_UDP_CSR_STALLSENT | AT91_UDP_CSR_TXCOMP); /* check status */ if (csr & AT91_UDP_CSR_TXPKTRDY) { goto not_complete; } if (!(csr & AT91_UDP_CSR_TXCOMP)) { goto not_complete; } if (td->status_reg == AT91_UDP_CSR(0) && sc->sc_dv_addr != 0xFF) { /* * The AT91 has a special requirement with regard to * setting the address and that is to write the new * address before clearing TXCOMP: */ at91dci_set_address(sc, sc->sc_dv_addr); } /* write command */ AT91_CSR_ACK(csr, temp); AT91_UDP_WRITE_4(sc, td->status_reg, csr); return (0); /* complete */ not_complete: if (temp) { /* write command */ AT91_CSR_ACK(csr, temp); AT91_UDP_WRITE_4(sc, td->status_reg, csr); } return (1); /* not complete */ } static void at91dci_xfer_do_fifo(struct usb_xfer *xfer) { struct at91dci_softc *sc = AT9100_DCI_BUS2SC(xfer->xroot->bus); struct at91dci_td *td; uint8_t temp; DPRINTFN(9, "\n"); td = xfer->td_transfer_cache; if (td == NULL) return; while (1) { if ((td->func) (sc, td)) { /* operation in progress */ break; } if (((void *)td) == xfer->td_transfer_last) { goto done; } if (td->error) { goto done; } else if (td->remainder > 0) { /* * We had a short transfer. If there is no alternate * next, stop processing ! */ if (!td->alt_next) { goto done; } } /* * Fetch the next transfer descriptor and transfer * some flags to the next transfer descriptor */ temp = 0; if (td->fifo_bank) temp |= 1; td = td->obj_next; xfer->td_transfer_cache = td; if (temp & 1) td->fifo_bank = 1; } return; done: temp = (xfer->endpointno & UE_ADDR); /* update FIFO bank flag and multi buffer */ if (td->fifo_bank) { sc->sc_ep_flags[temp].fifo_bank = 1; } else { sc->sc_ep_flags[temp].fifo_bank = 0; } /* compute all actual lengths */ xfer->td_transfer_cache = NULL; sc->sc_xfer_complete = 1; } static uint8_t at91dci_xfer_do_complete(struct usb_xfer *xfer) { struct at91dci_td *td; DPRINTFN(9, "\n"); td = xfer->td_transfer_cache; if (td == NULL) { /* compute all actual lengths */ at91dci_standard_done(xfer); return(1); } return (0); } static void at91dci_interrupt_poll_locked(struct at91dci_softc *sc) { struct usb_xfer *xfer; TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) at91dci_xfer_do_fifo(xfer); } static void at91dci_interrupt_complete_locked(struct at91dci_softc *sc) { struct usb_xfer *xfer; repeat: TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) { if (at91dci_xfer_do_complete(xfer)) goto repeat; } } void at91dci_vbus_interrupt(struct at91dci_softc *sc, uint8_t is_on) { DPRINTFN(5, "vbus = %u\n", is_on); if (is_on) { if (!sc->sc_flags.status_vbus) { sc->sc_flags.status_vbus = 1; /* complete root HUB interrupt endpoint */ at91dci_root_intr(sc); } } else { if (sc->sc_flags.status_vbus) { sc->sc_flags.status_vbus = 0; sc->sc_flags.status_bus_reset = 0; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; /* complete root HUB interrupt endpoint */ at91dci_root_intr(sc); } } } int at91dci_filter_interrupt(void *arg) { struct at91dci_softc *sc = arg; int retval = FILTER_HANDLED; uint32_t status; USB_BUS_SPIN_LOCK(&sc->sc_bus); status = AT91_UDP_READ_4(sc, AT91_UDP_ISR); status &= AT91_UDP_INT_DEFAULT; if (status & AT9100_DCI_THREAD_IRQ) retval = FILTER_SCHEDULE_THREAD; /* acknowledge interrupts */ AT91_UDP_WRITE_4(sc, AT91_UDP_ICR, status & ~AT9100_DCI_THREAD_IRQ); /* poll FIFOs, if any */ at91dci_interrupt_poll_locked(sc); if (sc->sc_xfer_complete != 0) retval = FILTER_SCHEDULE_THREAD; USB_BUS_SPIN_UNLOCK(&sc->sc_bus); return (retval); } void at91dci_interrupt(void *arg) { struct at91dci_softc *sc = arg; uint32_t status; USB_BUS_LOCK(&sc->sc_bus); USB_BUS_SPIN_LOCK(&sc->sc_bus); status = AT91_UDP_READ_4(sc, AT91_UDP_ISR); status &= AT9100_DCI_THREAD_IRQ; /* acknowledge interrupts */ AT91_UDP_WRITE_4(sc, AT91_UDP_ICR, status); /* check for any bus state change interrupts */ if (status & AT91_UDP_INT_BUS) { DPRINTFN(5, "real bus interrupt 0x%08x\n", status); if (status & AT91_UDP_INT_END_BR) { /* set correct state */ sc->sc_flags.status_bus_reset = 1; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; /* disable resume interrupt */ AT91_UDP_WRITE_4(sc, AT91_UDP_IDR, AT91_UDP_INT_RXRSM); /* enable suspend interrupt */ AT91_UDP_WRITE_4(sc, AT91_UDP_IER, AT91_UDP_INT_RXSUSP); } /* * If RXRSM and RXSUSP is set at the same time we interpret * that like RESUME. Resume is set when there is at least 3 * milliseconds of inactivity on the USB BUS. */ if (status & AT91_UDP_INT_RXRSM) { if (sc->sc_flags.status_suspend) { sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 1; /* disable resume interrupt */ AT91_UDP_WRITE_4(sc, AT91_UDP_IDR, AT91_UDP_INT_RXRSM); /* enable suspend interrupt */ AT91_UDP_WRITE_4(sc, AT91_UDP_IER, AT91_UDP_INT_RXSUSP); } } else if (status & AT91_UDP_INT_RXSUSP) { if (!sc->sc_flags.status_suspend) { sc->sc_flags.status_suspend = 1; sc->sc_flags.change_suspend = 1; /* disable suspend interrupt */ AT91_UDP_WRITE_4(sc, AT91_UDP_IDR, AT91_UDP_INT_RXSUSP); /* enable resume interrupt */ AT91_UDP_WRITE_4(sc, AT91_UDP_IER, AT91_UDP_INT_RXRSM); } } /* complete root HUB interrupt endpoint */ at91dci_root_intr(sc); } if (sc->sc_xfer_complete != 0) { sc->sc_xfer_complete = 0; at91dci_interrupt_complete_locked(sc); } USB_BUS_SPIN_UNLOCK(&sc->sc_bus); USB_BUS_UNLOCK(&sc->sc_bus); } static void at91dci_setup_standard_chain_sub(struct at91dci_std_temp *temp) { struct at91dci_td *td; /* get current Transfer Descriptor */ td = temp->td_next; temp->td = td; /* prepare for next TD */ temp->td_next = td->obj_next; /* fill out the Transfer Descriptor */ td->func = temp->func; td->pc = temp->pc; td->offset = temp->offset; td->remainder = temp->len; td->fifo_bank = 0; td->error = 0; td->did_stall = temp->did_stall; td->short_pkt = temp->short_pkt; td->alt_next = temp->setup_alt_next; } static void at91dci_setup_standard_chain(struct usb_xfer *xfer) { struct at91dci_std_temp temp; struct at91dci_softc *sc; struct at91dci_td *td; uint32_t x; uint8_t ep_no; uint8_t need_sync; DPRINTFN(9, "addr=%d endpt=%d sumlen=%d speed=%d\n", xfer->address, UE_GET_ADDR(xfer->endpointno), xfer->sumlen, usbd_get_speed(xfer->xroot->udev)); temp.max_frame_size = xfer->max_frame_size; td = xfer->td_start[0]; xfer->td_transfer_first = td; xfer->td_transfer_cache = td; /* setup temp */ temp.pc = NULL; temp.td = NULL; temp.td_next = xfer->td_start[0]; temp.offset = 0; temp.setup_alt_next = xfer->flags_int.short_frames_ok || xfer->flags_int.isochronous_xfr; temp.did_stall = !xfer->flags_int.control_stall; sc = AT9100_DCI_BUS2SC(xfer->xroot->bus); ep_no = (xfer->endpointno & UE_ADDR); /* check if we should prepend a setup message */ if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_hdr) { temp.func = &at91dci_setup_rx; temp.len = xfer->frlengths[0]; temp.pc = xfer->frbuffers + 0; temp.short_pkt = temp.len ? 1 : 0; /* check for last frame */ if (xfer->nframes == 1) { /* no STATUS stage yet, SETUP is last */ if (xfer->flags_int.control_act) temp.setup_alt_next = 0; } at91dci_setup_standard_chain_sub(&temp); } x = 1; } else { x = 0; } if (x != xfer->nframes) { if (xfer->endpointno & UE_DIR_IN) { temp.func = &at91dci_data_tx; need_sync = 1; } else { temp.func = &at91dci_data_rx; need_sync = 0; } /* setup "pc" pointer */ temp.pc = xfer->frbuffers + x; } else { need_sync = 0; } while (x != xfer->nframes) { /* DATA0 / DATA1 message */ temp.len = xfer->frlengths[x]; x++; if (x == xfer->nframes) { if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_act) { temp.setup_alt_next = 0; } } else { temp.setup_alt_next = 0; } } if (temp.len == 0) { /* make sure that we send an USB packet */ temp.short_pkt = 0; } else { /* regular data transfer */ temp.short_pkt = (xfer->flags.force_short_xfer) ? 0 : 1; } at91dci_setup_standard_chain_sub(&temp); if (xfer->flags_int.isochronous_xfr) { temp.offset += temp.len; } else { /* get next Page Cache pointer */ temp.pc = xfer->frbuffers + x; } } /* check for control transfer */ if (xfer->flags_int.control_xfr) { /* always setup a valid "pc" pointer for status and sync */ temp.pc = xfer->frbuffers + 0; temp.len = 0; temp.short_pkt = 0; temp.setup_alt_next = 0; /* check if we need to sync */ if (need_sync) { /* we need a SYNC point after TX */ temp.func = &at91dci_data_tx_sync; at91dci_setup_standard_chain_sub(&temp); } /* check if we should append a status stage */ if (!xfer->flags_int.control_act) { /* * Send a DATA1 message and invert the current * endpoint direction. */ if (xfer->endpointno & UE_DIR_IN) { temp.func = &at91dci_data_rx; need_sync = 0; } else { temp.func = &at91dci_data_tx; need_sync = 1; } at91dci_setup_standard_chain_sub(&temp); if (need_sync) { /* we need a SYNC point after TX */ temp.func = &at91dci_data_tx_sync; at91dci_setup_standard_chain_sub(&temp); } } } /* must have at least one frame! */ td = temp.td; xfer->td_transfer_last = td; /* setup the correct fifo bank */ if (sc->sc_ep_flags[ep_no].fifo_bank) { td = xfer->td_transfer_first; td->fifo_bank = 1; } } static void at91dci_timeout(void *arg) { struct usb_xfer *xfer = arg; DPRINTF("xfer=%p\n", xfer); USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED); /* transfer is transferred */ at91dci_device_done(xfer, USB_ERR_TIMEOUT); } static void at91dci_start_standard_chain(struct usb_xfer *xfer) { struct at91dci_softc *sc = AT9100_DCI_BUS2SC(xfer->xroot->bus); DPRINTFN(9, "\n"); USB_BUS_SPIN_LOCK(&sc->sc_bus); /* poll one time */ at91dci_xfer_do_fifo(xfer); if (at91dci_xfer_do_complete(xfer) == 0) { uint8_t ep_no = xfer->endpointno & UE_ADDR; /* * Only enable the endpoint interrupt when we are actually * waiting for data, hence we are dealing with level * triggered interrupts ! */ AT91_UDP_WRITE_4(sc, AT91_UDP_IER, AT91_UDP_INT_EP(ep_no)); DPRINTFN(15, "enable interrupts on endpoint %d\n", ep_no); /* put transfer on interrupt queue */ usbd_transfer_enqueue(&xfer->xroot->bus->intr_q, xfer); /* start timeout, if any */ if (xfer->timeout != 0) { usbd_transfer_timeout_ms(xfer, &at91dci_timeout, xfer->timeout); } } USB_BUS_SPIN_UNLOCK(&sc->sc_bus); } static void at91dci_root_intr(struct at91dci_softc *sc) { DPRINTFN(9, "\n"); USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); /* set port bit */ sc->sc_hub_idata[0] = 0x02; /* we only have one port */ uhub_root_intr(&sc->sc_bus, sc->sc_hub_idata, sizeof(sc->sc_hub_idata)); } static usb_error_t at91dci_standard_done_sub(struct usb_xfer *xfer) { struct at91dci_td *td; uint32_t len; uint8_t error; DPRINTFN(9, "\n"); td = xfer->td_transfer_cache; do { len = td->remainder; if (xfer->aframes != xfer->nframes) { /* * Verify the length and subtract * the remainder from "frlengths[]": */ if (len > xfer->frlengths[xfer->aframes]) { td->error = 1; } else { xfer->frlengths[xfer->aframes] -= len; } } /* Check for transfer error */ if (td->error) { /* the transfer is finished */ error = 1; td = NULL; break; } /* Check for short transfer */ if (len > 0) { if (xfer->flags_int.short_frames_ok || xfer->flags_int.isochronous_xfr) { /* follow alt next */ if (td->alt_next) { td = td->obj_next; } else { td = NULL; } } else { /* the transfer is finished */ td = NULL; } error = 0; break; } td = td->obj_next; /* this USB frame is complete */ error = 0; break; } while (0); /* update transfer cache */ xfer->td_transfer_cache = td; return (error ? USB_ERR_STALLED : USB_ERR_NORMAL_COMPLETION); } static void at91dci_standard_done(struct usb_xfer *xfer) { usb_error_t err = 0; DPRINTFN(13, "xfer=%p endpoint=%p transfer done\n", xfer, xfer->endpoint); /* reset scanner */ xfer->td_transfer_cache = xfer->td_transfer_first; if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_hdr) { err = at91dci_standard_done_sub(xfer); } xfer->aframes = 1; if (xfer->td_transfer_cache == NULL) { goto done; } } while (xfer->aframes != xfer->nframes) { err = at91dci_standard_done_sub(xfer); xfer->aframes++; if (xfer->td_transfer_cache == NULL) { goto done; } } if (xfer->flags_int.control_xfr && !xfer->flags_int.control_act) { err = at91dci_standard_done_sub(xfer); } done: at91dci_device_done(xfer, err); } /*------------------------------------------------------------------------* * at91dci_device_done * * NOTE: this function can be called more than one time on the * same USB transfer! *------------------------------------------------------------------------*/ static void at91dci_device_done(struct usb_xfer *xfer, usb_error_t error) { struct at91dci_softc *sc = AT9100_DCI_BUS2SC(xfer->xroot->bus); uint8_t ep_no; USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); DPRINTFN(2, "xfer=%p, endpoint=%p, error=%d\n", xfer, xfer->endpoint, error); USB_BUS_SPIN_LOCK(&sc->sc_bus); if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) { ep_no = (xfer->endpointno & UE_ADDR); /* disable endpoint interrupt */ AT91_UDP_WRITE_4(sc, AT91_UDP_IDR, AT91_UDP_INT_EP(ep_no)); DPRINTFN(15, "disable interrupts on endpoint %d\n", ep_no); } /* dequeue transfer and start next transfer */ usbd_transfer_done(xfer, error); USB_BUS_SPIN_UNLOCK(&sc->sc_bus); } static void at91dci_xfer_stall(struct usb_xfer *xfer) { at91dci_device_done(xfer, USB_ERR_STALLED); } static void at91dci_set_stall(struct usb_device *udev, struct usb_endpoint *ep, uint8_t *did_stall) { struct at91dci_softc *sc; uint32_t csr_val; uint8_t csr_reg; USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED); DPRINTFN(5, "endpoint=%p\n", ep); /* set FORCESTALL */ sc = AT9100_DCI_BUS2SC(udev->bus); USB_BUS_SPIN_LOCK(&sc->sc_bus); csr_reg = (ep->edesc->bEndpointAddress & UE_ADDR); csr_reg = AT91_UDP_CSR(csr_reg); csr_val = AT91_UDP_READ_4(sc, csr_reg); AT91_CSR_ACK(csr_val, AT91_UDP_CSR_FORCESTALL); AT91_UDP_WRITE_4(sc, csr_reg, csr_val); USB_BUS_SPIN_UNLOCK(&sc->sc_bus); } static void at91dci_clear_stall_sub(struct at91dci_softc *sc, uint8_t ep_no, uint8_t ep_type, uint8_t ep_dir) { const struct usb_hw_ep_profile *pf; uint32_t csr_val; uint32_t temp; uint8_t csr_reg; uint8_t to; if (ep_type == UE_CONTROL) { /* clearing stall is not needed */ return; } USB_BUS_SPIN_LOCK(&sc->sc_bus); /* compute CSR register offset */ csr_reg = AT91_UDP_CSR(ep_no); /* compute default CSR value */ csr_val = 0; AT91_CSR_ACK(csr_val, 0); /* disable endpoint */ AT91_UDP_WRITE_4(sc, csr_reg, csr_val); /* get endpoint profile */ at91dci_get_hw_ep_profile(NULL, &pf, ep_no); /* reset FIFO */ AT91_UDP_WRITE_4(sc, AT91_UDP_RST, AT91_UDP_RST_EP(ep_no)); AT91_UDP_WRITE_4(sc, AT91_UDP_RST, 0); /* * NOTE: One would assume that a FIFO reset would release the * FIFO banks aswell, but it doesn't! We have to do this * manually! */ /* release FIFO banks, if any */ for (to = 0; to != 2; to++) { /* get csr value */ csr_val = AT91_UDP_READ_4(sc, csr_reg); if (csr_val & (AT91_UDP_CSR_RX_DATA_BK0 | AT91_UDP_CSR_RX_DATA_BK1)) { /* clear status bits */ if (pf->support_multi_buffer) { if (sc->sc_ep_flags[ep_no].fifo_bank) { sc->sc_ep_flags[ep_no].fifo_bank = 0; temp = AT91_UDP_CSR_RX_DATA_BK1; } else { sc->sc_ep_flags[ep_no].fifo_bank = 1; temp = AT91_UDP_CSR_RX_DATA_BK0; } } else { temp = (AT91_UDP_CSR_RX_DATA_BK0 | AT91_UDP_CSR_RX_DATA_BK1); } } else { temp = 0; } /* clear FORCESTALL */ temp |= AT91_UDP_CSR_STALLSENT; AT91_CSR_ACK(csr_val, temp); AT91_UDP_WRITE_4(sc, csr_reg, csr_val); } /* compute default CSR value */ csr_val = 0; AT91_CSR_ACK(csr_val, 0); /* enable endpoint */ csr_val &= ~AT91_UDP_CSR_ET_MASK; csr_val |= AT91_UDP_CSR_EPEDS; if (ep_type == UE_CONTROL) { csr_val |= AT91_UDP_CSR_ET_CTRL; } else { if (ep_type == UE_BULK) { csr_val |= AT91_UDP_CSR_ET_BULK; } else if (ep_type == UE_INTERRUPT) { csr_val |= AT91_UDP_CSR_ET_INT; } else { csr_val |= AT91_UDP_CSR_ET_ISO; } if (ep_dir & UE_DIR_IN) { csr_val |= AT91_UDP_CSR_ET_DIR_IN; } } /* enable endpoint */ AT91_UDP_WRITE_4(sc, AT91_UDP_CSR(ep_no), csr_val); USB_BUS_SPIN_UNLOCK(&sc->sc_bus); } static void at91dci_clear_stall(struct usb_device *udev, struct usb_endpoint *ep) { struct at91dci_softc *sc; struct usb_endpoint_descriptor *ed; DPRINTFN(5, "endpoint=%p\n", ep); USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED); /* check mode */ if (udev->flags.usb_mode != USB_MODE_DEVICE) { /* not supported */ return; } /* get softc */ sc = AT9100_DCI_BUS2SC(udev->bus); /* get endpoint descriptor */ ed = ep->edesc; /* reset endpoint */ at91dci_clear_stall_sub(sc, (ed->bEndpointAddress & UE_ADDR), (ed->bmAttributes & UE_XFERTYPE), (ed->bEndpointAddress & (UE_DIR_IN | UE_DIR_OUT))); } usb_error_t at91dci_init(struct at91dci_softc *sc) { uint32_t csr_val; uint8_t n; DPRINTF("start\n"); /* set up the bus structure */ sc->sc_bus.usbrev = USB_REV_1_1; sc->sc_bus.methods = &at91dci_bus_methods; USB_BUS_LOCK(&sc->sc_bus); /* turn on clocks */ if (sc->sc_clocks_on) { (sc->sc_clocks_on) (sc->sc_clocks_arg); } /* wait a little for things to stabilise */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 1000); /* disable and clear all interrupts */ AT91_UDP_WRITE_4(sc, AT91_UDP_IDR, 0xFFFFFFFF); AT91_UDP_WRITE_4(sc, AT91_UDP_ICR, 0xFFFFFFFF); /* compute default CSR value */ csr_val = 0; AT91_CSR_ACK(csr_val, 0); /* disable all endpoints */ for (n = 0; n != AT91_UDP_EP_MAX; n++) { /* disable endpoint */ AT91_UDP_WRITE_4(sc, AT91_UDP_CSR(n), csr_val); } /* enable the control endpoint */ AT91_CSR_ACK(csr_val, AT91_UDP_CSR_ET_CTRL | AT91_UDP_CSR_EPEDS); /* write to FIFO control register */ AT91_UDP_WRITE_4(sc, AT91_UDP_CSR(0), csr_val); /* enable the interrupts we want */ AT91_UDP_WRITE_4(sc, AT91_UDP_IER, AT91_UDP_INT_BUS); /* turn off clocks */ at91dci_clocks_off(sc); USB_BUS_UNLOCK(&sc->sc_bus); /* catch any lost interrupts */ at91dci_do_poll(&sc->sc_bus); return (0); /* success */ } void at91dci_uninit(struct at91dci_softc *sc) { USB_BUS_LOCK(&sc->sc_bus); /* disable and clear all interrupts */ AT91_UDP_WRITE_4(sc, AT91_UDP_IDR, 0xFFFFFFFF); AT91_UDP_WRITE_4(sc, AT91_UDP_ICR, 0xFFFFFFFF); sc->sc_flags.port_powered = 0; sc->sc_flags.status_vbus = 0; sc->sc_flags.status_bus_reset = 0; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; at91dci_pull_down(sc); at91dci_clocks_off(sc); USB_BUS_UNLOCK(&sc->sc_bus); } static void at91dci_suspend(struct at91dci_softc *sc) { /* TODO */ } static void at91dci_resume(struct at91dci_softc *sc) { /* TODO */ } static void at91dci_do_poll(struct usb_bus *bus) { struct at91dci_softc *sc = AT9100_DCI_BUS2SC(bus); USB_BUS_LOCK(&sc->sc_bus); USB_BUS_SPIN_LOCK(&sc->sc_bus); at91dci_interrupt_poll_locked(sc); at91dci_interrupt_complete_locked(sc); USB_BUS_SPIN_UNLOCK(&sc->sc_bus); USB_BUS_UNLOCK(&sc->sc_bus); } /*------------------------------------------------------------------------* * at91dci bulk support *------------------------------------------------------------------------*/ static void at91dci_device_bulk_open(struct usb_xfer *xfer) { return; } static void at91dci_device_bulk_close(struct usb_xfer *xfer) { at91dci_device_done(xfer, USB_ERR_CANCELLED); } static void at91dci_device_bulk_enter(struct usb_xfer *xfer) { return; } static void at91dci_device_bulk_start(struct usb_xfer *xfer) { /* setup TDs */ at91dci_setup_standard_chain(xfer); at91dci_start_standard_chain(xfer); } static const struct usb_pipe_methods at91dci_device_bulk_methods = { .open = at91dci_device_bulk_open, .close = at91dci_device_bulk_close, .enter = at91dci_device_bulk_enter, .start = at91dci_device_bulk_start, }; /*------------------------------------------------------------------------* * at91dci control support *------------------------------------------------------------------------*/ static void at91dci_device_ctrl_open(struct usb_xfer *xfer) { return; } static void at91dci_device_ctrl_close(struct usb_xfer *xfer) { at91dci_device_done(xfer, USB_ERR_CANCELLED); } static void at91dci_device_ctrl_enter(struct usb_xfer *xfer) { return; } static void at91dci_device_ctrl_start(struct usb_xfer *xfer) { /* setup TDs */ at91dci_setup_standard_chain(xfer); at91dci_start_standard_chain(xfer); } static const struct usb_pipe_methods at91dci_device_ctrl_methods = { .open = at91dci_device_ctrl_open, .close = at91dci_device_ctrl_close, .enter = at91dci_device_ctrl_enter, .start = at91dci_device_ctrl_start, }; /*------------------------------------------------------------------------* * at91dci interrupt support *------------------------------------------------------------------------*/ static void at91dci_device_intr_open(struct usb_xfer *xfer) { return; } static void at91dci_device_intr_close(struct usb_xfer *xfer) { at91dci_device_done(xfer, USB_ERR_CANCELLED); } static void at91dci_device_intr_enter(struct usb_xfer *xfer) { return; } static void at91dci_device_intr_start(struct usb_xfer *xfer) { /* setup TDs */ at91dci_setup_standard_chain(xfer); at91dci_start_standard_chain(xfer); } static const struct usb_pipe_methods at91dci_device_intr_methods = { .open = at91dci_device_intr_open, .close = at91dci_device_intr_close, .enter = at91dci_device_intr_enter, .start = at91dci_device_intr_start, }; /*------------------------------------------------------------------------* * at91dci full speed isochronous support *------------------------------------------------------------------------*/ static void at91dci_device_isoc_fs_open(struct usb_xfer *xfer) { return; } static void at91dci_device_isoc_fs_close(struct usb_xfer *xfer) { at91dci_device_done(xfer, USB_ERR_CANCELLED); } static void at91dci_device_isoc_fs_enter(struct usb_xfer *xfer) { struct at91dci_softc *sc = AT9100_DCI_BUS2SC(xfer->xroot->bus); uint32_t temp; uint32_t nframes; DPRINTFN(6, "xfer=%p next=%d nframes=%d\n", xfer, xfer->endpoint->isoc_next, xfer->nframes); /* get the current frame index */ nframes = AT91_UDP_READ_4(sc, AT91_UDP_FRM); /* * check if the frame index is within the window where the frames * will be inserted */ temp = (nframes - xfer->endpoint->isoc_next) & AT91_UDP_FRM_MASK; if ((xfer->endpoint->is_synced == 0) || (temp < xfer->nframes)) { /* * If there is data underflow or the endpoint queue is * empty we schedule the transfer a few frames ahead * of the current frame position. Else two isochronous * transfers might overlap. */ xfer->endpoint->isoc_next = (nframes + 3) & AT91_UDP_FRM_MASK; xfer->endpoint->is_synced = 1; DPRINTFN(3, "start next=%d\n", xfer->endpoint->isoc_next); } /* * compute how many milliseconds the insertion is ahead of the * current frame position: */ temp = (xfer->endpoint->isoc_next - nframes) & AT91_UDP_FRM_MASK; /* * pre-compute when the isochronous transfer will be finished: */ xfer->isoc_time_complete = usb_isoc_time_expand(&sc->sc_bus, nframes) + temp + xfer->nframes; /* compute frame number for next insertion */ xfer->endpoint->isoc_next += xfer->nframes; /* setup TDs */ at91dci_setup_standard_chain(xfer); } static void at91dci_device_isoc_fs_start(struct usb_xfer *xfer) { /* start TD chain */ at91dci_start_standard_chain(xfer); } static const struct usb_pipe_methods at91dci_device_isoc_fs_methods = { .open = at91dci_device_isoc_fs_open, .close = at91dci_device_isoc_fs_close, .enter = at91dci_device_isoc_fs_enter, .start = at91dci_device_isoc_fs_start, }; /*------------------------------------------------------------------------* * at91dci root control support *------------------------------------------------------------------------* * Simulate a hardware HUB by handling all the necessary requests. *------------------------------------------------------------------------*/ static const struct usb_device_descriptor at91dci_devd = { .bLength = sizeof(struct usb_device_descriptor), .bDescriptorType = UDESC_DEVICE, .bcdUSB = {0x00, 0x02}, .bDeviceClass = UDCLASS_HUB, .bDeviceSubClass = UDSUBCLASS_HUB, .bDeviceProtocol = UDPROTO_FSHUB, .bMaxPacketSize = 64, .bcdDevice = {0x00, 0x01}, .iManufacturer = 1, .iProduct = 2, .bNumConfigurations = 1, }; static const struct at91dci_config_desc at91dci_confd = { .confd = { .bLength = sizeof(struct usb_config_descriptor), .bDescriptorType = UDESC_CONFIG, .wTotalLength[0] = sizeof(at91dci_confd), .bNumInterface = 1, .bConfigurationValue = 1, .iConfiguration = 0, .bmAttributes = UC_SELF_POWERED, .bMaxPower = 0, }, .ifcd = { .bLength = sizeof(struct usb_interface_descriptor), .bDescriptorType = UDESC_INTERFACE, .bNumEndpoints = 1, .bInterfaceClass = UICLASS_HUB, .bInterfaceSubClass = UISUBCLASS_HUB, .bInterfaceProtocol = 0, }, .endpd = { .bLength = sizeof(struct usb_endpoint_descriptor), .bDescriptorType = UDESC_ENDPOINT, .bEndpointAddress = (UE_DIR_IN | AT9100_DCI_INTR_ENDPT), .bmAttributes = UE_INTERRUPT, .wMaxPacketSize[0] = 8, .bInterval = 255, }, }; #define HSETW(ptr, val) ptr = { (uint8_t)(val), (uint8_t)((val) >> 8) } static const struct usb_hub_descriptor_min at91dci_hubd = { .bDescLength = sizeof(at91dci_hubd), .bDescriptorType = UDESC_HUB, .bNbrPorts = 1, HSETW(.wHubCharacteristics, (UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL)), .bPwrOn2PwrGood = 50, .bHubContrCurrent = 0, .DeviceRemovable = {0}, /* port is removable */ }; #define STRING_VENDOR \ "A\0T\0M\0E\0L" #define STRING_PRODUCT \ "D\0C\0I\0 \0R\0o\0o\0t\0 \0H\0U\0B" USB_MAKE_STRING_DESC(STRING_VENDOR, at91dci_vendor); USB_MAKE_STRING_DESC(STRING_PRODUCT, at91dci_product); static usb_error_t at91dci_roothub_exec(struct usb_device *udev, struct usb_device_request *req, const void **pptr, uint16_t *plength) { struct at91dci_softc *sc = AT9100_DCI_BUS2SC(udev->bus); const void *ptr; uint16_t len; uint16_t value; uint16_t index; usb_error_t err; USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); /* buffer reset */ ptr = (const void *)&sc->sc_hub_temp; len = 0; err = 0; value = UGETW(req->wValue); index = UGETW(req->wIndex); /* demultiplex the control request */ switch (req->bmRequestType) { case UT_READ_DEVICE: switch (req->bRequest) { case UR_GET_DESCRIPTOR: goto tr_handle_get_descriptor; case UR_GET_CONFIG: goto tr_handle_get_config; case UR_GET_STATUS: goto tr_handle_get_status; default: goto tr_stalled; } break; case UT_WRITE_DEVICE: switch (req->bRequest) { case UR_SET_ADDRESS: goto tr_handle_set_address; case UR_SET_CONFIG: goto tr_handle_set_config; case UR_CLEAR_FEATURE: goto tr_valid; /* nop */ case UR_SET_DESCRIPTOR: goto tr_valid; /* nop */ case UR_SET_FEATURE: default: goto tr_stalled; } break; case UT_WRITE_ENDPOINT: switch (req->bRequest) { case UR_CLEAR_FEATURE: switch (UGETW(req->wValue)) { case UF_ENDPOINT_HALT: goto tr_handle_clear_halt; case UF_DEVICE_REMOTE_WAKEUP: goto tr_handle_clear_wakeup; default: goto tr_stalled; } break; case UR_SET_FEATURE: switch (UGETW(req->wValue)) { case UF_ENDPOINT_HALT: goto tr_handle_set_halt; case UF_DEVICE_REMOTE_WAKEUP: goto tr_handle_set_wakeup; default: goto tr_stalled; } break; case UR_SYNCH_FRAME: goto tr_valid; /* nop */ default: goto tr_stalled; } break; case UT_READ_ENDPOINT: switch (req->bRequest) { case UR_GET_STATUS: goto tr_handle_get_ep_status; default: goto tr_stalled; } break; case UT_WRITE_INTERFACE: switch (req->bRequest) { case UR_SET_INTERFACE: goto tr_handle_set_interface; case UR_CLEAR_FEATURE: goto tr_valid; /* nop */ case UR_SET_FEATURE: default: goto tr_stalled; } break; case UT_READ_INTERFACE: switch (req->bRequest) { case UR_GET_INTERFACE: goto tr_handle_get_interface; case UR_GET_STATUS: goto tr_handle_get_iface_status; default: goto tr_stalled; } break; case UT_WRITE_CLASS_INTERFACE: case UT_WRITE_VENDOR_INTERFACE: /* XXX forward */ break; case UT_READ_CLASS_INTERFACE: case UT_READ_VENDOR_INTERFACE: /* XXX forward */ break; case UT_WRITE_CLASS_DEVICE: switch (req->bRequest) { case UR_CLEAR_FEATURE: goto tr_valid; case UR_SET_DESCRIPTOR: case UR_SET_FEATURE: break; default: goto tr_stalled; } break; case UT_WRITE_CLASS_OTHER: switch (req->bRequest) { case UR_CLEAR_FEATURE: goto tr_handle_clear_port_feature; case UR_SET_FEATURE: goto tr_handle_set_port_feature; case UR_CLEAR_TT_BUFFER: case UR_RESET_TT: case UR_STOP_TT: goto tr_valid; default: goto tr_stalled; } break; case UT_READ_CLASS_OTHER: switch (req->bRequest) { case UR_GET_TT_STATE: goto tr_handle_get_tt_state; case UR_GET_STATUS: goto tr_handle_get_port_status; default: goto tr_stalled; } break; case UT_READ_CLASS_DEVICE: switch (req->bRequest) { case UR_GET_DESCRIPTOR: goto tr_handle_get_class_descriptor; case UR_GET_STATUS: goto tr_handle_get_class_status; default: goto tr_stalled; } break; default: goto tr_stalled; } goto tr_valid; tr_handle_get_descriptor: switch (value >> 8) { case UDESC_DEVICE: if (value & 0xff) { goto tr_stalled; } len = sizeof(at91dci_devd); ptr = (const void *)&at91dci_devd; goto tr_valid; case UDESC_CONFIG: if (value & 0xff) { goto tr_stalled; } len = sizeof(at91dci_confd); ptr = (const void *)&at91dci_confd; goto tr_valid; case UDESC_STRING: switch (value & 0xff) { case 0: /* Language table */ len = sizeof(usb_string_lang_en); ptr = (const void *)&usb_string_lang_en; goto tr_valid; case 1: /* Vendor */ len = sizeof(at91dci_vendor); ptr = (const void *)&at91dci_vendor; goto tr_valid; case 2: /* Product */ len = sizeof(at91dci_product); ptr = (const void *)&at91dci_product; goto tr_valid; default: break; } break; default: goto tr_stalled; } goto tr_stalled; tr_handle_get_config: len = 1; sc->sc_hub_temp.wValue[0] = sc->sc_conf; goto tr_valid; tr_handle_get_status: len = 2; USETW(sc->sc_hub_temp.wValue, UDS_SELF_POWERED); goto tr_valid; tr_handle_set_address: if (value & 0xFF00) { goto tr_stalled; } sc->sc_rt_addr = value; goto tr_valid; tr_handle_set_config: if (value >= 2) { goto tr_stalled; } sc->sc_conf = value; goto tr_valid; tr_handle_get_interface: len = 1; sc->sc_hub_temp.wValue[0] = 0; goto tr_valid; tr_handle_get_tt_state: tr_handle_get_class_status: tr_handle_get_iface_status: tr_handle_get_ep_status: len = 2; USETW(sc->sc_hub_temp.wValue, 0); goto tr_valid; tr_handle_set_halt: tr_handle_set_interface: tr_handle_set_wakeup: tr_handle_clear_wakeup: tr_handle_clear_halt: goto tr_valid; tr_handle_clear_port_feature: if (index != 1) { goto tr_stalled; } DPRINTFN(9, "UR_CLEAR_PORT_FEATURE on port %d\n", index); switch (value) { case UHF_PORT_SUSPEND: at91dci_wakeup_peer(sc); break; case UHF_PORT_ENABLE: sc->sc_flags.port_enabled = 0; break; case UHF_PORT_TEST: case UHF_PORT_INDICATOR: case UHF_C_PORT_ENABLE: case UHF_C_PORT_OVER_CURRENT: case UHF_C_PORT_RESET: /* nops */ break; case UHF_PORT_POWER: sc->sc_flags.port_powered = 0; at91dci_pull_down(sc); at91dci_clocks_off(sc); break; case UHF_C_PORT_CONNECTION: sc->sc_flags.change_connect = 0; break; case UHF_C_PORT_SUSPEND: sc->sc_flags.change_suspend = 0; break; default: err = USB_ERR_IOERROR; goto done; } goto tr_valid; tr_handle_set_port_feature: if (index != 1) { goto tr_stalled; } DPRINTFN(9, "UR_SET_PORT_FEATURE\n"); switch (value) { case UHF_PORT_ENABLE: sc->sc_flags.port_enabled = 1; break; case UHF_PORT_SUSPEND: case UHF_PORT_RESET: case UHF_PORT_TEST: case UHF_PORT_INDICATOR: /* nops */ break; case UHF_PORT_POWER: sc->sc_flags.port_powered = 1; break; default: err = USB_ERR_IOERROR; goto done; } goto tr_valid; tr_handle_get_port_status: DPRINTFN(9, "UR_GET_PORT_STATUS\n"); if (index != 1) { goto tr_stalled; } if (sc->sc_flags.status_vbus) { at91dci_clocks_on(sc); at91dci_pull_up(sc); } else { at91dci_pull_down(sc); at91dci_clocks_off(sc); } /* Select FULL-speed and Device Side Mode */ value = UPS_PORT_MODE_DEVICE; if (sc->sc_flags.port_powered) { value |= UPS_PORT_POWER; } if (sc->sc_flags.port_enabled) { value |= UPS_PORT_ENABLED; } if (sc->sc_flags.status_vbus && sc->sc_flags.status_bus_reset) { value |= UPS_CURRENT_CONNECT_STATUS; } if (sc->sc_flags.status_suspend) { value |= UPS_SUSPEND; } USETW(sc->sc_hub_temp.ps.wPortStatus, value); value = 0; if (sc->sc_flags.change_connect) { value |= UPS_C_CONNECT_STATUS; if (sc->sc_flags.status_vbus && sc->sc_flags.status_bus_reset) { /* reset endpoint flags */ memset(sc->sc_ep_flags, 0, sizeof(sc->sc_ep_flags)); } } if (sc->sc_flags.change_suspend) { value |= UPS_C_SUSPEND; } USETW(sc->sc_hub_temp.ps.wPortChange, value); len = sizeof(sc->sc_hub_temp.ps); goto tr_valid; tr_handle_get_class_descriptor: if (value & 0xFF) { goto tr_stalled; } ptr = (const void *)&at91dci_hubd; len = sizeof(at91dci_hubd); goto tr_valid; tr_stalled: err = USB_ERR_STALLED; tr_valid: done: *plength = len; *pptr = ptr; return (err); } static void at91dci_xfer_setup(struct usb_setup_params *parm) { const struct usb_hw_ep_profile *pf; struct at91dci_softc *sc; struct usb_xfer *xfer; void *last_obj; uint32_t ntd; uint32_t n; uint8_t ep_no; sc = AT9100_DCI_BUS2SC(parm->udev->bus); xfer = parm->curr_xfer; /* * NOTE: This driver does not use any of the parameters that * are computed from the following values. Just set some * reasonable dummies: */ parm->hc_max_packet_size = 0x500; parm->hc_max_packet_count = 1; parm->hc_max_frame_size = 0x500; usbd_transfer_setup_sub(parm); /* * compute maximum number of TDs */ if (parm->methods == &at91dci_device_ctrl_methods) { ntd = xfer->nframes + 1 /* STATUS */ + 1 /* SYNC 1 */ + 1 /* SYNC 2 */ ; } else if (parm->methods == &at91dci_device_bulk_methods) { ntd = xfer->nframes + 1 /* SYNC */ ; } else if (parm->methods == &at91dci_device_intr_methods) { ntd = xfer->nframes + 1 /* SYNC */ ; } else if (parm->methods == &at91dci_device_isoc_fs_methods) { ntd = xfer->nframes + 1 /* SYNC */ ; } else { ntd = 0; } /* * check if "usbd_transfer_setup_sub" set an error */ if (parm->err) { return; } /* * allocate transfer descriptors */ last_obj = NULL; /* * get profile stuff */ if (ntd) { ep_no = xfer->endpointno & UE_ADDR; at91dci_get_hw_ep_profile(parm->udev, &pf, ep_no); if (pf == NULL) { /* should not happen */ parm->err = USB_ERR_INVAL; return; } } else { ep_no = 0; pf = NULL; } /* align data */ parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1)); for (n = 0; n != ntd; n++) { struct at91dci_td *td; if (parm->buf) { td = USB_ADD_BYTES(parm->buf, parm->size[0]); /* init TD */ td->max_packet_size = xfer->max_packet_size; td->status_reg = AT91_UDP_CSR(ep_no); td->fifo_reg = AT91_UDP_FDR(ep_no); if (pf->support_multi_buffer) { td->support_multi_buffer = 1; } td->obj_next = last_obj; last_obj = td; } parm->size[0] += sizeof(*td); } xfer->td_start[0] = last_obj; } static void at91dci_xfer_unsetup(struct usb_xfer *xfer) { return; } static void at91dci_ep_init(struct usb_device *udev, struct usb_endpoint_descriptor *edesc, struct usb_endpoint *ep) { struct at91dci_softc *sc = AT9100_DCI_BUS2SC(udev->bus); DPRINTFN(2, "endpoint=%p, addr=%d, endpt=%d, mode=%d (%d)\n", ep, udev->address, edesc->bEndpointAddress, udev->flags.usb_mode, sc->sc_rt_addr); if (udev->device_index != sc->sc_rt_addr) { if (udev->speed != USB_SPEED_FULL) { /* not supported */ return; } switch (edesc->bmAttributes & UE_XFERTYPE) { case UE_CONTROL: ep->methods = &at91dci_device_ctrl_methods; break; case UE_INTERRUPT: ep->methods = &at91dci_device_intr_methods; break; case UE_ISOCHRONOUS: ep->methods = &at91dci_device_isoc_fs_methods; break; case UE_BULK: ep->methods = &at91dci_device_bulk_methods; break; default: /* do nothing */ break; } } } static void at91dci_set_hw_power_sleep(struct usb_bus *bus, uint32_t state) { struct at91dci_softc *sc = AT9100_DCI_BUS2SC(bus); switch (state) { case USB_HW_POWER_SUSPEND: at91dci_suspend(sc); break; case USB_HW_POWER_SHUTDOWN: at91dci_uninit(sc); break; case USB_HW_POWER_RESUME: at91dci_resume(sc); break; default: break; } } static const struct usb_bus_methods at91dci_bus_methods = { .endpoint_init = &at91dci_ep_init, .xfer_setup = &at91dci_xfer_setup, .xfer_unsetup = &at91dci_xfer_unsetup, .get_hw_ep_profile = &at91dci_get_hw_ep_profile, .set_stall = &at91dci_set_stall, .xfer_stall = &at91dci_xfer_stall, .clear_stall = &at91dci_clear_stall, .roothub_exec = &at91dci_roothub_exec, .xfer_poll = &at91dci_do_poll, .set_hw_power_sleep = &at91dci_set_hw_power_sleep, }; Index: head/sys/dev/usb/controller/atmegadci.c =================================================================== --- head/sys/dev/usb/controller/atmegadci.c (revision 276700) +++ head/sys/dev/usb/controller/atmegadci.c (revision 276701) @@ -1,2157 +1,2157 @@ /* $FreeBSD$ */ /*- * Copyright (c) 2009 Hans Petter Selasky. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * This file contains the driver for the ATMEGA series USB OTG Controller. This * driver currently only supports the DCI mode of the USB hardware. */ /* * NOTE: When the chip detects BUS-reset it will also reset the * endpoints, Function-address and more. */ #ifdef USB_GLOBAL_INCLUDE_FILE #include USB_GLOBAL_INCLUDE_FILE #else #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define USB_DEBUG_VAR atmegadci_debug #include #include #include #include #include #include #include #include #include #include #endif /* USB_GLOBAL_INCLUDE_FILE */ #include #define ATMEGA_BUS2SC(bus) \ ((struct atmegadci_softc *)(((uint8_t *)(bus)) - \ ((uint8_t *)&(((struct atmegadci_softc *)0)->sc_bus)))) #define ATMEGA_PC2SC(pc) \ ATMEGA_BUS2SC(USB_DMATAG_TO_XROOT((pc)->tag_parent)->bus) #ifdef USB_DEBUG static int atmegadci_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, atmegadci, CTLFLAG_RW, 0, "USB ATMEGA DCI"); -SYSCTL_INT(_hw_usb_atmegadci, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_atmegadci, OID_AUTO, debug, CTLFLAG_RWTUN, &atmegadci_debug, 0, "ATMEGA DCI debug level"); #endif #define ATMEGA_INTR_ENDPT 1 /* prototypes */ static const struct usb_bus_methods atmegadci_bus_methods; static const struct usb_pipe_methods atmegadci_device_non_isoc_methods; static const struct usb_pipe_methods atmegadci_device_isoc_fs_methods; static atmegadci_cmd_t atmegadci_setup_rx; static atmegadci_cmd_t atmegadci_data_rx; static atmegadci_cmd_t atmegadci_data_tx; static atmegadci_cmd_t atmegadci_data_tx_sync; static void atmegadci_device_done(struct usb_xfer *, usb_error_t); static void atmegadci_do_poll(struct usb_bus *); static void atmegadci_standard_done(struct usb_xfer *); static void atmegadci_root_intr(struct atmegadci_softc *sc); /* * Here is a list of what the chip supports: */ static const struct usb_hw_ep_profile atmegadci_ep_profile[2] = { [0] = { .max_in_frame_size = 64, .max_out_frame_size = 64, .is_simplex = 1, .support_control = 1, }, [1] = { .max_in_frame_size = 64, .max_out_frame_size = 64, .is_simplex = 1, .support_bulk = 1, .support_interrupt = 1, .support_isochronous = 1, .support_in = 1, .support_out = 1, }, }; static void atmegadci_get_hw_ep_profile(struct usb_device *udev, const struct usb_hw_ep_profile **ppf, uint8_t ep_addr) { if (ep_addr == 0) *ppf = atmegadci_ep_profile; else if (ep_addr < ATMEGA_EP_MAX) *ppf = atmegadci_ep_profile + 1; else *ppf = NULL; } static void atmegadci_clocks_on(struct atmegadci_softc *sc) { if (sc->sc_flags.clocks_off && sc->sc_flags.port_powered) { DPRINTFN(5, "\n"); /* turn on clocks */ (sc->sc_clocks_on) (&sc->sc_bus); ATMEGA_WRITE_1(sc, ATMEGA_USBCON, ATMEGA_USBCON_USBE | ATMEGA_USBCON_OTGPADE | ATMEGA_USBCON_VBUSTE); sc->sc_flags.clocks_off = 0; /* enable transceiver ? */ } } static void atmegadci_clocks_off(struct atmegadci_softc *sc) { if (!sc->sc_flags.clocks_off) { DPRINTFN(5, "\n"); /* disable Transceiver ? */ ATMEGA_WRITE_1(sc, ATMEGA_USBCON, ATMEGA_USBCON_USBE | ATMEGA_USBCON_OTGPADE | ATMEGA_USBCON_FRZCLK | ATMEGA_USBCON_VBUSTE); /* turn clocks off */ (sc->sc_clocks_off) (&sc->sc_bus); sc->sc_flags.clocks_off = 1; } } static void atmegadci_pull_up(struct atmegadci_softc *sc) { /* pullup D+, if possible */ if (!sc->sc_flags.d_pulled_up && sc->sc_flags.port_powered) { sc->sc_flags.d_pulled_up = 1; ATMEGA_WRITE_1(sc, ATMEGA_UDCON, 0); } } static void atmegadci_pull_down(struct atmegadci_softc *sc) { /* pulldown D+, if possible */ if (sc->sc_flags.d_pulled_up) { sc->sc_flags.d_pulled_up = 0; ATMEGA_WRITE_1(sc, ATMEGA_UDCON, ATMEGA_UDCON_DETACH); } } static void atmegadci_wakeup_peer(struct atmegadci_softc *sc) { uint8_t temp; if (!sc->sc_flags.status_suspend) { return; } temp = ATMEGA_READ_1(sc, ATMEGA_UDCON); ATMEGA_WRITE_1(sc, ATMEGA_UDCON, temp | ATMEGA_UDCON_RMWKUP); /* wait 8 milliseconds */ /* Wait for reset to complete. */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 125); /* hardware should have cleared RMWKUP bit */ } static void atmegadci_set_address(struct atmegadci_softc *sc, uint8_t addr) { DPRINTFN(5, "addr=%d\n", addr); addr |= ATMEGA_UDADDR_ADDEN; ATMEGA_WRITE_1(sc, ATMEGA_UDADDR, addr); } static uint8_t atmegadci_setup_rx(struct atmegadci_td *td) { struct atmegadci_softc *sc; struct usb_device_request req; uint16_t count; uint8_t temp; /* get pointer to softc */ sc = ATMEGA_PC2SC(td->pc); /* select endpoint number */ ATMEGA_WRITE_1(sc, ATMEGA_UENUM, td->ep_no); /* check endpoint status */ temp = ATMEGA_READ_1(sc, ATMEGA_UEINTX); DPRINTFN(5, "UEINTX=0x%02x\n", temp); if (!(temp & ATMEGA_UEINTX_RXSTPI)) { goto not_complete; } /* clear did stall */ td->did_stall = 0; /* get the packet byte count */ count = (ATMEGA_READ_1(sc, ATMEGA_UEBCHX) << 8) | (ATMEGA_READ_1(sc, ATMEGA_UEBCLX)); /* mask away undefined bits */ count &= 0x7FF; /* verify data length */ if (count != td->remainder) { DPRINTFN(0, "Invalid SETUP packet " "length, %d bytes\n", count); goto not_complete; } if (count != sizeof(req)) { DPRINTFN(0, "Unsupported SETUP packet " "length, %d bytes\n", count); goto not_complete; } /* receive data */ ATMEGA_READ_MULTI_1(sc, ATMEGA_UEDATX, (void *)&req, sizeof(req)); /* copy data into real buffer */ usbd_copy_in(td->pc, 0, &req, sizeof(req)); td->offset = sizeof(req); td->remainder = 0; /* sneak peek the set address */ if ((req.bmRequestType == UT_WRITE_DEVICE) && (req.bRequest == UR_SET_ADDRESS)) { sc->sc_dv_addr = req.wValue[0] & 0x7F; /* must write address before ZLP */ ATMEGA_WRITE_1(sc, ATMEGA_UDADDR, sc->sc_dv_addr); } else { sc->sc_dv_addr = 0xFF; } /* Clear SETUP packet interrupt and all other previous interrupts */ ATMEGA_WRITE_1(sc, ATMEGA_UEINTX, 0); return (0); /* complete */ not_complete: /* abort any ongoing transfer */ if (!td->did_stall) { DPRINTFN(5, "stalling\n"); ATMEGA_WRITE_1(sc, ATMEGA_UECONX, ATMEGA_UECONX_EPEN | ATMEGA_UECONX_STALLRQ); td->did_stall = 1; } if (temp & ATMEGA_UEINTX_RXSTPI) { /* clear SETUP packet interrupt */ ATMEGA_WRITE_1(sc, ATMEGA_UEINTX, ~ATMEGA_UEINTX_RXSTPI); } /* we only want to know if there is a SETUP packet */ ATMEGA_WRITE_1(sc, ATMEGA_UEIENX, ATMEGA_UEIENX_RXSTPE); return (1); /* not complete */ } static uint8_t atmegadci_data_rx(struct atmegadci_td *td) { struct atmegadci_softc *sc; struct usb_page_search buf_res; uint16_t count; uint8_t temp; uint8_t to; uint8_t got_short; to = 3; /* don't loop forever! */ got_short = 0; /* get pointer to softc */ sc = ATMEGA_PC2SC(td->pc); /* select endpoint number */ ATMEGA_WRITE_1(sc, ATMEGA_UENUM, td->ep_no); repeat: /* check if any of the FIFO banks have data */ /* check endpoint status */ temp = ATMEGA_READ_1(sc, ATMEGA_UEINTX); DPRINTFN(5, "temp=0x%02x rem=%u\n", temp, td->remainder); if (temp & ATMEGA_UEINTX_RXSTPI) { if (td->remainder == 0) { /* * We are actually complete and have * received the next SETUP */ DPRINTFN(5, "faking complete\n"); return (0); /* complete */ } /* * USB Host Aborted the transfer. */ td->error = 1; return (0); /* complete */ } /* check status */ if (!(temp & (ATMEGA_UEINTX_FIFOCON | ATMEGA_UEINTX_RXOUTI))) { /* no data */ goto not_complete; } /* get the packet byte count */ count = (ATMEGA_READ_1(sc, ATMEGA_UEBCHX) << 8) | (ATMEGA_READ_1(sc, ATMEGA_UEBCLX)); /* mask away undefined bits */ count &= 0x7FF; /* verify the packet byte count */ if (count != td->max_packet_size) { if (count < td->max_packet_size) { /* we have a short packet */ td->short_pkt = 1; got_short = 1; } else { /* invalid USB packet */ td->error = 1; return (0); /* we are complete */ } } /* verify the packet byte count */ if (count > td->remainder) { /* invalid USB packet */ td->error = 1; return (0); /* we are complete */ } while (count > 0) { usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* receive data */ ATMEGA_READ_MULTI_1(sc, ATMEGA_UEDATX, buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* clear OUT packet interrupt */ ATMEGA_WRITE_1(sc, ATMEGA_UEINTX, ATMEGA_UEINTX_RXOUTI ^ 0xFF); /* release FIFO bank */ ATMEGA_WRITE_1(sc, ATMEGA_UEINTX, ATMEGA_UEINTX_FIFOCON ^ 0xFF); /* check if we are complete */ if ((td->remainder == 0) || got_short) { if (td->short_pkt) { /* we are complete */ return (0); } /* else need to receive a zero length packet */ } if (--to) { goto repeat; } not_complete: /* we only want to know if there is a SETUP packet or OUT packet */ ATMEGA_WRITE_1(sc, ATMEGA_UEIENX, ATMEGA_UEIENX_RXSTPE | ATMEGA_UEIENX_RXOUTE); return (1); /* not complete */ } static uint8_t atmegadci_data_tx(struct atmegadci_td *td) { struct atmegadci_softc *sc; struct usb_page_search buf_res; uint16_t count; uint8_t to; uint8_t temp; to = 3; /* don't loop forever! */ /* get pointer to softc */ sc = ATMEGA_PC2SC(td->pc); /* select endpoint number */ ATMEGA_WRITE_1(sc, ATMEGA_UENUM, td->ep_no); repeat: /* check endpoint status */ temp = ATMEGA_READ_1(sc, ATMEGA_UEINTX); DPRINTFN(5, "temp=0x%02x rem=%u\n", temp, td->remainder); if (temp & ATMEGA_UEINTX_RXSTPI) { /* * The current transfer was aborted * by the USB Host */ td->error = 1; return (0); /* complete */ } temp = ATMEGA_READ_1(sc, ATMEGA_UESTA0X); if (temp & 3) { /* cannot write any data - a bank is busy */ goto not_complete; } count = td->max_packet_size; if (td->remainder < count) { /* we have a short packet */ td->short_pkt = 1; count = td->remainder; } while (count > 0) { usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* transmit data */ ATMEGA_WRITE_MULTI_1(sc, ATMEGA_UEDATX, buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* clear IN packet interrupt */ ATMEGA_WRITE_1(sc, ATMEGA_UEINTX, 0xFF ^ ATMEGA_UEINTX_TXINI); /* allocate FIFO bank */ ATMEGA_WRITE_1(sc, ATMEGA_UEINTX, 0xFF ^ ATMEGA_UEINTX_FIFOCON); /* check remainder */ if (td->remainder == 0) { if (td->short_pkt) { return (0); /* complete */ } /* else we need to transmit a short packet */ } if (--to) { goto repeat; } not_complete: /* we only want to know if there is a SETUP packet or free IN packet */ ATMEGA_WRITE_1(sc, ATMEGA_UEIENX, ATMEGA_UEIENX_RXSTPE | ATMEGA_UEIENX_TXINE); return (1); /* not complete */ } static uint8_t atmegadci_data_tx_sync(struct atmegadci_td *td) { struct atmegadci_softc *sc; uint8_t temp; /* get pointer to softc */ sc = ATMEGA_PC2SC(td->pc); /* select endpoint number */ ATMEGA_WRITE_1(sc, ATMEGA_UENUM, td->ep_no); /* check endpoint status */ temp = ATMEGA_READ_1(sc, ATMEGA_UEINTX); DPRINTFN(5, "temp=0x%02x\n", temp); if (temp & ATMEGA_UEINTX_RXSTPI) { DPRINTFN(5, "faking complete\n"); /* Race condition */ return (0); /* complete */ } /* * The control endpoint has only got one bank, so if that bank * is free the packet has been transferred! */ temp = ATMEGA_READ_1(sc, ATMEGA_UESTA0X); if (temp & 3) { /* cannot write any data - a bank is busy */ goto not_complete; } if (sc->sc_dv_addr != 0xFF) { /* set new address */ atmegadci_set_address(sc, sc->sc_dv_addr); } return (0); /* complete */ not_complete: /* we only want to know if there is a SETUP packet or free IN packet */ ATMEGA_WRITE_1(sc, ATMEGA_UEIENX, ATMEGA_UEIENX_RXSTPE | ATMEGA_UEIENX_TXINE); return (1); /* not complete */ } static uint8_t atmegadci_xfer_do_fifo(struct usb_xfer *xfer) { struct atmegadci_td *td; DPRINTFN(9, "\n"); td = xfer->td_transfer_cache; while (1) { if ((td->func) (td)) { /* operation in progress */ break; } if (((void *)td) == xfer->td_transfer_last) { goto done; } if (td->error) { goto done; } else if (td->remainder > 0) { /* * We had a short transfer. If there is no alternate * next, stop processing ! */ if (!td->alt_next) { goto done; } } /* * Fetch the next transfer descriptor and transfer * some flags to the next transfer descriptor */ td = td->obj_next; xfer->td_transfer_cache = td; } return (1); /* not complete */ done: /* compute all actual lengths */ atmegadci_standard_done(xfer); return (0); /* complete */ } static void atmegadci_interrupt_poll(struct atmegadci_softc *sc) { struct usb_xfer *xfer; repeat: TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) { if (!atmegadci_xfer_do_fifo(xfer)) { /* queue has been modified */ goto repeat; } } } static void atmegadci_vbus_interrupt(struct atmegadci_softc *sc, uint8_t is_on) { DPRINTFN(5, "vbus = %u\n", is_on); if (is_on) { if (!sc->sc_flags.status_vbus) { sc->sc_flags.status_vbus = 1; /* complete root HUB interrupt endpoint */ atmegadci_root_intr(sc); } } else { if (sc->sc_flags.status_vbus) { sc->sc_flags.status_vbus = 0; sc->sc_flags.status_bus_reset = 0; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; /* complete root HUB interrupt endpoint */ atmegadci_root_intr(sc); } } } void atmegadci_interrupt(struct atmegadci_softc *sc) { uint8_t status; USB_BUS_LOCK(&sc->sc_bus); /* read interrupt status */ status = ATMEGA_READ_1(sc, ATMEGA_UDINT); /* clear all set interrupts */ ATMEGA_WRITE_1(sc, ATMEGA_UDINT, (~status) & 0x7D); DPRINTFN(14, "UDINT=0x%02x\n", status); /* check for any bus state change interrupts */ if (status & ATMEGA_UDINT_EORSTI) { DPRINTFN(5, "end of reset\n"); /* set correct state */ sc->sc_flags.status_bus_reset = 1; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; /* disable resume interrupt */ ATMEGA_WRITE_1(sc, ATMEGA_UDIEN, ATMEGA_UDINT_SUSPE | ATMEGA_UDINT_EORSTE); /* complete root HUB interrupt endpoint */ atmegadci_root_intr(sc); } /* * If resume and suspend is set at the same time we interpret * that like RESUME. Resume is set when there is at least 3 * milliseconds of inactivity on the USB BUS. */ if (status & ATMEGA_UDINT_WAKEUPI) { DPRINTFN(5, "resume interrupt\n"); if (sc->sc_flags.status_suspend) { /* update status bits */ sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 1; /* disable resume interrupt */ ATMEGA_WRITE_1(sc, ATMEGA_UDIEN, ATMEGA_UDINT_SUSPE | ATMEGA_UDINT_EORSTE); /* complete root HUB interrupt endpoint */ atmegadci_root_intr(sc); } } else if (status & ATMEGA_UDINT_SUSPI) { DPRINTFN(5, "suspend interrupt\n"); if (!sc->sc_flags.status_suspend) { /* update status bits */ sc->sc_flags.status_suspend = 1; sc->sc_flags.change_suspend = 1; /* disable suspend interrupt */ ATMEGA_WRITE_1(sc, ATMEGA_UDIEN, ATMEGA_UDINT_WAKEUPE | ATMEGA_UDINT_EORSTE); /* complete root HUB interrupt endpoint */ atmegadci_root_intr(sc); } } /* check VBUS */ status = ATMEGA_READ_1(sc, ATMEGA_USBINT); /* clear all set interrupts */ ATMEGA_WRITE_1(sc, ATMEGA_USBINT, (~status) & 0x03); if (status & ATMEGA_USBINT_VBUSTI) { uint8_t temp; DPRINTFN(5, "USBINT=0x%02x\n", status); temp = ATMEGA_READ_1(sc, ATMEGA_USBSTA); atmegadci_vbus_interrupt(sc, temp & ATMEGA_USBSTA_VBUS); } /* check for any endpoint interrupts */ status = ATMEGA_READ_1(sc, ATMEGA_UEINT); /* the hardware will clear the UEINT bits automatically */ if (status) { DPRINTFN(5, "real endpoint interrupt UEINT=0x%02x\n", status); atmegadci_interrupt_poll(sc); } USB_BUS_UNLOCK(&sc->sc_bus); } static void atmegadci_setup_standard_chain_sub(struct atmegadci_std_temp *temp) { struct atmegadci_td *td; /* get current Transfer Descriptor */ td = temp->td_next; temp->td = td; /* prepare for next TD */ temp->td_next = td->obj_next; /* fill out the Transfer Descriptor */ td->func = temp->func; td->pc = temp->pc; td->offset = temp->offset; td->remainder = temp->len; td->error = 0; td->did_stall = temp->did_stall; td->short_pkt = temp->short_pkt; td->alt_next = temp->setup_alt_next; } static void atmegadci_setup_standard_chain(struct usb_xfer *xfer) { struct atmegadci_std_temp temp; struct atmegadci_softc *sc; struct atmegadci_td *td; uint32_t x; uint8_t ep_no; uint8_t need_sync; DPRINTFN(9, "addr=%d endpt=%d sumlen=%d speed=%d\n", xfer->address, UE_GET_ADDR(xfer->endpointno), xfer->sumlen, usbd_get_speed(xfer->xroot->udev)); temp.max_frame_size = xfer->max_frame_size; td = xfer->td_start[0]; xfer->td_transfer_first = td; xfer->td_transfer_cache = td; /* setup temp */ temp.pc = NULL; temp.td = NULL; temp.td_next = xfer->td_start[0]; temp.offset = 0; temp.setup_alt_next = xfer->flags_int.short_frames_ok || xfer->flags_int.isochronous_xfr; temp.did_stall = !xfer->flags_int.control_stall; sc = ATMEGA_BUS2SC(xfer->xroot->bus); ep_no = (xfer->endpointno & UE_ADDR); /* check if we should prepend a setup message */ if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_hdr) { temp.func = &atmegadci_setup_rx; temp.len = xfer->frlengths[0]; temp.pc = xfer->frbuffers + 0; temp.short_pkt = temp.len ? 1 : 0; /* check for last frame */ if (xfer->nframes == 1) { /* no STATUS stage yet, SETUP is last */ if (xfer->flags_int.control_act) temp.setup_alt_next = 0; } atmegadci_setup_standard_chain_sub(&temp); } x = 1; } else { x = 0; } if (x != xfer->nframes) { if (xfer->endpointno & UE_DIR_IN) { temp.func = &atmegadci_data_tx; need_sync = 1; } else { temp.func = &atmegadci_data_rx; need_sync = 0; } /* setup "pc" pointer */ temp.pc = xfer->frbuffers + x; } else { need_sync = 0; } while (x != xfer->nframes) { /* DATA0 / DATA1 message */ temp.len = xfer->frlengths[x]; x++; if (x == xfer->nframes) { if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_act) { temp.setup_alt_next = 0; } } else { temp.setup_alt_next = 0; } } if (temp.len == 0) { /* make sure that we send an USB packet */ temp.short_pkt = 0; } else { /* regular data transfer */ temp.short_pkt = (xfer->flags.force_short_xfer) ? 0 : 1; } atmegadci_setup_standard_chain_sub(&temp); if (xfer->flags_int.isochronous_xfr) { temp.offset += temp.len; } else { /* get next Page Cache pointer */ temp.pc = xfer->frbuffers + x; } } if (xfer->flags_int.control_xfr) { /* always setup a valid "pc" pointer for status and sync */ temp.pc = xfer->frbuffers + 0; temp.len = 0; temp.short_pkt = 0; temp.setup_alt_next = 0; /* check if we need to sync */ if (need_sync) { /* we need a SYNC point after TX */ temp.func = &atmegadci_data_tx_sync; atmegadci_setup_standard_chain_sub(&temp); } /* check if we should append a status stage */ if (!xfer->flags_int.control_act) { /* * Send a DATA1 message and invert the current * endpoint direction. */ if (xfer->endpointno & UE_DIR_IN) { temp.func = &atmegadci_data_rx; need_sync = 0; } else { temp.func = &atmegadci_data_tx; need_sync = 1; } atmegadci_setup_standard_chain_sub(&temp); if (need_sync) { /* we need a SYNC point after TX */ temp.func = &atmegadci_data_tx_sync; atmegadci_setup_standard_chain_sub(&temp); } } } /* must have at least one frame! */ td = temp.td; xfer->td_transfer_last = td; } static void atmegadci_timeout(void *arg) { struct usb_xfer *xfer = arg; DPRINTF("xfer=%p\n", xfer); USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED); /* transfer is transferred */ atmegadci_device_done(xfer, USB_ERR_TIMEOUT); } static void atmegadci_start_standard_chain(struct usb_xfer *xfer) { DPRINTFN(9, "\n"); /* poll one time - will turn on interrupts */ if (atmegadci_xfer_do_fifo(xfer)) { /* put transfer on interrupt queue */ usbd_transfer_enqueue(&xfer->xroot->bus->intr_q, xfer); /* start timeout, if any */ if (xfer->timeout != 0) { usbd_transfer_timeout_ms(xfer, &atmegadci_timeout, xfer->timeout); } } } static void atmegadci_root_intr(struct atmegadci_softc *sc) { DPRINTFN(9, "\n"); USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); /* set port bit */ sc->sc_hub_idata[0] = 0x02; /* we only have one port */ uhub_root_intr(&sc->sc_bus, sc->sc_hub_idata, sizeof(sc->sc_hub_idata)); } static usb_error_t atmegadci_standard_done_sub(struct usb_xfer *xfer) { struct atmegadci_td *td; uint32_t len; uint8_t error; DPRINTFN(9, "\n"); td = xfer->td_transfer_cache; do { len = td->remainder; if (xfer->aframes != xfer->nframes) { /* * Verify the length and subtract * the remainder from "frlengths[]": */ if (len > xfer->frlengths[xfer->aframes]) { td->error = 1; } else { xfer->frlengths[xfer->aframes] -= len; } } /* Check for transfer error */ if (td->error) { /* the transfer is finished */ error = 1; td = NULL; break; } /* Check for short transfer */ if (len > 0) { if (xfer->flags_int.short_frames_ok || xfer->flags_int.isochronous_xfr) { /* follow alt next */ if (td->alt_next) { td = td->obj_next; } else { td = NULL; } } else { /* the transfer is finished */ td = NULL; } error = 0; break; } td = td->obj_next; /* this USB frame is complete */ error = 0; break; } while (0); /* update transfer cache */ xfer->td_transfer_cache = td; return (error ? USB_ERR_STALLED : USB_ERR_NORMAL_COMPLETION); } static void atmegadci_standard_done(struct usb_xfer *xfer) { usb_error_t err = 0; DPRINTFN(13, "xfer=%p endpoint=%p transfer done\n", xfer, xfer->endpoint); /* reset scanner */ xfer->td_transfer_cache = xfer->td_transfer_first; if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_hdr) { err = atmegadci_standard_done_sub(xfer); } xfer->aframes = 1; if (xfer->td_transfer_cache == NULL) { goto done; } } while (xfer->aframes != xfer->nframes) { err = atmegadci_standard_done_sub(xfer); xfer->aframes++; if (xfer->td_transfer_cache == NULL) { goto done; } } if (xfer->flags_int.control_xfr && !xfer->flags_int.control_act) { err = atmegadci_standard_done_sub(xfer); } done: atmegadci_device_done(xfer, err); } /*------------------------------------------------------------------------* * atmegadci_device_done * * NOTE: this function can be called more than one time on the * same USB transfer! *------------------------------------------------------------------------*/ static void atmegadci_device_done(struct usb_xfer *xfer, usb_error_t error) { struct atmegadci_softc *sc = ATMEGA_BUS2SC(xfer->xroot->bus); uint8_t ep_no; USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); DPRINTFN(9, "xfer=%p, endpoint=%p, error=%d\n", xfer, xfer->endpoint, error); if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) { ep_no = (xfer->endpointno & UE_ADDR); /* select endpoint number */ ATMEGA_WRITE_1(sc, ATMEGA_UENUM, ep_no); /* disable endpoint interrupt */ ATMEGA_WRITE_1(sc, ATMEGA_UEIENX, 0); DPRINTFN(15, "disabled interrupts!\n"); } /* dequeue transfer and start next transfer */ usbd_transfer_done(xfer, error); } static void atmegadci_xfer_stall(struct usb_xfer *xfer) { atmegadci_device_done(xfer, USB_ERR_STALLED); } static void atmegadci_set_stall(struct usb_device *udev, struct usb_endpoint *ep, uint8_t *did_stall) { struct atmegadci_softc *sc; uint8_t ep_no; USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED); DPRINTFN(5, "endpoint=%p\n", ep); sc = ATMEGA_BUS2SC(udev->bus); /* get endpoint number */ ep_no = (ep->edesc->bEndpointAddress & UE_ADDR); /* select endpoint number */ ATMEGA_WRITE_1(sc, ATMEGA_UENUM, ep_no); /* set stall */ ATMEGA_WRITE_1(sc, ATMEGA_UECONX, ATMEGA_UECONX_EPEN | ATMEGA_UECONX_STALLRQ); } static void atmegadci_clear_stall_sub(struct atmegadci_softc *sc, uint8_t ep_no, uint8_t ep_type, uint8_t ep_dir) { uint8_t temp; if (ep_type == UE_CONTROL) { /* clearing stall is not needed */ return; } /* select endpoint number */ ATMEGA_WRITE_1(sc, ATMEGA_UENUM, ep_no); /* set endpoint reset */ ATMEGA_WRITE_1(sc, ATMEGA_UERST, ATMEGA_UERST_MASK(ep_no)); /* clear endpoint reset */ ATMEGA_WRITE_1(sc, ATMEGA_UERST, 0); /* set stall */ ATMEGA_WRITE_1(sc, ATMEGA_UECONX, ATMEGA_UECONX_EPEN | ATMEGA_UECONX_STALLRQ); /* reset data toggle */ ATMEGA_WRITE_1(sc, ATMEGA_UECONX, ATMEGA_UECONX_EPEN | ATMEGA_UECONX_RSTDT); /* clear stall */ ATMEGA_WRITE_1(sc, ATMEGA_UECONX, ATMEGA_UECONX_EPEN | ATMEGA_UECONX_STALLRQC); do { if (ep_type == UE_BULK) { temp = ATMEGA_UECFG0X_EPTYPE2; } else if (ep_type == UE_INTERRUPT) { temp = ATMEGA_UECFG0X_EPTYPE3; } else { temp = ATMEGA_UECFG0X_EPTYPE1; } if (ep_dir & UE_DIR_IN) { temp |= ATMEGA_UECFG0X_EPDIR; } /* two banks, 64-bytes wMaxPacket */ ATMEGA_WRITE_1(sc, ATMEGA_UECFG0X, temp); ATMEGA_WRITE_1(sc, ATMEGA_UECFG1X, ATMEGA_UECFG1X_ALLOC | ATMEGA_UECFG1X_EPBK0 | /* one bank */ ATMEGA_UECFG1X_EPSIZE(3)); temp = ATMEGA_READ_1(sc, ATMEGA_UESTA0X); if (!(temp & ATMEGA_UESTA0X_CFGOK)) { device_printf(sc->sc_bus.bdev, "Chip rejected configuration\n"); } } while (0); } static void atmegadci_clear_stall(struct usb_device *udev, struct usb_endpoint *ep) { struct atmegadci_softc *sc; struct usb_endpoint_descriptor *ed; DPRINTFN(5, "endpoint=%p\n", ep); USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED); /* check mode */ if (udev->flags.usb_mode != USB_MODE_DEVICE) { /* not supported */ return; } /* get softc */ sc = ATMEGA_BUS2SC(udev->bus); /* get endpoint descriptor */ ed = ep->edesc; /* reset endpoint */ atmegadci_clear_stall_sub(sc, (ed->bEndpointAddress & UE_ADDR), (ed->bmAttributes & UE_XFERTYPE), (ed->bEndpointAddress & (UE_DIR_IN | UE_DIR_OUT))); } usb_error_t atmegadci_init(struct atmegadci_softc *sc) { uint8_t n; DPRINTF("start\n"); /* set up the bus structure */ sc->sc_bus.usbrev = USB_REV_1_1; sc->sc_bus.methods = &atmegadci_bus_methods; USB_BUS_LOCK(&sc->sc_bus); /* make sure USB is enabled */ ATMEGA_WRITE_1(sc, ATMEGA_USBCON, ATMEGA_USBCON_USBE | ATMEGA_USBCON_FRZCLK); /* enable USB PAD regulator */ ATMEGA_WRITE_1(sc, ATMEGA_UHWCON, ATMEGA_UHWCON_UVREGE | ATMEGA_UHWCON_UIMOD); /* the following register sets up the USB PLL, assuming 16MHz X-tal */ ATMEGA_WRITE_1(sc, 0x49 /* PLLCSR */, 0x14 | 0x02); /* wait for PLL to lock */ for (n = 0; n != 20; n++) { if (ATMEGA_READ_1(sc, 0x49) & 0x01) break; /* wait a little bit for PLL to start */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 100); } /* make sure USB is enabled */ ATMEGA_WRITE_1(sc, ATMEGA_USBCON, ATMEGA_USBCON_USBE | ATMEGA_USBCON_OTGPADE | ATMEGA_USBCON_VBUSTE); /* turn on clocks */ (sc->sc_clocks_on) (&sc->sc_bus); /* make sure device is re-enumerated */ ATMEGA_WRITE_1(sc, ATMEGA_UDCON, ATMEGA_UDCON_DETACH); /* wait a little for things to stabilise */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 20); /* enable interrupts */ ATMEGA_WRITE_1(sc, ATMEGA_UDIEN, ATMEGA_UDINT_SUSPE | ATMEGA_UDINT_EORSTE); /* reset all endpoints */ ATMEGA_WRITE_1(sc, ATMEGA_UERST, (1 << ATMEGA_EP_MAX) - 1); /* disable reset */ ATMEGA_WRITE_1(sc, ATMEGA_UERST, 0); /* disable all endpoints */ for (n = 0; n != ATMEGA_EP_MAX; n++) { /* select endpoint */ ATMEGA_WRITE_1(sc, ATMEGA_UENUM, n); /* disable endpoint interrupt */ ATMEGA_WRITE_1(sc, ATMEGA_UEIENX, 0); /* disable endpoint */ ATMEGA_WRITE_1(sc, ATMEGA_UECONX, 0); } /* turn off clocks */ atmegadci_clocks_off(sc); /* read initial VBUS state */ n = ATMEGA_READ_1(sc, ATMEGA_USBSTA); atmegadci_vbus_interrupt(sc, n & ATMEGA_USBSTA_VBUS); USB_BUS_UNLOCK(&sc->sc_bus); /* catch any lost interrupts */ atmegadci_do_poll(&sc->sc_bus); return (0); /* success */ } void atmegadci_uninit(struct atmegadci_softc *sc) { USB_BUS_LOCK(&sc->sc_bus); /* turn on clocks */ (sc->sc_clocks_on) (&sc->sc_bus); /* disable interrupts */ ATMEGA_WRITE_1(sc, ATMEGA_UDIEN, 0); /* reset all endpoints */ ATMEGA_WRITE_1(sc, ATMEGA_UERST, (1 << ATMEGA_EP_MAX) - 1); /* disable reset */ ATMEGA_WRITE_1(sc, ATMEGA_UERST, 0); sc->sc_flags.port_powered = 0; sc->sc_flags.status_vbus = 0; sc->sc_flags.status_bus_reset = 0; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; atmegadci_pull_down(sc); atmegadci_clocks_off(sc); /* disable USB PAD regulator */ ATMEGA_WRITE_1(sc, ATMEGA_UHWCON, 0); USB_BUS_UNLOCK(&sc->sc_bus); } static void atmegadci_suspend(struct atmegadci_softc *sc) { /* TODO */ } static void atmegadci_resume(struct atmegadci_softc *sc) { /* TODO */ } static void atmegadci_do_poll(struct usb_bus *bus) { struct atmegadci_softc *sc = ATMEGA_BUS2SC(bus); USB_BUS_LOCK(&sc->sc_bus); atmegadci_interrupt_poll(sc); USB_BUS_UNLOCK(&sc->sc_bus); } /*------------------------------------------------------------------------* * atmegadci bulk support * atmegadci control support * atmegadci interrupt support *------------------------------------------------------------------------*/ static void atmegadci_device_non_isoc_open(struct usb_xfer *xfer) { return; } static void atmegadci_device_non_isoc_close(struct usb_xfer *xfer) { atmegadci_device_done(xfer, USB_ERR_CANCELLED); } static void atmegadci_device_non_isoc_enter(struct usb_xfer *xfer) { return; } static void atmegadci_device_non_isoc_start(struct usb_xfer *xfer) { /* setup TDs */ atmegadci_setup_standard_chain(xfer); atmegadci_start_standard_chain(xfer); } static const struct usb_pipe_methods atmegadci_device_non_isoc_methods = { .open = atmegadci_device_non_isoc_open, .close = atmegadci_device_non_isoc_close, .enter = atmegadci_device_non_isoc_enter, .start = atmegadci_device_non_isoc_start, }; /*------------------------------------------------------------------------* * atmegadci full speed isochronous support *------------------------------------------------------------------------*/ static void atmegadci_device_isoc_fs_open(struct usb_xfer *xfer) { return; } static void atmegadci_device_isoc_fs_close(struct usb_xfer *xfer) { atmegadci_device_done(xfer, USB_ERR_CANCELLED); } static void atmegadci_device_isoc_fs_enter(struct usb_xfer *xfer) { struct atmegadci_softc *sc = ATMEGA_BUS2SC(xfer->xroot->bus); uint32_t temp; uint32_t nframes; DPRINTFN(6, "xfer=%p next=%d nframes=%d\n", xfer, xfer->endpoint->isoc_next, xfer->nframes); /* get the current frame index */ nframes = (ATMEGA_READ_1(sc, ATMEGA_UDFNUMH) << 8) | (ATMEGA_READ_1(sc, ATMEGA_UDFNUML)); nframes &= ATMEGA_FRAME_MASK; /* * check if the frame index is within the window where the frames * will be inserted */ temp = (nframes - xfer->endpoint->isoc_next) & ATMEGA_FRAME_MASK; if ((xfer->endpoint->is_synced == 0) || (temp < xfer->nframes)) { /* * If there is data underflow or the pipe queue is * empty we schedule the transfer a few frames ahead * of the current frame position. Else two isochronous * transfers might overlap. */ xfer->endpoint->isoc_next = (nframes + 3) & ATMEGA_FRAME_MASK; xfer->endpoint->is_synced = 1; DPRINTFN(3, "start next=%d\n", xfer->endpoint->isoc_next); } /* * compute how many milliseconds the insertion is ahead of the * current frame position: */ temp = (xfer->endpoint->isoc_next - nframes) & ATMEGA_FRAME_MASK; /* * pre-compute when the isochronous transfer will be finished: */ xfer->isoc_time_complete = usb_isoc_time_expand(&sc->sc_bus, nframes) + temp + xfer->nframes; /* compute frame number for next insertion */ xfer->endpoint->isoc_next += xfer->nframes; /* setup TDs */ atmegadci_setup_standard_chain(xfer); } static void atmegadci_device_isoc_fs_start(struct usb_xfer *xfer) { /* start TD chain */ atmegadci_start_standard_chain(xfer); } static const struct usb_pipe_methods atmegadci_device_isoc_fs_methods = { .open = atmegadci_device_isoc_fs_open, .close = atmegadci_device_isoc_fs_close, .enter = atmegadci_device_isoc_fs_enter, .start = atmegadci_device_isoc_fs_start, }; /*------------------------------------------------------------------------* * atmegadci root control support *------------------------------------------------------------------------* * Simulate a hardware HUB by handling all the necessary requests. *------------------------------------------------------------------------*/ static const struct usb_device_descriptor atmegadci_devd = { .bLength = sizeof(struct usb_device_descriptor), .bDescriptorType = UDESC_DEVICE, .bcdUSB = {0x00, 0x02}, .bDeviceClass = UDCLASS_HUB, .bDeviceSubClass = UDSUBCLASS_HUB, .bDeviceProtocol = UDPROTO_FSHUB, .bMaxPacketSize = 64, .bcdDevice = {0x00, 0x01}, .iManufacturer = 1, .iProduct = 2, .bNumConfigurations = 1, }; static const struct atmegadci_config_desc atmegadci_confd = { .confd = { .bLength = sizeof(struct usb_config_descriptor), .bDescriptorType = UDESC_CONFIG, .wTotalLength[0] = sizeof(atmegadci_confd), .bNumInterface = 1, .bConfigurationValue = 1, .iConfiguration = 0, .bmAttributes = UC_SELF_POWERED, .bMaxPower = 0, }, .ifcd = { .bLength = sizeof(struct usb_interface_descriptor), .bDescriptorType = UDESC_INTERFACE, .bNumEndpoints = 1, .bInterfaceClass = UICLASS_HUB, .bInterfaceSubClass = UISUBCLASS_HUB, .bInterfaceProtocol = 0, }, .endpd = { .bLength = sizeof(struct usb_endpoint_descriptor), .bDescriptorType = UDESC_ENDPOINT, .bEndpointAddress = (UE_DIR_IN | ATMEGA_INTR_ENDPT), .bmAttributes = UE_INTERRUPT, .wMaxPacketSize[0] = 8, .bInterval = 255, }, }; #define HSETW(ptr, val) ptr = { (uint8_t)(val), (uint8_t)((val) >> 8) } static const struct usb_hub_descriptor_min atmegadci_hubd = { .bDescLength = sizeof(atmegadci_hubd), .bDescriptorType = UDESC_HUB, .bNbrPorts = 1, HSETW(.wHubCharacteristics, (UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL)), .bPwrOn2PwrGood = 50, .bHubContrCurrent = 0, .DeviceRemovable = {0}, /* port is removable */ }; #define STRING_VENDOR \ "A\0T\0M\0E\0G\0A" #define STRING_PRODUCT \ "D\0C\0I\0 \0R\0o\0o\0t\0 \0H\0U\0B" USB_MAKE_STRING_DESC(STRING_VENDOR, atmegadci_vendor); USB_MAKE_STRING_DESC(STRING_PRODUCT, atmegadci_product); static usb_error_t atmegadci_roothub_exec(struct usb_device *udev, struct usb_device_request *req, const void **pptr, uint16_t *plength) { struct atmegadci_softc *sc = ATMEGA_BUS2SC(udev->bus); const void *ptr; uint16_t len; uint16_t value; uint16_t index; uint8_t temp; usb_error_t err; USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); /* buffer reset */ ptr = (const void *)&sc->sc_hub_temp; len = 0; err = 0; value = UGETW(req->wValue); index = UGETW(req->wIndex); /* demultiplex the control request */ switch (req->bmRequestType) { case UT_READ_DEVICE: switch (req->bRequest) { case UR_GET_DESCRIPTOR: goto tr_handle_get_descriptor; case UR_GET_CONFIG: goto tr_handle_get_config; case UR_GET_STATUS: goto tr_handle_get_status; default: goto tr_stalled; } break; case UT_WRITE_DEVICE: switch (req->bRequest) { case UR_SET_ADDRESS: goto tr_handle_set_address; case UR_SET_CONFIG: goto tr_handle_set_config; case UR_CLEAR_FEATURE: goto tr_valid; /* nop */ case UR_SET_DESCRIPTOR: goto tr_valid; /* nop */ case UR_SET_FEATURE: default: goto tr_stalled; } break; case UT_WRITE_ENDPOINT: switch (req->bRequest) { case UR_CLEAR_FEATURE: switch (UGETW(req->wValue)) { case UF_ENDPOINT_HALT: goto tr_handle_clear_halt; case UF_DEVICE_REMOTE_WAKEUP: goto tr_handle_clear_wakeup; default: goto tr_stalled; } break; case UR_SET_FEATURE: switch (UGETW(req->wValue)) { case UF_ENDPOINT_HALT: goto tr_handle_set_halt; case UF_DEVICE_REMOTE_WAKEUP: goto tr_handle_set_wakeup; default: goto tr_stalled; } break; case UR_SYNCH_FRAME: goto tr_valid; /* nop */ default: goto tr_stalled; } break; case UT_READ_ENDPOINT: switch (req->bRequest) { case UR_GET_STATUS: goto tr_handle_get_ep_status; default: goto tr_stalled; } break; case UT_WRITE_INTERFACE: switch (req->bRequest) { case UR_SET_INTERFACE: goto tr_handle_set_interface; case UR_CLEAR_FEATURE: goto tr_valid; /* nop */ case UR_SET_FEATURE: default: goto tr_stalled; } break; case UT_READ_INTERFACE: switch (req->bRequest) { case UR_GET_INTERFACE: goto tr_handle_get_interface; case UR_GET_STATUS: goto tr_handle_get_iface_status; default: goto tr_stalled; } break; case UT_WRITE_CLASS_INTERFACE: case UT_WRITE_VENDOR_INTERFACE: /* XXX forward */ break; case UT_READ_CLASS_INTERFACE: case UT_READ_VENDOR_INTERFACE: /* XXX forward */ break; case UT_WRITE_CLASS_DEVICE: switch (req->bRequest) { case UR_CLEAR_FEATURE: goto tr_valid; case UR_SET_DESCRIPTOR: case UR_SET_FEATURE: break; default: goto tr_stalled; } break; case UT_WRITE_CLASS_OTHER: switch (req->bRequest) { case UR_CLEAR_FEATURE: goto tr_handle_clear_port_feature; case UR_SET_FEATURE: goto tr_handle_set_port_feature; case UR_CLEAR_TT_BUFFER: case UR_RESET_TT: case UR_STOP_TT: goto tr_valid; default: goto tr_stalled; } break; case UT_READ_CLASS_OTHER: switch (req->bRequest) { case UR_GET_TT_STATE: goto tr_handle_get_tt_state; case UR_GET_STATUS: goto tr_handle_get_port_status; default: goto tr_stalled; } break; case UT_READ_CLASS_DEVICE: switch (req->bRequest) { case UR_GET_DESCRIPTOR: goto tr_handle_get_class_descriptor; case UR_GET_STATUS: goto tr_handle_get_class_status; default: goto tr_stalled; } break; default: goto tr_stalled; } goto tr_valid; tr_handle_get_descriptor: switch (value >> 8) { case UDESC_DEVICE: if (value & 0xff) { goto tr_stalled; } len = sizeof(atmegadci_devd); ptr = (const void *)&atmegadci_devd; goto tr_valid; case UDESC_CONFIG: if (value & 0xff) { goto tr_stalled; } len = sizeof(atmegadci_confd); ptr = (const void *)&atmegadci_confd; goto tr_valid; case UDESC_STRING: switch (value & 0xff) { case 0: /* Language table */ len = sizeof(usb_string_lang_en); ptr = (const void *)&usb_string_lang_en; goto tr_valid; case 1: /* Vendor */ len = sizeof(atmegadci_vendor); ptr = (const void *)&atmegadci_vendor; goto tr_valid; case 2: /* Product */ len = sizeof(atmegadci_product); ptr = (const void *)&atmegadci_product; goto tr_valid; default: break; } break; default: goto tr_stalled; } goto tr_stalled; tr_handle_get_config: len = 1; sc->sc_hub_temp.wValue[0] = sc->sc_conf; goto tr_valid; tr_handle_get_status: len = 2; USETW(sc->sc_hub_temp.wValue, UDS_SELF_POWERED); goto tr_valid; tr_handle_set_address: if (value & 0xFF00) { goto tr_stalled; } sc->sc_rt_addr = value; goto tr_valid; tr_handle_set_config: if (value >= 2) { goto tr_stalled; } sc->sc_conf = value; goto tr_valid; tr_handle_get_interface: len = 1; sc->sc_hub_temp.wValue[0] = 0; goto tr_valid; tr_handle_get_tt_state: tr_handle_get_class_status: tr_handle_get_iface_status: tr_handle_get_ep_status: len = 2; USETW(sc->sc_hub_temp.wValue, 0); goto tr_valid; tr_handle_set_halt: tr_handle_set_interface: tr_handle_set_wakeup: tr_handle_clear_wakeup: tr_handle_clear_halt: goto tr_valid; tr_handle_clear_port_feature: if (index != 1) { goto tr_stalled; } DPRINTFN(9, "UR_CLEAR_PORT_FEATURE on port %d\n", index); switch (value) { case UHF_PORT_SUSPEND: atmegadci_wakeup_peer(sc); break; case UHF_PORT_ENABLE: sc->sc_flags.port_enabled = 0; break; case UHF_PORT_TEST: case UHF_PORT_INDICATOR: case UHF_C_PORT_ENABLE: case UHF_C_PORT_OVER_CURRENT: case UHF_C_PORT_RESET: /* nops */ break; case UHF_PORT_POWER: sc->sc_flags.port_powered = 0; atmegadci_pull_down(sc); atmegadci_clocks_off(sc); break; case UHF_C_PORT_CONNECTION: /* clear connect change flag */ sc->sc_flags.change_connect = 0; if (!sc->sc_flags.status_bus_reset) { /* we are not connected */ break; } /* configure the control endpoint */ /* select endpoint number */ ATMEGA_WRITE_1(sc, ATMEGA_UENUM, 0); /* set endpoint reset */ ATMEGA_WRITE_1(sc, ATMEGA_UERST, ATMEGA_UERST_MASK(0)); /* clear endpoint reset */ ATMEGA_WRITE_1(sc, ATMEGA_UERST, 0); /* enable and stall endpoint */ ATMEGA_WRITE_1(sc, ATMEGA_UECONX, ATMEGA_UECONX_EPEN | ATMEGA_UECONX_STALLRQ); /* one bank, 64-bytes wMaxPacket */ ATMEGA_WRITE_1(sc, ATMEGA_UECFG0X, ATMEGA_UECFG0X_EPTYPE0); ATMEGA_WRITE_1(sc, ATMEGA_UECFG1X, ATMEGA_UECFG1X_ALLOC | ATMEGA_UECFG1X_EPBK0 | ATMEGA_UECFG1X_EPSIZE(3)); /* check valid config */ temp = ATMEGA_READ_1(sc, ATMEGA_UESTA0X); if (!(temp & ATMEGA_UESTA0X_CFGOK)) { device_printf(sc->sc_bus.bdev, "Chip rejected EP0 configuration\n"); } break; case UHF_C_PORT_SUSPEND: sc->sc_flags.change_suspend = 0; break; default: err = USB_ERR_IOERROR; goto done; } goto tr_valid; tr_handle_set_port_feature: if (index != 1) { goto tr_stalled; } DPRINTFN(9, "UR_SET_PORT_FEATURE\n"); switch (value) { case UHF_PORT_ENABLE: sc->sc_flags.port_enabled = 1; break; case UHF_PORT_SUSPEND: case UHF_PORT_RESET: case UHF_PORT_TEST: case UHF_PORT_INDICATOR: /* nops */ break; case UHF_PORT_POWER: sc->sc_flags.port_powered = 1; break; default: err = USB_ERR_IOERROR; goto done; } goto tr_valid; tr_handle_get_port_status: DPRINTFN(9, "UR_GET_PORT_STATUS\n"); if (index != 1) { goto tr_stalled; } if (sc->sc_flags.status_vbus) { atmegadci_clocks_on(sc); atmegadci_pull_up(sc); } else { atmegadci_pull_down(sc); atmegadci_clocks_off(sc); } /* Select FULL-speed and Device Side Mode */ value = UPS_PORT_MODE_DEVICE; if (sc->sc_flags.port_powered) { value |= UPS_PORT_POWER; } if (sc->sc_flags.port_enabled) { value |= UPS_PORT_ENABLED; } if (sc->sc_flags.status_vbus && sc->sc_flags.status_bus_reset) { value |= UPS_CURRENT_CONNECT_STATUS; } if (sc->sc_flags.status_suspend) { value |= UPS_SUSPEND; } USETW(sc->sc_hub_temp.ps.wPortStatus, value); value = 0; if (sc->sc_flags.change_connect) { value |= UPS_C_CONNECT_STATUS; } if (sc->sc_flags.change_suspend) { value |= UPS_C_SUSPEND; } USETW(sc->sc_hub_temp.ps.wPortChange, value); len = sizeof(sc->sc_hub_temp.ps); goto tr_valid; tr_handle_get_class_descriptor: if (value & 0xFF) { goto tr_stalled; } ptr = (const void *)&atmegadci_hubd; len = sizeof(atmegadci_hubd); goto tr_valid; tr_stalled: err = USB_ERR_STALLED; tr_valid: done: *plength = len; *pptr = ptr; return (err); } static void atmegadci_xfer_setup(struct usb_setup_params *parm) { const struct usb_hw_ep_profile *pf; struct atmegadci_softc *sc; struct usb_xfer *xfer; void *last_obj; uint32_t ntd; uint32_t n; uint8_t ep_no; sc = ATMEGA_BUS2SC(parm->udev->bus); xfer = parm->curr_xfer; /* * NOTE: This driver does not use any of the parameters that * are computed from the following values. Just set some * reasonable dummies: */ parm->hc_max_packet_size = 0x500; parm->hc_max_packet_count = 1; parm->hc_max_frame_size = 0x500; usbd_transfer_setup_sub(parm); /* * compute maximum number of TDs */ if ((xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) == UE_CONTROL) { ntd = xfer->nframes + 1 /* STATUS */ + 1 /* SYNC 1 */ + 1 /* SYNC 2 */ ; } else { ntd = xfer->nframes + 1 /* SYNC */ ; } /* * check if "usbd_transfer_setup_sub" set an error */ if (parm->err) return; /* * allocate transfer descriptors */ last_obj = NULL; /* * get profile stuff */ ep_no = xfer->endpointno & UE_ADDR; atmegadci_get_hw_ep_profile(parm->udev, &pf, ep_no); if (pf == NULL) { /* should not happen */ parm->err = USB_ERR_INVAL; return; } /* align data */ parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1)); for (n = 0; n != ntd; n++) { struct atmegadci_td *td; if (parm->buf) { td = USB_ADD_BYTES(parm->buf, parm->size[0]); /* init TD */ td->max_packet_size = xfer->max_packet_size; td->ep_no = ep_no; if (pf->support_multi_buffer) { td->support_multi_buffer = 1; } td->obj_next = last_obj; last_obj = td; } parm->size[0] += sizeof(*td); } xfer->td_start[0] = last_obj; } static void atmegadci_xfer_unsetup(struct usb_xfer *xfer) { return; } static void atmegadci_ep_init(struct usb_device *udev, struct usb_endpoint_descriptor *edesc, struct usb_endpoint *ep) { struct atmegadci_softc *sc = ATMEGA_BUS2SC(udev->bus); DPRINTFN(2, "endpoint=%p, addr=%d, endpt=%d, mode=%d (%d,%d)\n", ep, udev->address, edesc->bEndpointAddress, udev->flags.usb_mode, sc->sc_rt_addr, udev->device_index); if (udev->device_index != sc->sc_rt_addr) { if (udev->speed != USB_SPEED_FULL) { /* not supported */ return; } if ((edesc->bmAttributes & UE_XFERTYPE) == UE_ISOCHRONOUS) ep->methods = &atmegadci_device_isoc_fs_methods; else ep->methods = &atmegadci_device_non_isoc_methods; } } static void atmegadci_set_hw_power_sleep(struct usb_bus *bus, uint32_t state) { struct atmegadci_softc *sc = ATMEGA_BUS2SC(bus); switch (state) { case USB_HW_POWER_SUSPEND: atmegadci_suspend(sc); break; case USB_HW_POWER_SHUTDOWN: atmegadci_uninit(sc); break; case USB_HW_POWER_RESUME: atmegadci_resume(sc); break; default: break; } } static const struct usb_bus_methods atmegadci_bus_methods = { .endpoint_init = &atmegadci_ep_init, .xfer_setup = &atmegadci_xfer_setup, .xfer_unsetup = &atmegadci_xfer_unsetup, .get_hw_ep_profile = &atmegadci_get_hw_ep_profile, .xfer_stall = &atmegadci_xfer_stall, .set_stall = &atmegadci_set_stall, .clear_stall = &atmegadci_clear_stall, .roothub_exec = &atmegadci_roothub_exec, .xfer_poll = &atmegadci_do_poll, .set_hw_power_sleep = &atmegadci_set_hw_power_sleep, }; Index: head/sys/dev/usb/controller/avr32dci.c =================================================================== --- head/sys/dev/usb/controller/avr32dci.c (revision 276700) +++ head/sys/dev/usb/controller/avr32dci.c (revision 276701) @@ -1,2101 +1,2101 @@ /* $FreeBSD$ */ /*- * Copyright (c) 2009 Hans Petter Selasky. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * This file contains the driver for the AVR32 series USB Device * Controller */ /* * NOTE: When the chip detects BUS-reset it will also reset the * endpoints, Function-address and more. */ #ifdef USB_GLOBAL_INCLUDE_FILE #include USB_GLOBAL_INCLUDE_FILE #else #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define USB_DEBUG_VAR avr32dci_debug #include #include #include #include #include #include #include #include #include #include #endif /* USB_GLOBAL_INCLUDE_FILE */ #include #define AVR32_BUS2SC(bus) \ ((struct avr32dci_softc *)(((uint8_t *)(bus)) - \ ((uint8_t *)&(((struct avr32dci_softc *)0)->sc_bus)))) #define AVR32_PC2SC(pc) \ AVR32_BUS2SC(USB_DMATAG_TO_XROOT((pc)->tag_parent)->bus) #ifdef USB_DEBUG static int avr32dci_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, avr32dci, CTLFLAG_RW, 0, "USB AVR32 DCI"); -SYSCTL_INT(_hw_usb_avr32dci, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_avr32dci, OID_AUTO, debug, CTLFLAG_RWTUN, &avr32dci_debug, 0, "AVR32 DCI debug level"); #endif #define AVR32_INTR_ENDPT 1 /* prototypes */ static const struct usb_bus_methods avr32dci_bus_methods; static const struct usb_pipe_methods avr32dci_device_non_isoc_methods; static const struct usb_pipe_methods avr32dci_device_isoc_fs_methods; static avr32dci_cmd_t avr32dci_setup_rx; static avr32dci_cmd_t avr32dci_data_rx; static avr32dci_cmd_t avr32dci_data_tx; static avr32dci_cmd_t avr32dci_data_tx_sync; static void avr32dci_device_done(struct usb_xfer *, usb_error_t); static void avr32dci_do_poll(struct usb_bus *); static void avr32dci_standard_done(struct usb_xfer *); static void avr32dci_root_intr(struct avr32dci_softc *sc); /* * Here is a list of what the chip supports: */ static const struct usb_hw_ep_profile avr32dci_ep_profile[4] = { [0] = { .max_in_frame_size = 64, .max_out_frame_size = 64, .is_simplex = 1, .support_control = 1, }, [1] = { .max_in_frame_size = 512, .max_out_frame_size = 512, .is_simplex = 1, .support_bulk = 1, .support_interrupt = 1, .support_isochronous = 1, .support_in = 1, .support_out = 1, }, [2] = { .max_in_frame_size = 64, .max_out_frame_size = 64, .is_simplex = 1, .support_bulk = 1, .support_interrupt = 1, .support_in = 1, .support_out = 1, }, [3] = { .max_in_frame_size = 1024, .max_out_frame_size = 1024, .is_simplex = 1, .support_bulk = 1, .support_interrupt = 1, .support_isochronous = 1, .support_in = 1, .support_out = 1, }, }; static void avr32dci_get_hw_ep_profile(struct usb_device *udev, const struct usb_hw_ep_profile **ppf, uint8_t ep_addr) { if (ep_addr == 0) *ppf = avr32dci_ep_profile; else if (ep_addr < 3) *ppf = avr32dci_ep_profile + 1; else if (ep_addr < 5) *ppf = avr32dci_ep_profile + 2; else if (ep_addr < 7) *ppf = avr32dci_ep_profile + 3; else *ppf = NULL; } static void avr32dci_mod_ctrl(struct avr32dci_softc *sc, uint32_t set, uint32_t clear) { uint32_t temp; temp = AVR32_READ_4(sc, AVR32_CTRL); temp |= set; temp &= ~clear; AVR32_WRITE_4(sc, AVR32_CTRL, temp); } static void avr32dci_mod_ien(struct avr32dci_softc *sc, uint32_t set, uint32_t clear) { uint32_t temp; temp = AVR32_READ_4(sc, AVR32_IEN); temp |= set; temp &= ~clear; AVR32_WRITE_4(sc, AVR32_IEN, temp); } static void avr32dci_clocks_on(struct avr32dci_softc *sc) { if (sc->sc_flags.clocks_off && sc->sc_flags.port_powered) { DPRINTFN(5, "\n"); /* turn on clocks */ (sc->sc_clocks_on) (&sc->sc_bus); avr32dci_mod_ctrl(sc, AVR32_CTRL_DEV_EN_USBA, 0); sc->sc_flags.clocks_off = 0; } } static void avr32dci_clocks_off(struct avr32dci_softc *sc) { if (!sc->sc_flags.clocks_off) { DPRINTFN(5, "\n"); avr32dci_mod_ctrl(sc, 0, AVR32_CTRL_DEV_EN_USBA); /* turn clocks off */ (sc->sc_clocks_off) (&sc->sc_bus); sc->sc_flags.clocks_off = 1; } } static void avr32dci_pull_up(struct avr32dci_softc *sc) { /* pullup D+, if possible */ if (!sc->sc_flags.d_pulled_up && sc->sc_flags.port_powered) { sc->sc_flags.d_pulled_up = 1; avr32dci_mod_ctrl(sc, 0, AVR32_CTRL_DEV_DETACH); } } static void avr32dci_pull_down(struct avr32dci_softc *sc) { /* pulldown D+, if possible */ if (sc->sc_flags.d_pulled_up) { sc->sc_flags.d_pulled_up = 0; avr32dci_mod_ctrl(sc, AVR32_CTRL_DEV_DETACH, 0); } } static void avr32dci_wakeup_peer(struct avr32dci_softc *sc) { if (!sc->sc_flags.status_suspend) { return; } avr32dci_mod_ctrl(sc, AVR32_CTRL_DEV_REWAKEUP, 0); /* wait 8 milliseconds */ /* Wait for reset to complete. */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 125); /* hardware should have cleared RMWKUP bit */ } static void avr32dci_set_address(struct avr32dci_softc *sc, uint8_t addr) { DPRINTFN(5, "addr=%d\n", addr); avr32dci_mod_ctrl(sc, AVR32_CTRL_DEV_FADDR_EN | addr, 0); } static uint8_t avr32dci_setup_rx(struct avr32dci_td *td) { struct avr32dci_softc *sc; struct usb_device_request req; uint16_t count; uint32_t temp; /* get pointer to softc */ sc = AVR32_PC2SC(td->pc); /* check endpoint status */ temp = AVR32_READ_4(sc, AVR32_EPTSTA(td->ep_no)); DPRINTFN(5, "EPTSTA(%u)=0x%08x\n", td->ep_no, temp); if (!(temp & AVR32_EPTSTA_RX_SETUP)) { goto not_complete; } /* clear did stall */ td->did_stall = 0; /* get the packet byte count */ count = AVR32_EPTSTA_BYTE_COUNT(temp); /* verify data length */ if (count != td->remainder) { DPRINTFN(0, "Invalid SETUP packet " "length, %d bytes\n", count); goto not_complete; } if (count != sizeof(req)) { DPRINTFN(0, "Unsupported SETUP packet " "length, %d bytes\n", count); goto not_complete; } /* receive data */ memcpy(&req, sc->physdata, sizeof(req)); /* copy data into real buffer */ usbd_copy_in(td->pc, 0, &req, sizeof(req)); td->offset = sizeof(req); td->remainder = 0; /* sneak peek the set address */ if ((req.bmRequestType == UT_WRITE_DEVICE) && (req.bRequest == UR_SET_ADDRESS)) { sc->sc_dv_addr = req.wValue[0] & 0x7F; /* must write address before ZLP */ avr32dci_mod_ctrl(sc, 0, AVR32_CTRL_DEV_FADDR_EN | AVR32_CTRL_DEV_ADDR); avr32dci_mod_ctrl(sc, sc->sc_dv_addr, 0); } else { sc->sc_dv_addr = 0xFF; } /* clear SETUP packet interrupt */ AVR32_WRITE_4(sc, AVR32_EPTCLRSTA(td->ep_no), AVR32_EPTSTA_RX_SETUP); return (0); /* complete */ not_complete: if (temp & AVR32_EPTSTA_RX_SETUP) { /* clear SETUP packet interrupt */ AVR32_WRITE_4(sc, AVR32_EPTCLRSTA(td->ep_no), AVR32_EPTSTA_RX_SETUP); } /* abort any ongoing transfer */ if (!td->did_stall) { DPRINTFN(5, "stalling\n"); AVR32_WRITE_4(sc, AVR32_EPTSETSTA(td->ep_no), AVR32_EPTSTA_FRCESTALL); td->did_stall = 1; } return (1); /* not complete */ } static uint8_t avr32dci_data_rx(struct avr32dci_td *td) { struct avr32dci_softc *sc; struct usb_page_search buf_res; uint16_t count; uint32_t temp; uint8_t to; uint8_t got_short; to = 4; /* don't loop forever! */ got_short = 0; /* get pointer to softc */ sc = AVR32_PC2SC(td->pc); repeat: /* check if any of the FIFO banks have data */ /* check endpoint status */ temp = AVR32_READ_4(sc, AVR32_EPTSTA(td->ep_no)); DPRINTFN(5, "EPTSTA(%u)=0x%08x\n", td->ep_no, temp); if (temp & AVR32_EPTSTA_RX_SETUP) { if (td->remainder == 0) { /* * We are actually complete and have * received the next SETUP */ DPRINTFN(5, "faking complete\n"); return (0); /* complete */ } /* * USB Host Aborted the transfer. */ td->error = 1; return (0); /* complete */ } /* check status */ if (!(temp & AVR32_EPTSTA_RX_BK_RDY)) { /* no data */ goto not_complete; } /* get the packet byte count */ count = AVR32_EPTSTA_BYTE_COUNT(temp); /* verify the packet byte count */ if (count != td->max_packet_size) { if (count < td->max_packet_size) { /* we have a short packet */ td->short_pkt = 1; got_short = 1; } else { /* invalid USB packet */ td->error = 1; return (0); /* we are complete */ } } /* verify the packet byte count */ if (count > td->remainder) { /* invalid USB packet */ td->error = 1; return (0); /* we are complete */ } while (count > 0) { usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* receive data */ memcpy(buf_res.buffer, sc->physdata + (AVR32_EPTSTA_CURRENT_BANK(temp) << td->bank_shift) + (td->ep_no << 16) + (td->offset % td->max_packet_size), buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* clear OUT packet interrupt */ AVR32_WRITE_4(sc, AVR32_EPTCLRSTA(td->ep_no), AVR32_EPTSTA_RX_BK_RDY); /* check if we are complete */ if ((td->remainder == 0) || got_short) { if (td->short_pkt) { /* we are complete */ return (0); } /* else need to receive a zero length packet */ } if (--to) { goto repeat; } not_complete: return (1); /* not complete */ } static uint8_t avr32dci_data_tx(struct avr32dci_td *td) { struct avr32dci_softc *sc; struct usb_page_search buf_res; uint16_t count; uint8_t to; uint32_t temp; to = 4; /* don't loop forever! */ /* get pointer to softc */ sc = AVR32_PC2SC(td->pc); repeat: /* check endpoint status */ temp = AVR32_READ_4(sc, AVR32_EPTSTA(td->ep_no)); DPRINTFN(5, "EPTSTA(%u)=0x%08x\n", td->ep_no, temp); if (temp & AVR32_EPTSTA_RX_SETUP) { /* * The current transfer was aborted * by the USB Host */ td->error = 1; return (0); /* complete */ } if (temp & AVR32_EPTSTA_TX_PK_RDY) { /* cannot write any data - all banks are busy */ goto not_complete; } count = td->max_packet_size; if (td->remainder < count) { /* we have a short packet */ td->short_pkt = 1; count = td->remainder; } while (count > 0) { usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* transmit data */ memcpy(sc->physdata + (AVR32_EPTSTA_CURRENT_BANK(temp) << td->bank_shift) + (td->ep_no << 16) + (td->offset % td->max_packet_size), buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* allocate FIFO bank */ AVR32_WRITE_4(sc, AVR32_EPTCTL(td->ep_no), AVR32_EPTCTL_TX_PK_RDY); /* check remainder */ if (td->remainder == 0) { if (td->short_pkt) { return (0); /* complete */ } /* else we need to transmit a short packet */ } if (--to) { goto repeat; } not_complete: return (1); /* not complete */ } static uint8_t avr32dci_data_tx_sync(struct avr32dci_td *td) { struct avr32dci_softc *sc; uint32_t temp; /* get pointer to softc */ sc = AVR32_PC2SC(td->pc); /* check endpoint status */ temp = AVR32_READ_4(sc, AVR32_EPTSTA(td->ep_no)); DPRINTFN(5, "EPTSTA(%u)=0x%08x\n", td->ep_no, temp); if (temp & AVR32_EPTSTA_RX_SETUP) { DPRINTFN(5, "faking complete\n"); /* Race condition */ return (0); /* complete */ } /* * The control endpoint has only got one bank, so if that bank * is free the packet has been transferred! */ if (AVR32_EPTSTA_BUSY_BANK_STA(temp) != 0) { /* cannot write any data - a bank is busy */ goto not_complete; } if (sc->sc_dv_addr != 0xFF) { /* set new address */ avr32dci_set_address(sc, sc->sc_dv_addr); } return (0); /* complete */ not_complete: return (1); /* not complete */ } static uint8_t avr32dci_xfer_do_fifo(struct usb_xfer *xfer) { struct avr32dci_td *td; DPRINTFN(9, "\n"); td = xfer->td_transfer_cache; while (1) { if ((td->func) (td)) { /* operation in progress */ break; } if (((void *)td) == xfer->td_transfer_last) { goto done; } if (td->error) { goto done; } else if (td->remainder > 0) { /* * We had a short transfer. If there is no alternate * next, stop processing ! */ if (!td->alt_next) { goto done; } } /* * Fetch the next transfer descriptor and transfer * some flags to the next transfer descriptor */ td = td->obj_next; xfer->td_transfer_cache = td; } return (1); /* not complete */ done: /* compute all actual lengths */ avr32dci_standard_done(xfer); return (0); /* complete */ } static void avr32dci_interrupt_poll(struct avr32dci_softc *sc) { struct usb_xfer *xfer; repeat: TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) { if (!avr32dci_xfer_do_fifo(xfer)) { /* queue has been modified */ goto repeat; } } } void avr32dci_vbus_interrupt(struct avr32dci_softc *sc, uint8_t is_on) { DPRINTFN(5, "vbus = %u\n", is_on); if (is_on) { if (!sc->sc_flags.status_vbus) { sc->sc_flags.status_vbus = 1; /* complete root HUB interrupt endpoint */ avr32dci_root_intr(sc); } } else { if (sc->sc_flags.status_vbus) { sc->sc_flags.status_vbus = 0; sc->sc_flags.status_bus_reset = 0; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; /* complete root HUB interrupt endpoint */ avr32dci_root_intr(sc); } } } void avr32dci_interrupt(struct avr32dci_softc *sc) { uint32_t status; USB_BUS_LOCK(&sc->sc_bus); /* read interrupt status */ status = AVR32_READ_4(sc, AVR32_INTSTA); /* clear all set interrupts */ AVR32_WRITE_4(sc, AVR32_CLRINT, status); DPRINTFN(14, "INTSTA=0x%08x\n", status); /* check for any bus state change interrupts */ if (status & AVR32_INT_ENDRESET) { DPRINTFN(5, "end of reset\n"); /* set correct state */ sc->sc_flags.status_bus_reset = 1; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; /* disable resume interrupt */ avr32dci_mod_ien(sc, AVR32_INT_DET_SUSPD | AVR32_INT_ENDRESET, AVR32_INT_WAKE_UP); /* complete root HUB interrupt endpoint */ avr32dci_root_intr(sc); } /* * If resume and suspend is set at the same time we interpret * that like RESUME. Resume is set when there is at least 3 * milliseconds of inactivity on the USB BUS. */ if (status & AVR32_INT_WAKE_UP) { DPRINTFN(5, "resume interrupt\n"); if (sc->sc_flags.status_suspend) { /* update status bits */ sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 1; /* disable resume interrupt */ avr32dci_mod_ien(sc, AVR32_INT_DET_SUSPD | AVR32_INT_ENDRESET, AVR32_INT_WAKE_UP); /* complete root HUB interrupt endpoint */ avr32dci_root_intr(sc); } } else if (status & AVR32_INT_DET_SUSPD) { DPRINTFN(5, "suspend interrupt\n"); if (!sc->sc_flags.status_suspend) { /* update status bits */ sc->sc_flags.status_suspend = 1; sc->sc_flags.change_suspend = 1; /* disable suspend interrupt */ avr32dci_mod_ien(sc, AVR32_INT_WAKE_UP | AVR32_INT_ENDRESET, AVR32_INT_DET_SUSPD); /* complete root HUB interrupt endpoint */ avr32dci_root_intr(sc); } } /* check for any endpoint interrupts */ if (status & -AVR32_INT_EPT_INT(0)) { DPRINTFN(5, "real endpoint interrupt\n"); avr32dci_interrupt_poll(sc); } USB_BUS_UNLOCK(&sc->sc_bus); } static void avr32dci_setup_standard_chain_sub(struct avr32dci_std_temp *temp) { struct avr32dci_td *td; /* get current Transfer Descriptor */ td = temp->td_next; temp->td = td; /* prepare for next TD */ temp->td_next = td->obj_next; /* fill out the Transfer Descriptor */ td->func = temp->func; td->pc = temp->pc; td->offset = temp->offset; td->remainder = temp->len; td->error = 0; td->did_stall = temp->did_stall; td->short_pkt = temp->short_pkt; td->alt_next = temp->setup_alt_next; } static void avr32dci_setup_standard_chain(struct usb_xfer *xfer) { struct avr32dci_std_temp temp; struct avr32dci_softc *sc; struct avr32dci_td *td; uint32_t x; uint8_t ep_no; uint8_t need_sync; DPRINTFN(9, "addr=%d endpt=%d sumlen=%d speed=%d\n", xfer->address, UE_GET_ADDR(xfer->endpointno), xfer->sumlen, usbd_get_speed(xfer->xroot->udev)); temp.max_frame_size = xfer->max_frame_size; td = xfer->td_start[0]; xfer->td_transfer_first = td; xfer->td_transfer_cache = td; /* setup temp */ temp.pc = NULL; temp.td = NULL; temp.td_next = xfer->td_start[0]; temp.offset = 0; temp.setup_alt_next = xfer->flags_int.short_frames_ok || xfer->flags_int.isochronous_xfr; temp.did_stall = !xfer->flags_int.control_stall; sc = AVR32_BUS2SC(xfer->xroot->bus); ep_no = (xfer->endpointno & UE_ADDR); /* check if we should prepend a setup message */ if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_hdr) { temp.func = &avr32dci_setup_rx; temp.len = xfer->frlengths[0]; temp.pc = xfer->frbuffers + 0; temp.short_pkt = temp.len ? 1 : 0; /* check for last frame */ if (xfer->nframes == 1) { /* no STATUS stage yet, SETUP is last */ if (xfer->flags_int.control_act) temp.setup_alt_next = 0; } avr32dci_setup_standard_chain_sub(&temp); } x = 1; } else { x = 0; } if (x != xfer->nframes) { if (xfer->endpointno & UE_DIR_IN) { temp.func = &avr32dci_data_tx; need_sync = 1; } else { temp.func = &avr32dci_data_rx; need_sync = 0; } /* setup "pc" pointer */ temp.pc = xfer->frbuffers + x; } else { need_sync = 0; } while (x != xfer->nframes) { /* DATA0 / DATA1 message */ temp.len = xfer->frlengths[x]; x++; if (x == xfer->nframes) { if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_act) { temp.setup_alt_next = 0; } } else { temp.setup_alt_next = 0; } } if (temp.len == 0) { /* make sure that we send an USB packet */ temp.short_pkt = 0; } else { /* regular data transfer */ temp.short_pkt = (xfer->flags.force_short_xfer) ? 0 : 1; } avr32dci_setup_standard_chain_sub(&temp); if (xfer->flags_int.isochronous_xfr) { temp.offset += temp.len; } else { /* get next Page Cache pointer */ temp.pc = xfer->frbuffers + x; } } if (xfer->flags_int.control_xfr) { /* always setup a valid "pc" pointer for status and sync */ temp.pc = xfer->frbuffers + 0; temp.len = 0; temp.short_pkt = 0; temp.setup_alt_next = 0; /* check if we need to sync */ if (need_sync) { /* we need a SYNC point after TX */ temp.func = &avr32dci_data_tx_sync; avr32dci_setup_standard_chain_sub(&temp); } /* check if we should append a status stage */ if (!xfer->flags_int.control_act) { /* * Send a DATA1 message and invert the current * endpoint direction. */ if (xfer->endpointno & UE_DIR_IN) { temp.func = &avr32dci_data_rx; need_sync = 0; } else { temp.func = &avr32dci_data_tx; need_sync = 1; } avr32dci_setup_standard_chain_sub(&temp); if (need_sync) { /* we need a SYNC point after TX */ temp.func = &avr32dci_data_tx_sync; avr32dci_setup_standard_chain_sub(&temp); } } } /* must have at least one frame! */ td = temp.td; xfer->td_transfer_last = td; } static void avr32dci_timeout(void *arg) { struct usb_xfer *xfer = arg; DPRINTF("xfer=%p\n", xfer); USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED); /* transfer is transferred */ avr32dci_device_done(xfer, USB_ERR_TIMEOUT); } static void avr32dci_start_standard_chain(struct usb_xfer *xfer) { DPRINTFN(9, "\n"); /* poll one time - will turn on interrupts */ if (avr32dci_xfer_do_fifo(xfer)) { uint8_t ep_no = xfer->endpointno & UE_ADDR; struct avr32dci_softc *sc = AVR32_BUS2SC(xfer->xroot->bus); avr32dci_mod_ien(sc, AVR32_INT_EPT_INT(ep_no), 0); /* put transfer on interrupt queue */ usbd_transfer_enqueue(&xfer->xroot->bus->intr_q, xfer); /* start timeout, if any */ if (xfer->timeout != 0) { usbd_transfer_timeout_ms(xfer, &avr32dci_timeout, xfer->timeout); } } } static void avr32dci_root_intr(struct avr32dci_softc *sc) { DPRINTFN(9, "\n"); USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); /* set port bit */ sc->sc_hub_idata[0] = 0x02; /* we only have one port */ uhub_root_intr(&sc->sc_bus, sc->sc_hub_idata, sizeof(sc->sc_hub_idata)); } static usb_error_t avr32dci_standard_done_sub(struct usb_xfer *xfer) { struct avr32dci_td *td; uint32_t len; uint8_t error; DPRINTFN(9, "\n"); td = xfer->td_transfer_cache; do { len = td->remainder; if (xfer->aframes != xfer->nframes) { /* * Verify the length and subtract * the remainder from "frlengths[]": */ if (len > xfer->frlengths[xfer->aframes]) { td->error = 1; } else { xfer->frlengths[xfer->aframes] -= len; } } /* Check for transfer error */ if (td->error) { /* the transfer is finished */ error = 1; td = NULL; break; } /* Check for short transfer */ if (len > 0) { if (xfer->flags_int.short_frames_ok || xfer->flags_int.isochronous_xfr) { /* follow alt next */ if (td->alt_next) { td = td->obj_next; } else { td = NULL; } } else { /* the transfer is finished */ td = NULL; } error = 0; break; } td = td->obj_next; /* this USB frame is complete */ error = 0; break; } while (0); /* update transfer cache */ xfer->td_transfer_cache = td; return (error ? USB_ERR_STALLED : USB_ERR_NORMAL_COMPLETION); } static void avr32dci_standard_done(struct usb_xfer *xfer) { usb_error_t err = 0; DPRINTFN(13, "xfer=%p pipe=%p transfer done\n", xfer, xfer->endpoint); /* reset scanner */ xfer->td_transfer_cache = xfer->td_transfer_first; if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_hdr) { err = avr32dci_standard_done_sub(xfer); } xfer->aframes = 1; if (xfer->td_transfer_cache == NULL) { goto done; } } while (xfer->aframes != xfer->nframes) { err = avr32dci_standard_done_sub(xfer); xfer->aframes++; if (xfer->td_transfer_cache == NULL) { goto done; } } if (xfer->flags_int.control_xfr && !xfer->flags_int.control_act) { err = avr32dci_standard_done_sub(xfer); } done: avr32dci_device_done(xfer, err); } /*------------------------------------------------------------------------* * avr32dci_device_done * * NOTE: this function can be called more than one time on the * same USB transfer! *------------------------------------------------------------------------*/ static void avr32dci_device_done(struct usb_xfer *xfer, usb_error_t error) { struct avr32dci_softc *sc = AVR32_BUS2SC(xfer->xroot->bus); uint8_t ep_no; USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); DPRINTFN(9, "xfer=%p, pipe=%p, error=%d\n", xfer, xfer->endpoint, error); if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) { ep_no = (xfer->endpointno & UE_ADDR); /* disable endpoint interrupt */ avr32dci_mod_ien(sc, 0, AVR32_INT_EPT_INT(ep_no)); DPRINTFN(15, "disabled interrupts!\n"); } /* dequeue transfer and start next transfer */ usbd_transfer_done(xfer, error); } static void avr32dci_xfer_stall(struct usb_xfer *xfer) { avr32dci_device_done(xfer, USB_ERR_STALLED); } static void avr32dci_set_stall(struct usb_device *udev, struct usb_endpoint *pipe, uint8_t *did_stall) { struct avr32dci_softc *sc; uint8_t ep_no; USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED); DPRINTFN(5, "pipe=%p\n", pipe); sc = AVR32_BUS2SC(udev->bus); /* get endpoint number */ ep_no = (pipe->edesc->bEndpointAddress & UE_ADDR); /* set stall */ AVR32_WRITE_4(sc, AVR32_EPTSETSTA(ep_no), AVR32_EPTSTA_FRCESTALL); } static void avr32dci_clear_stall_sub(struct avr32dci_softc *sc, uint8_t ep_no, uint8_t ep_type, uint8_t ep_dir) { const struct usb_hw_ep_profile *pf; uint32_t temp; uint32_t epsize; uint8_t n; if (ep_type == UE_CONTROL) { /* clearing stall is not needed */ return; } /* set endpoint reset */ AVR32_WRITE_4(sc, AVR32_EPTRST, AVR32_EPTRST_MASK(ep_no)); /* set stall */ AVR32_WRITE_4(sc, AVR32_EPTSETSTA(ep_no), AVR32_EPTSTA_FRCESTALL); /* reset data toggle */ AVR32_WRITE_4(sc, AVR32_EPTCLRSTA(ep_no), AVR32_EPTSTA_TOGGLESQ); /* clear stall */ AVR32_WRITE_4(sc, AVR32_EPTCLRSTA(ep_no), AVR32_EPTSTA_FRCESTALL); if (ep_type == UE_BULK) { temp = AVR32_EPTCFG_TYPE_BULK; } else if (ep_type == UE_INTERRUPT) { temp = AVR32_EPTCFG_TYPE_INTR; } else { temp = AVR32_EPTCFG_TYPE_ISOC | AVR32_EPTCFG_NB_TRANS(1); } if (ep_dir & UE_DIR_IN) { temp |= AVR32_EPTCFG_EPDIR_IN; } avr32dci_get_hw_ep_profile(NULL, &pf, ep_no); /* compute endpoint size (use maximum) */ epsize = pf->max_in_frame_size | pf->max_out_frame_size; n = 0; while ((epsize /= 2)) n++; temp |= AVR32_EPTCFG_EPSIZE(n); /* use the maximum number of banks supported */ if (ep_no < 1) temp |= AVR32_EPTCFG_NBANK(1); else if (ep_no < 3) temp |= AVR32_EPTCFG_NBANK(2); else temp |= AVR32_EPTCFG_NBANK(3); AVR32_WRITE_4(sc, AVR32_EPTCFG(ep_no), temp); temp = AVR32_READ_4(sc, AVR32_EPTCFG(ep_no)); if (!(temp & AVR32_EPTCFG_EPT_MAPD)) { device_printf(sc->sc_bus.bdev, "Chip rejected configuration\n"); } else { AVR32_WRITE_4(sc, AVR32_EPTCTLENB(ep_no), AVR32_EPTCTL_EPT_ENABL); } } static void avr32dci_clear_stall(struct usb_device *udev, struct usb_endpoint *pipe) { struct avr32dci_softc *sc; struct usb_endpoint_descriptor *ed; DPRINTFN(5, "pipe=%p\n", pipe); USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED); /* check mode */ if (udev->flags.usb_mode != USB_MODE_DEVICE) { /* not supported */ return; } /* get softc */ sc = AVR32_BUS2SC(udev->bus); /* get endpoint descriptor */ ed = pipe->edesc; /* reset endpoint */ avr32dci_clear_stall_sub(sc, (ed->bEndpointAddress & UE_ADDR), (ed->bmAttributes & UE_XFERTYPE), (ed->bEndpointAddress & (UE_DIR_IN | UE_DIR_OUT))); } usb_error_t avr32dci_init(struct avr32dci_softc *sc) { uint8_t n; DPRINTF("start\n"); /* set up the bus structure */ sc->sc_bus.usbrev = USB_REV_1_1; sc->sc_bus.methods = &avr32dci_bus_methods; USB_BUS_LOCK(&sc->sc_bus); /* make sure USB is enabled */ avr32dci_mod_ctrl(sc, AVR32_CTRL_DEV_EN_USBA, 0); /* turn on clocks */ (sc->sc_clocks_on) (&sc->sc_bus); /* make sure device is re-enumerated */ avr32dci_mod_ctrl(sc, AVR32_CTRL_DEV_DETACH, 0); /* wait a little for things to stabilise */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 20); /* disable interrupts */ avr32dci_mod_ien(sc, 0, 0xFFFFFFFF); /* enable interrupts */ avr32dci_mod_ien(sc, AVR32_INT_DET_SUSPD | AVR32_INT_ENDRESET, 0); /* reset all endpoints */ AVR32_WRITE_4(sc, AVR32_EPTRST, (1 << AVR32_EP_MAX) - 1); /* disable all endpoints */ for (n = 0; n != AVR32_EP_MAX; n++) { /* disable endpoint */ AVR32_WRITE_4(sc, AVR32_EPTCTLDIS(n), AVR32_EPTCTL_EPT_ENABL); } /* turn off clocks */ avr32dci_clocks_off(sc); USB_BUS_UNLOCK(&sc->sc_bus); /* catch any lost interrupts */ avr32dci_do_poll(&sc->sc_bus); return (0); /* success */ } void avr32dci_uninit(struct avr32dci_softc *sc) { uint8_t n; USB_BUS_LOCK(&sc->sc_bus); /* turn on clocks */ (sc->sc_clocks_on) (&sc->sc_bus); /* disable interrupts */ avr32dci_mod_ien(sc, 0, 0xFFFFFFFF); /* reset all endpoints */ AVR32_WRITE_4(sc, AVR32_EPTRST, (1 << AVR32_EP_MAX) - 1); /* disable all endpoints */ for (n = 0; n != AVR32_EP_MAX; n++) { /* disable endpoint */ AVR32_WRITE_4(sc, AVR32_EPTCTLDIS(n), AVR32_EPTCTL_EPT_ENABL); } sc->sc_flags.port_powered = 0; sc->sc_flags.status_vbus = 0; sc->sc_flags.status_bus_reset = 0; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; avr32dci_pull_down(sc); avr32dci_clocks_off(sc); USB_BUS_UNLOCK(&sc->sc_bus); } static void avr32dci_suspend(struct avr32dci_softc *sc) { /* TODO */ } static void avr32dci_resume(struct avr32dci_softc *sc) { /* TODO */ } static void avr32dci_do_poll(struct usb_bus *bus) { struct avr32dci_softc *sc = AVR32_BUS2SC(bus); USB_BUS_LOCK(&sc->sc_bus); avr32dci_interrupt_poll(sc); USB_BUS_UNLOCK(&sc->sc_bus); } /*------------------------------------------------------------------------* * avr32dci bulk support * avr32dci control support * avr32dci interrupt support *------------------------------------------------------------------------*/ static void avr32dci_device_non_isoc_open(struct usb_xfer *xfer) { return; } static void avr32dci_device_non_isoc_close(struct usb_xfer *xfer) { avr32dci_device_done(xfer, USB_ERR_CANCELLED); } static void avr32dci_device_non_isoc_enter(struct usb_xfer *xfer) { return; } static void avr32dci_device_non_isoc_start(struct usb_xfer *xfer) { /* setup TDs */ avr32dci_setup_standard_chain(xfer); avr32dci_start_standard_chain(xfer); } static const struct usb_pipe_methods avr32dci_device_non_isoc_methods = { .open = avr32dci_device_non_isoc_open, .close = avr32dci_device_non_isoc_close, .enter = avr32dci_device_non_isoc_enter, .start = avr32dci_device_non_isoc_start, }; /*------------------------------------------------------------------------* * avr32dci full speed isochronous support *------------------------------------------------------------------------*/ static void avr32dci_device_isoc_fs_open(struct usb_xfer *xfer) { return; } static void avr32dci_device_isoc_fs_close(struct usb_xfer *xfer) { avr32dci_device_done(xfer, USB_ERR_CANCELLED); } static void avr32dci_device_isoc_fs_enter(struct usb_xfer *xfer) { struct avr32dci_softc *sc = AVR32_BUS2SC(xfer->xroot->bus); uint32_t temp; uint32_t nframes; uint8_t ep_no; DPRINTFN(6, "xfer=%p next=%d nframes=%d\n", xfer, xfer->endpoint->isoc_next, xfer->nframes); /* get the current frame index */ ep_no = xfer->endpointno & UE_ADDR; nframes = (AVR32_READ_4(sc, AVR32_FNUM) / 8); nframes &= AVR32_FRAME_MASK; /* * check if the frame index is within the window where the frames * will be inserted */ temp = (nframes - xfer->endpoint->isoc_next) & AVR32_FRAME_MASK; if ((xfer->endpoint->is_synced == 0) || (temp < xfer->nframes)) { /* * If there is data underflow or the pipe queue is * empty we schedule the transfer a few frames ahead * of the current frame position. Else two isochronous * transfers might overlap. */ xfer->endpoint->isoc_next = (nframes + 3) & AVR32_FRAME_MASK; xfer->endpoint->is_synced = 1; DPRINTFN(3, "start next=%d\n", xfer->endpoint->isoc_next); } /* * compute how many milliseconds the insertion is ahead of the * current frame position: */ temp = (xfer->endpoint->isoc_next - nframes) & AVR32_FRAME_MASK; /* * pre-compute when the isochronous transfer will be finished: */ xfer->isoc_time_complete = usb_isoc_time_expand(&sc->sc_bus, nframes) + temp + xfer->nframes; /* compute frame number for next insertion */ xfer->endpoint->isoc_next += xfer->nframes; /* setup TDs */ avr32dci_setup_standard_chain(xfer); } static void avr32dci_device_isoc_fs_start(struct usb_xfer *xfer) { /* start TD chain */ avr32dci_start_standard_chain(xfer); } static const struct usb_pipe_methods avr32dci_device_isoc_fs_methods = { .open = avr32dci_device_isoc_fs_open, .close = avr32dci_device_isoc_fs_close, .enter = avr32dci_device_isoc_fs_enter, .start = avr32dci_device_isoc_fs_start, }; /*------------------------------------------------------------------------* * avr32dci root control support *------------------------------------------------------------------------* * Simulate a hardware HUB by handling all the necessary requests. *------------------------------------------------------------------------*/ static const struct usb_device_descriptor avr32dci_devd = { .bLength = sizeof(struct usb_device_descriptor), .bDescriptorType = UDESC_DEVICE, .bcdUSB = {0x00, 0x02}, .bDeviceClass = UDCLASS_HUB, .bDeviceSubClass = UDSUBCLASS_HUB, .bDeviceProtocol = UDPROTO_HSHUBSTT, .bMaxPacketSize = 64, .bcdDevice = {0x00, 0x01}, .iManufacturer = 1, .iProduct = 2, .bNumConfigurations = 1, }; static const struct usb_device_qualifier avr32dci_odevd = { .bLength = sizeof(struct usb_device_qualifier), .bDescriptorType = UDESC_DEVICE_QUALIFIER, .bcdUSB = {0x00, 0x02}, .bDeviceClass = UDCLASS_HUB, .bDeviceSubClass = UDSUBCLASS_HUB, .bDeviceProtocol = UDPROTO_FSHUB, .bMaxPacketSize0 = 0, .bNumConfigurations = 0, }; static const struct avr32dci_config_desc avr32dci_confd = { .confd = { .bLength = sizeof(struct usb_config_descriptor), .bDescriptorType = UDESC_CONFIG, .wTotalLength[0] = sizeof(avr32dci_confd), .bNumInterface = 1, .bConfigurationValue = 1, .iConfiguration = 0, .bmAttributes = UC_SELF_POWERED, .bMaxPower = 0, }, .ifcd = { .bLength = sizeof(struct usb_interface_descriptor), .bDescriptorType = UDESC_INTERFACE, .bNumEndpoints = 1, .bInterfaceClass = UICLASS_HUB, .bInterfaceSubClass = UISUBCLASS_HUB, .bInterfaceProtocol = 0, }, .endpd = { .bLength = sizeof(struct usb_endpoint_descriptor), .bDescriptorType = UDESC_ENDPOINT, .bEndpointAddress = (UE_DIR_IN | AVR32_INTR_ENDPT), .bmAttributes = UE_INTERRUPT, .wMaxPacketSize[0] = 8, .bInterval = 255, }, }; #define HSETW(ptr, val) ptr = { (uint8_t)(val), (uint8_t)((val) >> 8) } static const struct usb_hub_descriptor_min avr32dci_hubd = { .bDescLength = sizeof(avr32dci_hubd), .bDescriptorType = UDESC_HUB, .bNbrPorts = 1, HSETW(.wHubCharacteristics, (UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL)), .bPwrOn2PwrGood = 50, .bHubContrCurrent = 0, .DeviceRemovable = {0}, /* port is removable */ }; #define STRING_VENDOR \ "A\0V\0R\0003\0002" #define STRING_PRODUCT \ "D\0C\0I\0 \0R\0o\0o\0t\0 \0H\0U\0B" USB_MAKE_STRING_DESC(STRING_VENDOR, avr32dci_vendor); USB_MAKE_STRING_DESC(STRING_PRODUCT, avr32dci_product); static usb_error_t avr32dci_roothub_exec(struct usb_device *udev, struct usb_device_request *req, const void **pptr, uint16_t *plength) { struct avr32dci_softc *sc = AVR32_BUS2SC(udev->bus); const void *ptr; uint16_t len; uint16_t value; uint16_t index; uint32_t temp; usb_error_t err; USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); /* buffer reset */ ptr = (const void *)&sc->sc_hub_temp; len = 0; err = 0; value = UGETW(req->wValue); index = UGETW(req->wIndex); /* demultiplex the control request */ switch (req->bmRequestType) { case UT_READ_DEVICE: switch (req->bRequest) { case UR_GET_DESCRIPTOR: goto tr_handle_get_descriptor; case UR_GET_CONFIG: goto tr_handle_get_config; case UR_GET_STATUS: goto tr_handle_get_status; default: goto tr_stalled; } break; case UT_WRITE_DEVICE: switch (req->bRequest) { case UR_SET_ADDRESS: goto tr_handle_set_address; case UR_SET_CONFIG: goto tr_handle_set_config; case UR_CLEAR_FEATURE: goto tr_valid; /* nop */ case UR_SET_DESCRIPTOR: goto tr_valid; /* nop */ case UR_SET_FEATURE: default: goto tr_stalled; } break; case UT_WRITE_ENDPOINT: switch (req->bRequest) { case UR_CLEAR_FEATURE: switch (UGETW(req->wValue)) { case UF_ENDPOINT_HALT: goto tr_handle_clear_halt; case UF_DEVICE_REMOTE_WAKEUP: goto tr_handle_clear_wakeup; default: goto tr_stalled; } break; case UR_SET_FEATURE: switch (UGETW(req->wValue)) { case UF_ENDPOINT_HALT: goto tr_handle_set_halt; case UF_DEVICE_REMOTE_WAKEUP: goto tr_handle_set_wakeup; default: goto tr_stalled; } break; case UR_SYNCH_FRAME: goto tr_valid; /* nop */ default: goto tr_stalled; } break; case UT_READ_ENDPOINT: switch (req->bRequest) { case UR_GET_STATUS: goto tr_handle_get_ep_status; default: goto tr_stalled; } break; case UT_WRITE_INTERFACE: switch (req->bRequest) { case UR_SET_INTERFACE: goto tr_handle_set_interface; case UR_CLEAR_FEATURE: goto tr_valid; /* nop */ case UR_SET_FEATURE: default: goto tr_stalled; } break; case UT_READ_INTERFACE: switch (req->bRequest) { case UR_GET_INTERFACE: goto tr_handle_get_interface; case UR_GET_STATUS: goto tr_handle_get_iface_status; default: goto tr_stalled; } break; case UT_WRITE_CLASS_INTERFACE: case UT_WRITE_VENDOR_INTERFACE: /* XXX forward */ break; case UT_READ_CLASS_INTERFACE: case UT_READ_VENDOR_INTERFACE: /* XXX forward */ break; case UT_WRITE_CLASS_DEVICE: switch (req->bRequest) { case UR_CLEAR_FEATURE: goto tr_valid; case UR_SET_DESCRIPTOR: case UR_SET_FEATURE: break; default: goto tr_stalled; } break; case UT_WRITE_CLASS_OTHER: switch (req->bRequest) { case UR_CLEAR_FEATURE: goto tr_handle_clear_port_feature; case UR_SET_FEATURE: goto tr_handle_set_port_feature; case UR_CLEAR_TT_BUFFER: case UR_RESET_TT: case UR_STOP_TT: goto tr_valid; default: goto tr_stalled; } break; case UT_READ_CLASS_OTHER: switch (req->bRequest) { case UR_GET_TT_STATE: goto tr_handle_get_tt_state; case UR_GET_STATUS: goto tr_handle_get_port_status; default: goto tr_stalled; } break; case UT_READ_CLASS_DEVICE: switch (req->bRequest) { case UR_GET_DESCRIPTOR: goto tr_handle_get_class_descriptor; case UR_GET_STATUS: goto tr_handle_get_class_status; default: goto tr_stalled; } break; default: goto tr_stalled; } goto tr_valid; tr_handle_get_descriptor: switch (value >> 8) { case UDESC_DEVICE: if (value & 0xff) { goto tr_stalled; } len = sizeof(avr32dci_devd); ptr = (const void *)&avr32dci_devd; goto tr_valid; case UDESC_CONFIG: if (value & 0xff) { goto tr_stalled; } len = sizeof(avr32dci_confd); ptr = (const void *)&avr32dci_confd; goto tr_valid; case UDESC_STRING: switch (value & 0xff) { case 0: /* Language table */ len = sizeof(usb_string_lang_en); ptr = (const void *)&usb_string_lang_en; goto tr_valid; case 1: /* Vendor */ len = sizeof(avr32dci_vendor); ptr = (const void *)&avr32dci_vendor; goto tr_valid; case 2: /* Product */ len = sizeof(avr32dci_product); ptr = (const void *)&avr32dci_product; goto tr_valid; default: break; } break; default: goto tr_stalled; } goto tr_stalled; tr_handle_get_config: len = 1; sc->sc_hub_temp.wValue[0] = sc->sc_conf; goto tr_valid; tr_handle_get_status: len = 2; USETW(sc->sc_hub_temp.wValue, UDS_SELF_POWERED); goto tr_valid; tr_handle_set_address: if (value & 0xFF00) { goto tr_stalled; } sc->sc_rt_addr = value; goto tr_valid; tr_handle_set_config: if (value >= 2) { goto tr_stalled; } sc->sc_conf = value; goto tr_valid; tr_handle_get_interface: len = 1; sc->sc_hub_temp.wValue[0] = 0; goto tr_valid; tr_handle_get_tt_state: tr_handle_get_class_status: tr_handle_get_iface_status: tr_handle_get_ep_status: len = 2; USETW(sc->sc_hub_temp.wValue, 0); goto tr_valid; tr_handle_set_halt: tr_handle_set_interface: tr_handle_set_wakeup: tr_handle_clear_wakeup: tr_handle_clear_halt: goto tr_valid; tr_handle_clear_port_feature: if (index != 1) { goto tr_stalled; } DPRINTFN(9, "UR_CLEAR_PORT_FEATURE on port %d\n", index); switch (value) { case UHF_PORT_SUSPEND: avr32dci_wakeup_peer(sc); break; case UHF_PORT_ENABLE: sc->sc_flags.port_enabled = 0; break; case UHF_PORT_TEST: case UHF_PORT_INDICATOR: case UHF_C_PORT_ENABLE: case UHF_C_PORT_OVER_CURRENT: case UHF_C_PORT_RESET: /* nops */ break; case UHF_PORT_POWER: sc->sc_flags.port_powered = 0; avr32dci_pull_down(sc); avr32dci_clocks_off(sc); break; case UHF_C_PORT_CONNECTION: /* clear connect change flag */ sc->sc_flags.change_connect = 0; if (!sc->sc_flags.status_bus_reset) { /* we are not connected */ break; } /* configure the control endpoint */ /* set endpoint reset */ AVR32_WRITE_4(sc, AVR32_EPTRST, AVR32_EPTRST_MASK(0)); /* set stall */ AVR32_WRITE_4(sc, AVR32_EPTSETSTA(0), AVR32_EPTSTA_FRCESTALL); /* reset data toggle */ AVR32_WRITE_4(sc, AVR32_EPTCLRSTA(0), AVR32_EPTSTA_TOGGLESQ); /* clear stall */ AVR32_WRITE_4(sc, AVR32_EPTCLRSTA(0), AVR32_EPTSTA_FRCESTALL); /* configure */ AVR32_WRITE_4(sc, AVR32_EPTCFG(0), AVR32_EPTCFG_TYPE_CTRL | AVR32_EPTCFG_NBANK(1) | AVR32_EPTCFG_EPSIZE(6)); temp = AVR32_READ_4(sc, AVR32_EPTCFG(0)); if (!(temp & AVR32_EPTCFG_EPT_MAPD)) { device_printf(sc->sc_bus.bdev, "Chip rejected configuration\n"); } else { AVR32_WRITE_4(sc, AVR32_EPTCTLENB(0), AVR32_EPTCTL_EPT_ENABL); } break; case UHF_C_PORT_SUSPEND: sc->sc_flags.change_suspend = 0; break; default: err = USB_ERR_IOERROR; goto done; } goto tr_valid; tr_handle_set_port_feature: if (index != 1) { goto tr_stalled; } DPRINTFN(9, "UR_SET_PORT_FEATURE\n"); switch (value) { case UHF_PORT_ENABLE: sc->sc_flags.port_enabled = 1; break; case UHF_PORT_SUSPEND: case UHF_PORT_RESET: case UHF_PORT_TEST: case UHF_PORT_INDICATOR: /* nops */ break; case UHF_PORT_POWER: sc->sc_flags.port_powered = 1; break; default: err = USB_ERR_IOERROR; goto done; } goto tr_valid; tr_handle_get_port_status: DPRINTFN(9, "UR_GET_PORT_STATUS\n"); if (index != 1) { goto tr_stalled; } if (sc->sc_flags.status_vbus) { avr32dci_clocks_on(sc); avr32dci_pull_up(sc); } else { avr32dci_pull_down(sc); avr32dci_clocks_off(sc); } /* Select Device Side Mode */ value = UPS_PORT_MODE_DEVICE; /* Check for High Speed */ if (AVR32_READ_4(sc, AVR32_INTSTA) & AVR32_INT_SPEED) value |= UPS_HIGH_SPEED; if (sc->sc_flags.port_powered) { value |= UPS_PORT_POWER; } if (sc->sc_flags.port_enabled) { value |= UPS_PORT_ENABLED; } if (sc->sc_flags.status_vbus && sc->sc_flags.status_bus_reset) { value |= UPS_CURRENT_CONNECT_STATUS; } if (sc->sc_flags.status_suspend) { value |= UPS_SUSPEND; } USETW(sc->sc_hub_temp.ps.wPortStatus, value); value = 0; if (sc->sc_flags.change_connect) { value |= UPS_C_CONNECT_STATUS; } if (sc->sc_flags.change_suspend) { value |= UPS_C_SUSPEND; } USETW(sc->sc_hub_temp.ps.wPortChange, value); len = sizeof(sc->sc_hub_temp.ps); goto tr_valid; tr_handle_get_class_descriptor: if (value & 0xFF) { goto tr_stalled; } ptr = (const void *)&avr32dci_hubd; len = sizeof(avr32dci_hubd); goto tr_valid; tr_stalled: err = USB_ERR_STALLED; tr_valid: done: *plength = len; *pptr = ptr; return (err); } static void avr32dci_xfer_setup(struct usb_setup_params *parm) { const struct usb_hw_ep_profile *pf; struct avr32dci_softc *sc; struct usb_xfer *xfer; void *last_obj; uint32_t ntd; uint32_t n; uint8_t ep_no; sc = AVR32_BUS2SC(parm->udev->bus); xfer = parm->curr_xfer; /* * NOTE: This driver does not use any of the parameters that * are computed from the following values. Just set some * reasonable dummies: */ parm->hc_max_packet_size = 0x400; parm->hc_max_packet_count = 1; parm->hc_max_frame_size = 0x400; usbd_transfer_setup_sub(parm); /* * compute maximum number of TDs */ if ((xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) == UE_CONTROL) { ntd = xfer->nframes + 1 /* STATUS */ + 1 /* SYNC 1 */ + 1 /* SYNC 2 */ ; } else { ntd = xfer->nframes + 1 /* SYNC */ ; } /* * check if "usbd_transfer_setup_sub" set an error */ if (parm->err) return; /* * allocate transfer descriptors */ last_obj = NULL; /* * get profile stuff */ ep_no = xfer->endpointno & UE_ADDR; avr32dci_get_hw_ep_profile(parm->udev, &pf, ep_no); if (pf == NULL) { /* should not happen */ parm->err = USB_ERR_INVAL; return; } /* align data */ parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1)); for (n = 0; n != ntd; n++) { struct avr32dci_td *td; if (parm->buf) { uint32_t temp; td = USB_ADD_BYTES(parm->buf, parm->size[0]); /* init TD */ td->max_packet_size = xfer->max_packet_size; td->ep_no = ep_no; temp = pf->max_in_frame_size | pf->max_out_frame_size; td->bank_shift = 0; while ((temp /= 2)) td->bank_shift++; if (pf->support_multi_buffer) { td->support_multi_buffer = 1; } td->obj_next = last_obj; last_obj = td; } parm->size[0] += sizeof(*td); } xfer->td_start[0] = last_obj; } static void avr32dci_xfer_unsetup(struct usb_xfer *xfer) { return; } static void avr32dci_ep_init(struct usb_device *udev, struct usb_endpoint_descriptor *edesc, struct usb_endpoint *pipe) { struct avr32dci_softc *sc = AVR32_BUS2SC(udev->bus); DPRINTFN(2, "pipe=%p, addr=%d, endpt=%d, mode=%d (%d,%d)\n", pipe, udev->address, edesc->bEndpointAddress, udev->flags.usb_mode, sc->sc_rt_addr, udev->device_index); if (udev->device_index != sc->sc_rt_addr) { if ((udev->speed != USB_SPEED_FULL) && (udev->speed != USB_SPEED_HIGH)) { /* not supported */ return; } if ((edesc->bmAttributes & UE_XFERTYPE) == UE_ISOCHRONOUS) pipe->methods = &avr32dci_device_isoc_fs_methods; else pipe->methods = &avr32dci_device_non_isoc_methods; } } static void avr32dci_set_hw_power_sleep(struct usb_bus *bus, uint32_t state) { struct avr32dci_softc *sc = AVR32_BUS2SC(bus); switch (state) { case USB_HW_POWER_SUSPEND: avr32dci_suspend(sc); break; case USB_HW_POWER_SHUTDOWN: avr32dci_uninit(sc); break; case USB_HW_POWER_RESUME: avr32dci_resume(sc); break; default: break; } } static const struct usb_bus_methods avr32dci_bus_methods = { .endpoint_init = &avr32dci_ep_init, .xfer_setup = &avr32dci_xfer_setup, .xfer_unsetup = &avr32dci_xfer_unsetup, .get_hw_ep_profile = &avr32dci_get_hw_ep_profile, .xfer_stall = &avr32dci_xfer_stall, .set_stall = &avr32dci_set_stall, .clear_stall = &avr32dci_clear_stall, .roothub_exec = &avr32dci_roothub_exec, .xfer_poll = &avr32dci_do_poll, .set_hw_power_sleep = &avr32dci_set_hw_power_sleep, }; Index: head/sys/dev/usb/controller/musb_otg.c =================================================================== --- head/sys/dev/usb/controller/musb_otg.c (revision 276700) +++ head/sys/dev/usb/controller/musb_otg.c (revision 276701) @@ -1,4244 +1,4244 @@ /* $FreeBSD$ */ /*- * Copyright (c) 2008 Hans Petter Selasky. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Thanks to Mentor Graphics for providing a reference driver for this USB chip * at their homepage. */ /* * This file contains the driver for the Mentor Graphics Inventra USB * 2.0 High Speed Dual-Role controller. * * NOTE: The current implementation only supports Device Side Mode! */ #ifdef USB_GLOBAL_INCLUDE_FILE #include USB_GLOBAL_INCLUDE_FILE #else #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define USB_DEBUG_VAR musbotgdebug #include #include #include #include #include #include #include #include #include #include #endif /* USB_GLOBAL_INCLUDE_FILE */ #include #define MUSBOTG_INTR_ENDPT 1 #define MUSBOTG_BUS2SC(bus) \ ((struct musbotg_softc *)(((uint8_t *)(bus)) - \ USB_P2U(&(((struct musbotg_softc *)0)->sc_bus)))) #define MUSBOTG_PC2SC(pc) \ MUSBOTG_BUS2SC(USB_DMATAG_TO_XROOT((pc)->tag_parent)->bus) #ifdef USB_DEBUG static int musbotgdebug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, musbotg, CTLFLAG_RW, 0, "USB musbotg"); -SYSCTL_INT(_hw_usb_musbotg, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_musbotg, OID_AUTO, debug, CTLFLAG_RWTUN, &musbotgdebug, 0, "Debug level"); #endif #define MAX_NAK_TO 16 /* prototypes */ static const struct usb_bus_methods musbotg_bus_methods; static const struct usb_pipe_methods musbotg_device_bulk_methods; static const struct usb_pipe_methods musbotg_device_ctrl_methods; static const struct usb_pipe_methods musbotg_device_intr_methods; static const struct usb_pipe_methods musbotg_device_isoc_methods; /* Control transfers: Device mode */ static musbotg_cmd_t musbotg_dev_ctrl_setup_rx; static musbotg_cmd_t musbotg_dev_ctrl_data_rx; static musbotg_cmd_t musbotg_dev_ctrl_data_tx; static musbotg_cmd_t musbotg_dev_ctrl_status; /* Control transfers: Host mode */ static musbotg_cmd_t musbotg_host_ctrl_setup_tx; static musbotg_cmd_t musbotg_host_ctrl_data_rx; static musbotg_cmd_t musbotg_host_ctrl_data_tx; static musbotg_cmd_t musbotg_host_ctrl_status_rx; static musbotg_cmd_t musbotg_host_ctrl_status_tx; /* Bulk, Interrupt, Isochronous: Device mode */ static musbotg_cmd_t musbotg_dev_data_rx; static musbotg_cmd_t musbotg_dev_data_tx; /* Bulk, Interrupt, Isochronous: Host mode */ static musbotg_cmd_t musbotg_host_data_rx; static musbotg_cmd_t musbotg_host_data_tx; static void musbotg_device_done(struct usb_xfer *, usb_error_t); static void musbotg_do_poll(struct usb_bus *); static void musbotg_standard_done(struct usb_xfer *); static void musbotg_interrupt_poll(struct musbotg_softc *); static void musbotg_root_intr(struct musbotg_softc *); static int musbotg_channel_alloc(struct musbotg_softc *, struct musbotg_td *td, uint8_t); static void musbotg_channel_free(struct musbotg_softc *, struct musbotg_td *td); static void musbotg_ep_int_set(struct musbotg_softc *sc, int channel, int on); /* * Here is a configuration that the chip supports. */ static const struct usb_hw_ep_profile musbotg_ep_profile[1] = { [0] = { .max_in_frame_size = 64,/* fixed */ .max_out_frame_size = 64, /* fixed */ .is_simplex = 1, .support_control = 1, } }; static int musbotg_channel_alloc(struct musbotg_softc *sc, struct musbotg_td *td, uint8_t is_tx) { int ch; int ep; ep = td->ep_no; /* In device mode each EP got its own channel */ if (sc->sc_mode == MUSB2_DEVICE_MODE) { musbotg_ep_int_set(sc, ep, 1); return (ep); } /* * All control transactions go through EP0 */ if (ep == 0) { if (sc->sc_channel_mask & (1 << 0)) return (-1); sc->sc_channel_mask |= (1 << 0); musbotg_ep_int_set(sc, ep, 1); return (0); } for (ch = sc->sc_ep_max; ch != 0; ch--) { if (sc->sc_channel_mask & (1 << ch)) continue; /* check FIFO size requirement */ if (is_tx) { if (td->max_frame_size > sc->sc_hw_ep_profile[ch].max_in_frame_size) continue; } else { if (td->max_frame_size > sc->sc_hw_ep_profile[ch].max_out_frame_size) continue; } sc->sc_channel_mask |= (1 << ch); musbotg_ep_int_set(sc, ch, 1); return (ch); } DPRINTFN(-1, "No available channels. Mask: %04x\n", sc->sc_channel_mask); return (-1); } static void musbotg_channel_free(struct musbotg_softc *sc, struct musbotg_td *td) { DPRINTFN(1, "ep_no=%d\n", td->channel); if (sc->sc_mode == MUSB2_DEVICE_MODE) return; if (td == NULL) return; if (td->channel == -1) return; musbotg_ep_int_set(sc, td->channel, 0); sc->sc_channel_mask &= ~(1 << td->channel); td->channel = -1; } static void musbotg_get_hw_ep_profile(struct usb_device *udev, const struct usb_hw_ep_profile **ppf, uint8_t ep_addr) { struct musbotg_softc *sc; sc = MUSBOTG_BUS2SC(udev->bus); if (ep_addr == 0) { /* control endpoint */ *ppf = musbotg_ep_profile; } else if (ep_addr <= sc->sc_ep_max) { /* other endpoints */ *ppf = sc->sc_hw_ep_profile + ep_addr; } else { *ppf = NULL; } } static void musbotg_clocks_on(struct musbotg_softc *sc) { if (sc->sc_flags.clocks_off && sc->sc_flags.port_powered) { DPRINTFN(4, "\n"); if (sc->sc_clocks_on) { (sc->sc_clocks_on) (sc->sc_clocks_arg); } sc->sc_flags.clocks_off = 0; /* XXX enable Transceiver */ } } static void musbotg_clocks_off(struct musbotg_softc *sc) { if (!sc->sc_flags.clocks_off) { DPRINTFN(4, "\n"); /* XXX disable Transceiver */ if (sc->sc_clocks_off) { (sc->sc_clocks_off) (sc->sc_clocks_arg); } sc->sc_flags.clocks_off = 1; } } static void musbotg_pull_common(struct musbotg_softc *sc, uint8_t on) { uint8_t temp; temp = MUSB2_READ_1(sc, MUSB2_REG_POWER); if (on) temp |= MUSB2_MASK_SOFTC; else temp &= ~MUSB2_MASK_SOFTC; MUSB2_WRITE_1(sc, MUSB2_REG_POWER, temp); } static void musbotg_pull_up(struct musbotg_softc *sc) { /* pullup D+, if possible */ if (!sc->sc_flags.d_pulled_up && sc->sc_flags.port_powered) { sc->sc_flags.d_pulled_up = 1; musbotg_pull_common(sc, 1); } } static void musbotg_pull_down(struct musbotg_softc *sc) { /* pulldown D+, if possible */ if (sc->sc_flags.d_pulled_up) { sc->sc_flags.d_pulled_up = 0; musbotg_pull_common(sc, 0); } } static void musbotg_suspend_host(struct musbotg_softc *sc) { uint8_t temp; if (sc->sc_flags.status_suspend) { return; } temp = MUSB2_READ_1(sc, MUSB2_REG_POWER); temp |= MUSB2_MASK_SUSPMODE; MUSB2_WRITE_1(sc, MUSB2_REG_POWER, temp); sc->sc_flags.status_suspend = 1; } static void musbotg_wakeup_host(struct musbotg_softc *sc) { uint8_t temp; if (!(sc->sc_flags.status_suspend)) { return; } temp = MUSB2_READ_1(sc, MUSB2_REG_POWER); temp &= ~MUSB2_MASK_SUSPMODE; temp |= MUSB2_MASK_RESUME; MUSB2_WRITE_1(sc, MUSB2_REG_POWER, temp); /* wait 20 milliseconds */ /* Wait for reset to complete. */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 50); temp = MUSB2_READ_1(sc, MUSB2_REG_POWER); temp &= ~MUSB2_MASK_RESUME; MUSB2_WRITE_1(sc, MUSB2_REG_POWER, temp); sc->sc_flags.status_suspend = 0; } static void musbotg_wakeup_peer(struct musbotg_softc *sc) { uint8_t temp; if (!(sc->sc_flags.status_suspend)) { return; } temp = MUSB2_READ_1(sc, MUSB2_REG_POWER); temp |= MUSB2_MASK_RESUME; MUSB2_WRITE_1(sc, MUSB2_REG_POWER, temp); /* wait 8 milliseconds */ /* Wait for reset to complete. */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 125); temp = MUSB2_READ_1(sc, MUSB2_REG_POWER); temp &= ~MUSB2_MASK_RESUME; MUSB2_WRITE_1(sc, MUSB2_REG_POWER, temp); } static void musbotg_set_address(struct musbotg_softc *sc, uint8_t addr) { DPRINTFN(4, "addr=%d\n", addr); addr &= 0x7F; MUSB2_WRITE_1(sc, MUSB2_REG_FADDR, addr); } static uint8_t musbotg_dev_ctrl_setup_rx(struct musbotg_td *td) { struct musbotg_softc *sc; struct usb_device_request req; uint16_t count; uint8_t csr; /* get pointer to softc */ sc = MUSBOTG_PC2SC(td->pc); if (td->channel == -1) td->channel = musbotg_channel_alloc(sc, td, 0); /* EP0 is busy, wait */ if (td->channel == -1) return (1); DPRINTFN(1, "ep_no=%d\n", td->channel); /* select endpoint 0 */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, 0); /* read out FIFO status */ csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); DPRINTFN(4, "csr=0x%02x\n", csr); /* * NOTE: If DATAEND is set we should not call the * callback, hence the status stage is not complete. */ if (csr & MUSB2_MASK_CSR0L_DATAEND) { /* do not stall at this point */ td->did_stall = 1; /* wait for interrupt */ DPRINTFN(0, "CSR0 DATAEND\n"); goto not_complete; } if (csr & MUSB2_MASK_CSR0L_SENTSTALL) { /* clear SENTSTALL */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, 0); /* get latest status */ csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); /* update EP0 state */ sc->sc_ep0_busy = 0; } if (csr & MUSB2_MASK_CSR0L_SETUPEND) { /* clear SETUPEND */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSR0L_SETUPEND_CLR); /* get latest status */ csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); /* update EP0 state */ sc->sc_ep0_busy = 0; } if (sc->sc_ep0_busy) { DPRINTFN(0, "EP0 BUSY\n"); goto not_complete; } if (!(csr & MUSB2_MASK_CSR0L_RXPKTRDY)) { goto not_complete; } /* clear did stall flag */ td->did_stall = 0; /* get the packet byte count */ count = MUSB2_READ_2(sc, MUSB2_REG_RXCOUNT); /* verify data length */ if (count != td->remainder) { DPRINTFN(0, "Invalid SETUP packet " "length, %d bytes\n", count); MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSR0L_RXPKTRDY_CLR); goto not_complete; } if (count != sizeof(req)) { DPRINTFN(0, "Unsupported SETUP packet " "length, %d bytes\n", count); MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSR0L_RXPKTRDY_CLR); goto not_complete; } /* receive data */ bus_space_read_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), (void *)&req, sizeof(req)); /* copy data into real buffer */ usbd_copy_in(td->pc, 0, &req, sizeof(req)); td->offset = sizeof(req); td->remainder = 0; /* set pending command */ sc->sc_ep0_cmd = MUSB2_MASK_CSR0L_RXPKTRDY_CLR; /* we need set stall or dataend after this */ sc->sc_ep0_busy = 1; /* sneak peek the set address */ if ((req.bmRequestType == UT_WRITE_DEVICE) && (req.bRequest == UR_SET_ADDRESS)) { sc->sc_dv_addr = req.wValue[0] & 0x7F; } else { sc->sc_dv_addr = 0xFF; } musbotg_channel_free(sc, td); return (0); /* complete */ not_complete: /* abort any ongoing transfer */ if (!td->did_stall) { DPRINTFN(4, "stalling\n"); MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSR0L_SENDSTALL); td->did_stall = 1; } return (1); /* not complete */ } static uint8_t musbotg_host_ctrl_setup_tx(struct musbotg_td *td) { struct musbotg_softc *sc; struct usb_device_request req; uint8_t csr, csrh; /* get pointer to softc */ sc = MUSBOTG_PC2SC(td->pc); if (td->channel == -1) td->channel = musbotg_channel_alloc(sc, td, 1); /* EP0 is busy, wait */ if (td->channel == -1) return (1); DPRINTFN(1, "ep_no=%d\n", td->channel); /* select endpoint 0 */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, 0); /* read out FIFO status */ csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); DPRINTFN(4, "csr=0x%02x\n", csr); /* Not ready yet yet */ if (csr & MUSB2_MASK_CSR0L_TXPKTRDY) return (1); /* Failed */ if (csr & (MUSB2_MASK_CSR0L_RXSTALL | MUSB2_MASK_CSR0L_ERROR)) { /* Clear status bit */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, 0); DPRINTFN(1, "error bit set, csr=0x%02x\n", csr); td->error = 1; } if (csr & MUSB2_MASK_CSR0L_NAKTIMO) { DPRINTFN(1, "NAK timeout\n"); if (csr & MUSB2_MASK_CSR0L_TXFIFONEMPTY) { csrh = MUSB2_READ_1(sc, MUSB2_REG_TXCSRH); csrh |= MUSB2_MASK_CSR0H_FFLUSH; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRH, csrh); csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); if (csr & MUSB2_MASK_CSR0L_TXFIFONEMPTY) { csrh = MUSB2_READ_1(sc, MUSB2_REG_TXCSRH); csrh |= MUSB2_MASK_CSR0H_FFLUSH; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRH, csrh); csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); } } csr &= ~MUSB2_MASK_CSR0L_NAKTIMO; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, csr); td->error = 1; } if (td->error) { musbotg_channel_free(sc, td); return (0); } /* Fifo is not empty and there is no NAK timeout */ if (csr & MUSB2_MASK_CSR0L_TXPKTRDY) return (1); /* check if we are complete */ if (td->remainder == 0) { /* we are complete */ musbotg_channel_free(sc, td); return (0); } /* copy data into real buffer */ usbd_copy_out(td->pc, 0, &req, sizeof(req)); /* send data */ bus_space_write_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), (void *)&req, sizeof(req)); /* update offset and remainder */ td->offset += sizeof(req); td->remainder -= sizeof(req); MUSB2_WRITE_1(sc, MUSB2_REG_TXNAKLIMIT, MAX_NAK_TO); MUSB2_WRITE_1(sc, MUSB2_REG_TXFADDR(0), td->dev_addr); MUSB2_WRITE_1(sc, MUSB2_REG_TXHADDR(0), td->haddr); MUSB2_WRITE_1(sc, MUSB2_REG_TXHUBPORT(0), td->hport); MUSB2_WRITE_1(sc, MUSB2_REG_TXTI, td->transfer_type); /* write command */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSR0L_TXPKTRDY | MUSB2_MASK_CSR0L_SETUPPKT); /* Just to be consistent, not used above */ td->transaction_started = 1; return (1); /* in progress */ } /* Control endpoint only data handling functions (RX/TX/SYNC) */ static uint8_t musbotg_dev_ctrl_data_rx(struct musbotg_td *td) { struct usb_page_search buf_res; struct musbotg_softc *sc; uint16_t count; uint8_t csr; uint8_t got_short; /* get pointer to softc */ sc = MUSBOTG_PC2SC(td->pc); /* select endpoint 0 */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, 0); /* check if a command is pending */ if (sc->sc_ep0_cmd) { MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, sc->sc_ep0_cmd); sc->sc_ep0_cmd = 0; } /* read out FIFO status */ csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); DPRINTFN(4, "csr=0x%02x\n", csr); got_short = 0; if (csr & (MUSB2_MASK_CSR0L_SETUPEND | MUSB2_MASK_CSR0L_SENTSTALL)) { if (td->remainder == 0) { /* * We are actually complete and have * received the next SETUP */ DPRINTFN(4, "faking complete\n"); return (0); /* complete */ } /* * USB Host Aborted the transfer. */ td->error = 1; return (0); /* complete */ } if (!(csr & MUSB2_MASK_CSR0L_RXPKTRDY)) { return (1); /* not complete */ } /* get the packet byte count */ count = MUSB2_READ_2(sc, MUSB2_REG_RXCOUNT); /* verify the packet byte count */ if (count != td->max_frame_size) { if (count < td->max_frame_size) { /* we have a short packet */ td->short_pkt = 1; got_short = 1; } else { /* invalid USB packet */ td->error = 1; return (0); /* we are complete */ } } /* verify the packet byte count */ if (count > td->remainder) { /* invalid USB packet */ td->error = 1; return (0); /* we are complete */ } while (count > 0) { uint32_t temp; usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* check for unaligned memory address */ if (USB_P2U(buf_res.buffer) & 3) { temp = count & ~3; if (temp) { /* receive data 4 bytes at a time */ bus_space_read_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), sc->sc_bounce_buf, temp / 4); } temp = count & 3; if (temp) { /* receive data 1 byte at a time */ bus_space_read_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), (void *)(&sc->sc_bounce_buf[count / 4]), temp); } usbd_copy_in(td->pc, td->offset, sc->sc_bounce_buf, count); /* update offset and remainder */ td->offset += count; td->remainder -= count; break; } /* check if we can optimise */ if (buf_res.length >= 4) { /* receive data 4 bytes at a time */ bus_space_read_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), buf_res.buffer, buf_res.length / 4); temp = buf_res.length & ~3; /* update counters */ count -= temp; td->offset += temp; td->remainder -= temp; continue; } /* receive data */ bus_space_read_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* check if we are complete */ if ((td->remainder == 0) || got_short) { if (td->short_pkt) { /* we are complete */ sc->sc_ep0_cmd = MUSB2_MASK_CSR0L_RXPKTRDY_CLR; return (0); } /* else need to receive a zero length packet */ } /* write command - need more data */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSR0L_RXPKTRDY_CLR); return (1); /* not complete */ } static uint8_t musbotg_dev_ctrl_data_tx(struct musbotg_td *td) { struct usb_page_search buf_res; struct musbotg_softc *sc; uint16_t count; uint8_t csr; /* get pointer to softc */ sc = MUSBOTG_PC2SC(td->pc); /* select endpoint 0 */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, 0); /* check if a command is pending */ if (sc->sc_ep0_cmd) { MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, sc->sc_ep0_cmd); sc->sc_ep0_cmd = 0; } /* read out FIFO status */ csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); DPRINTFN(4, "csr=0x%02x\n", csr); if (csr & (MUSB2_MASK_CSR0L_SETUPEND | MUSB2_MASK_CSR0L_SENTSTALL)) { /* * The current transfer was aborted * by the USB Host */ td->error = 1; return (0); /* complete */ } if (csr & MUSB2_MASK_CSR0L_TXPKTRDY) { return (1); /* not complete */ } count = td->max_frame_size; if (td->remainder < count) { /* we have a short packet */ td->short_pkt = 1; count = td->remainder; } while (count > 0) { uint32_t temp; usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* check for unaligned memory address */ if (USB_P2U(buf_res.buffer) & 3) { usbd_copy_out(td->pc, td->offset, sc->sc_bounce_buf, count); temp = count & ~3; if (temp) { /* transmit data 4 bytes at a time */ bus_space_write_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), sc->sc_bounce_buf, temp / 4); } temp = count & 3; if (temp) { /* receive data 1 byte at a time */ bus_space_write_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), ((void *)&sc->sc_bounce_buf[count / 4]), temp); } /* update offset and remainder */ td->offset += count; td->remainder -= count; break; } /* check if we can optimise */ if (buf_res.length >= 4) { /* transmit data 4 bytes at a time */ bus_space_write_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), buf_res.buffer, buf_res.length / 4); temp = buf_res.length & ~3; /* update counters */ count -= temp; td->offset += temp; td->remainder -= temp; continue; } /* transmit data */ bus_space_write_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* check remainder */ if (td->remainder == 0) { if (td->short_pkt) { sc->sc_ep0_cmd = MUSB2_MASK_CSR0L_TXPKTRDY; return (0); /* complete */ } /* else we need to transmit a short packet */ } /* write command */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSR0L_TXPKTRDY); return (1); /* not complete */ } static uint8_t musbotg_host_ctrl_data_rx(struct musbotg_td *td) { struct usb_page_search buf_res; struct musbotg_softc *sc; uint16_t count; uint8_t csr; uint8_t got_short; /* get pointer to softc */ sc = MUSBOTG_PC2SC(td->pc); if (td->channel == -1) td->channel = musbotg_channel_alloc(sc, td, 0); /* EP0 is busy, wait */ if (td->channel == -1) return (1); DPRINTFN(1, "ep_no=%d\n", td->channel); /* select endpoint 0 */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, 0); /* read out FIFO status */ csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); DPRINTFN(4, "csr=0x%02x\n", csr); got_short = 0; if (!td->transaction_started) { td->transaction_started = 1; MUSB2_WRITE_1(sc, MUSB2_REG_RXNAKLIMIT, MAX_NAK_TO); MUSB2_WRITE_1(sc, MUSB2_REG_RXFADDR(0), td->dev_addr); MUSB2_WRITE_1(sc, MUSB2_REG_RXHADDR(0), td->haddr); MUSB2_WRITE_1(sc, MUSB2_REG_RXHUBPORT(0), td->hport); MUSB2_WRITE_1(sc, MUSB2_REG_RXTI, td->transfer_type); MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSR0L_REQPKT); return (1); } if (csr & MUSB2_MASK_CSR0L_NAKTIMO) { csr &= ~MUSB2_MASK_CSR0L_REQPKT; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, csr); csr &= ~MUSB2_MASK_CSR0L_NAKTIMO; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, csr); td->error = 1; } /* Failed */ if (csr & (MUSB2_MASK_CSR0L_RXSTALL | MUSB2_MASK_CSR0L_ERROR)) { /* Clear status bit */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, 0); DPRINTFN(1, "error bit set, csr=0x%02x\n", csr); td->error = 1; } if (td->error) { musbotg_channel_free(sc, td); return (0); /* we are complete */ } if (!(csr & MUSB2_MASK_CSR0L_RXPKTRDY)) return (1); /* not yet */ /* get the packet byte count */ count = MUSB2_READ_2(sc, MUSB2_REG_RXCOUNT); /* verify the packet byte count */ if (count != td->max_frame_size) { if (count < td->max_frame_size) { /* we have a short packet */ td->short_pkt = 1; got_short = 1; } else { /* invalid USB packet */ td->error = 1; musbotg_channel_free(sc, td); return (0); /* we are complete */ } } /* verify the packet byte count */ if (count > td->remainder) { /* invalid USB packet */ td->error = 1; musbotg_channel_free(sc, td); return (0); /* we are complete */ } while (count > 0) { uint32_t temp; usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* check for unaligned memory address */ if (USB_P2U(buf_res.buffer) & 3) { temp = count & ~3; if (temp) { /* receive data 4 bytes at a time */ bus_space_read_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), sc->sc_bounce_buf, temp / 4); } temp = count & 3; if (temp) { /* receive data 1 byte at a time */ bus_space_read_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), (void *)(&sc->sc_bounce_buf[count / 4]), temp); } usbd_copy_in(td->pc, td->offset, sc->sc_bounce_buf, count); /* update offset and remainder */ td->offset += count; td->remainder -= count; break; } /* check if we can optimise */ if (buf_res.length >= 4) { /* receive data 4 bytes at a time */ bus_space_read_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), buf_res.buffer, buf_res.length / 4); temp = buf_res.length & ~3; /* update counters */ count -= temp; td->offset += temp; td->remainder -= temp; continue; } /* receive data */ bus_space_read_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } csr &= ~MUSB2_MASK_CSR0L_RXPKTRDY; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, csr); /* check if we are complete */ if ((td->remainder == 0) || got_short) { if (td->short_pkt) { /* we are complete */ musbotg_channel_free(sc, td); return (0); } /* else need to receive a zero length packet */ } td->transaction_started = 1; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSR0L_REQPKT); return (1); /* not complete */ } static uint8_t musbotg_host_ctrl_data_tx(struct musbotg_td *td) { struct usb_page_search buf_res; struct musbotg_softc *sc; uint16_t count; uint8_t csr, csrh; /* get pointer to softc */ sc = MUSBOTG_PC2SC(td->pc); if (td->channel == -1) td->channel = musbotg_channel_alloc(sc, td, 1); /* No free EPs */ if (td->channel == -1) return (1); DPRINTFN(1, "ep_no=%d\n", td->channel); /* select endpoint */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, 0); /* read out FIFO status */ csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); DPRINTFN(4, "csr=0x%02x\n", csr); if (csr & (MUSB2_MASK_CSR0L_RXSTALL | MUSB2_MASK_CSR0L_ERROR)) { /* clear status bits */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, 0); td->error = 1; } if (csr & MUSB2_MASK_CSR0L_NAKTIMO ) { if (csr & MUSB2_MASK_CSR0L_TXFIFONEMPTY) { csrh = MUSB2_READ_1(sc, MUSB2_REG_TXCSRH); csrh |= MUSB2_MASK_CSR0H_FFLUSH; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRH, csrh); csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); if (csr & MUSB2_MASK_CSR0L_TXFIFONEMPTY) { csrh = MUSB2_READ_1(sc, MUSB2_REG_TXCSRH); csrh |= MUSB2_MASK_CSR0H_FFLUSH; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRH, csrh); csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); } } csr &= ~MUSB2_MASK_CSR0L_NAKTIMO; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, csr); td->error = 1; } if (td->error) { musbotg_channel_free(sc, td); return (0); /* complete */ } /* * Wait while FIFO is empty. * Do not flush it because it will cause transactions * with size more then packet size. It might upset * some devices */ if (csr & MUSB2_MASK_CSR0L_TXFIFONEMPTY) return (1); /* Packet still being processed */ if (csr & MUSB2_MASK_CSR0L_TXPKTRDY) return (1); if (td->transaction_started) { /* check remainder */ if (td->remainder == 0) { if (td->short_pkt) { musbotg_channel_free(sc, td); return (0); /* complete */ } /* else we need to transmit a short packet */ } /* We're not complete - more transactions required */ td->transaction_started = 0; } /* check for short packet */ count = td->max_frame_size; if (td->remainder < count) { /* we have a short packet */ td->short_pkt = 1; count = td->remainder; } while (count > 0) { uint32_t temp; usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* check for unaligned memory address */ if (USB_P2U(buf_res.buffer) & 3) { usbd_copy_out(td->pc, td->offset, sc->sc_bounce_buf, count); temp = count & ~3; if (temp) { /* transmit data 4 bytes at a time */ bus_space_write_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), sc->sc_bounce_buf, temp / 4); } temp = count & 3; if (temp) { /* receive data 1 byte at a time */ bus_space_write_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), ((void *)&sc->sc_bounce_buf[count / 4]), temp); } /* update offset and remainder */ td->offset += count; td->remainder -= count; break; } /* check if we can optimise */ if (buf_res.length >= 4) { /* transmit data 4 bytes at a time */ bus_space_write_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), buf_res.buffer, buf_res.length / 4); temp = buf_res.length & ~3; /* update counters */ count -= temp; td->offset += temp; td->remainder -= temp; continue; } /* transmit data */ bus_space_write_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(0), buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* Function address */ MUSB2_WRITE_1(sc, MUSB2_REG_TXFADDR(0), td->dev_addr); MUSB2_WRITE_1(sc, MUSB2_REG_TXHADDR(0), td->haddr); MUSB2_WRITE_1(sc, MUSB2_REG_TXHUBPORT(0), td->hport); MUSB2_WRITE_1(sc, MUSB2_REG_TXTI, td->transfer_type); /* TX NAK timeout */ MUSB2_WRITE_1(sc, MUSB2_REG_TXNAKLIMIT, MAX_NAK_TO); /* write command */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSR0L_TXPKTRDY); td->transaction_started = 1; return (1); /* not complete */ } static uint8_t musbotg_dev_ctrl_status(struct musbotg_td *td) { struct musbotg_softc *sc; uint8_t csr; /* get pointer to softc */ sc = MUSBOTG_PC2SC(td->pc); /* select endpoint 0 */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, 0); if (sc->sc_ep0_busy) { sc->sc_ep0_busy = 0; sc->sc_ep0_cmd |= MUSB2_MASK_CSR0L_DATAEND; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, sc->sc_ep0_cmd); sc->sc_ep0_cmd = 0; } /* read out FIFO status */ csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); DPRINTFN(4, "csr=0x%02x\n", csr); if (csr & MUSB2_MASK_CSR0L_DATAEND) { /* wait for interrupt */ return (1); /* not complete */ } if (sc->sc_dv_addr != 0xFF) { /* write function address */ musbotg_set_address(sc, sc->sc_dv_addr); } musbotg_channel_free(sc, td); return (0); /* complete */ } static uint8_t musbotg_host_ctrl_status_rx(struct musbotg_td *td) { struct musbotg_softc *sc; uint8_t csr, csrh; /* get pointer to softc */ sc = MUSBOTG_PC2SC(td->pc); if (td->channel == -1) td->channel = musbotg_channel_alloc(sc, td, 0); /* EP0 is busy, wait */ if (td->channel == -1) return (1); DPRINTFN(1, "ep_no=%d\n", td->channel); /* select endpoint 0 */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, 0); if (!td->transaction_started) { MUSB2_WRITE_1(sc, MUSB2_REG_RXFADDR(0), td->dev_addr); MUSB2_WRITE_1(sc, MUSB2_REG_RXHADDR(0), td->haddr); MUSB2_WRITE_1(sc, MUSB2_REG_RXHUBPORT(0), td->hport); MUSB2_WRITE_1(sc, MUSB2_REG_RXTI, td->transfer_type); /* RX NAK timeout */ MUSB2_WRITE_1(sc, MUSB2_REG_RXNAKLIMIT, MAX_NAK_TO); td->transaction_started = 1; /* Disable PING */ csrh = MUSB2_READ_1(sc, MUSB2_REG_RXCSRH); csrh |= MUSB2_MASK_CSR0H_PING_DIS; MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRH, csrh); /* write command */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSR0L_STATUSPKT | MUSB2_MASK_CSR0L_REQPKT); return (1); /* Just started */ } csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); DPRINTFN(4, "IN STATUS csr=0x%02x\n", csr); if (csr & MUSB2_MASK_CSR0L_RXPKTRDY) { MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSR0L_RXPKTRDY_CLR); musbotg_channel_free(sc, td); return (0); /* complete */ } if (csr & MUSB2_MASK_CSR0L_NAKTIMO) { csr &= ~ (MUSB2_MASK_CSR0L_STATUSPKT | MUSB2_MASK_CSR0L_REQPKT); MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, csr); csr &= ~MUSB2_MASK_CSR0L_NAKTIMO; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, csr); td->error = 1; } /* Failed */ if (csr & (MUSB2_MASK_CSR0L_RXSTALL | MUSB2_MASK_CSR0L_ERROR)) { /* Clear status bit */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, 0); DPRINTFN(1, "error bit set, csr=0x%02x\n", csr); td->error = 1; } if (td->error) { musbotg_channel_free(sc, td); return (0); } return (1); /* Not ready yet */ } static uint8_t musbotg_host_ctrl_status_tx(struct musbotg_td *td) { struct musbotg_softc *sc; uint8_t csr; /* get pointer to softc */ sc = MUSBOTG_PC2SC(td->pc); if (td->channel == -1) td->channel = musbotg_channel_alloc(sc, td, 1); /* EP0 is busy, wait */ if (td->channel == -1) return (1); DPRINTFN(1, "ep_no=%d/%d [%d@%d.%d/%02x]\n", td->channel, td->transaction_started, td->dev_addr,td->haddr,td->hport, td->transfer_type); /* select endpoint 0 */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, 0); csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); DPRINTFN(4, "csr=0x%02x\n", csr); /* Not yet */ if (csr & MUSB2_MASK_CSR0L_TXPKTRDY) return (1); /* Failed */ if (csr & (MUSB2_MASK_CSR0L_RXSTALL | MUSB2_MASK_CSR0L_ERROR)) { /* Clear status bit */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, 0); DPRINTFN(1, "error bit set, csr=0x%02x\n", csr); td->error = 1; musbotg_channel_free(sc, td); return (0); /* complete */ } if (td->transaction_started) { musbotg_channel_free(sc, td); return (0); /* complete */ } MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRH, MUSB2_MASK_CSR0H_PING_DIS); MUSB2_WRITE_1(sc, MUSB2_REG_TXFADDR(0), td->dev_addr); MUSB2_WRITE_1(sc, MUSB2_REG_TXHADDR(0), td->haddr); MUSB2_WRITE_1(sc, MUSB2_REG_TXHUBPORT(0), td->hport); MUSB2_WRITE_1(sc, MUSB2_REG_TXTI, td->transfer_type); /* TX NAK timeout */ MUSB2_WRITE_1(sc, MUSB2_REG_TXNAKLIMIT, MAX_NAK_TO); td->transaction_started = 1; /* write command */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSR0L_STATUSPKT | MUSB2_MASK_CSR0L_TXPKTRDY); return (1); /* wait for interrupt */ } static uint8_t musbotg_dev_data_rx(struct musbotg_td *td) { struct usb_page_search buf_res; struct musbotg_softc *sc; uint16_t count; uint8_t csr; uint8_t to; uint8_t got_short; to = 8; /* don't loop forever! */ got_short = 0; /* get pointer to softc */ sc = MUSBOTG_PC2SC(td->pc); if (td->channel == -1) td->channel = musbotg_channel_alloc(sc, td, 0); /* EP0 is busy, wait */ if (td->channel == -1) return (1); /* select endpoint */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, td->channel); repeat: /* read out FIFO status */ csr = MUSB2_READ_1(sc, MUSB2_REG_RXCSRL); DPRINTFN(4, "csr=0x%02x\n", csr); /* clear overrun */ if (csr & MUSB2_MASK_CSRL_RXOVERRUN) { /* make sure we don't clear "RXPKTRDY" */ MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRL, MUSB2_MASK_CSRL_RXPKTRDY); } /* check status */ if (!(csr & MUSB2_MASK_CSRL_RXPKTRDY)) return (1); /* not complete */ /* get the packet byte count */ count = MUSB2_READ_2(sc, MUSB2_REG_RXCOUNT); DPRINTFN(4, "count=0x%04x\n", count); /* * Check for short or invalid packet: */ if (count != td->max_frame_size) { if (count < td->max_frame_size) { /* we have a short packet */ td->short_pkt = 1; got_short = 1; } else { /* invalid USB packet */ td->error = 1; musbotg_channel_free(sc, td); return (0); /* we are complete */ } } /* verify the packet byte count */ if (count > td->remainder) { /* invalid USB packet */ td->error = 1; musbotg_channel_free(sc, td); return (0); /* we are complete */ } while (count > 0) { uint32_t temp; usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* check for unaligned memory address */ if (USB_P2U(buf_res.buffer) & 3) { temp = count & ~3; if (temp) { /* receive data 4 bytes at a time */ bus_space_read_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), sc->sc_bounce_buf, temp / 4); } temp = count & 3; if (temp) { /* receive data 1 byte at a time */ bus_space_read_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), ((void *)&sc->sc_bounce_buf[count / 4]), temp); } usbd_copy_in(td->pc, td->offset, sc->sc_bounce_buf, count); /* update offset and remainder */ td->offset += count; td->remainder -= count; break; } /* check if we can optimise */ if (buf_res.length >= 4) { /* receive data 4 bytes at a time */ bus_space_read_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), buf_res.buffer, buf_res.length / 4); temp = buf_res.length & ~3; /* update counters */ count -= temp; td->offset += temp; td->remainder -= temp; continue; } /* receive data */ bus_space_read_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* clear status bits */ MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRL, 0); /* check if we are complete */ if ((td->remainder == 0) || got_short) { if (td->short_pkt) { /* we are complete */ musbotg_channel_free(sc, td); return (0); } /* else need to receive a zero length packet */ } if (--to) { goto repeat; } return (1); /* not complete */ } static uint8_t musbotg_dev_data_tx(struct musbotg_td *td) { struct usb_page_search buf_res; struct musbotg_softc *sc; uint16_t count; uint8_t csr; uint8_t to; to = 8; /* don't loop forever! */ /* get pointer to softc */ sc = MUSBOTG_PC2SC(td->pc); if (td->channel == -1) td->channel = musbotg_channel_alloc(sc, td, 1); /* EP0 is busy, wait */ if (td->channel == -1) return (1); /* select endpoint */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, td->channel); repeat: /* read out FIFO status */ csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); DPRINTFN(4, "csr=0x%02x\n", csr); if (csr & (MUSB2_MASK_CSRL_TXINCOMP | MUSB2_MASK_CSRL_TXUNDERRUN)) { /* clear status bits */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, 0); } if (csr & MUSB2_MASK_CSRL_TXPKTRDY) { return (1); /* not complete */ } /* check for short packet */ count = td->max_frame_size; if (td->remainder < count) { /* we have a short packet */ td->short_pkt = 1; count = td->remainder; } while (count > 0) { uint32_t temp; usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* check for unaligned memory address */ if (USB_P2U(buf_res.buffer) & 3) { usbd_copy_out(td->pc, td->offset, sc->sc_bounce_buf, count); temp = count & ~3; if (temp) { /* transmit data 4 bytes at a time */ bus_space_write_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), sc->sc_bounce_buf, temp / 4); } temp = count & 3; if (temp) { /* receive data 1 byte at a time */ bus_space_write_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), ((void *)&sc->sc_bounce_buf[count / 4]), temp); } /* update offset and remainder */ td->offset += count; td->remainder -= count; break; } /* check if we can optimise */ if (buf_res.length >= 4) { /* transmit data 4 bytes at a time */ bus_space_write_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), buf_res.buffer, buf_res.length / 4); temp = buf_res.length & ~3; /* update counters */ count -= temp; td->offset += temp; td->remainder -= temp; continue; } /* transmit data */ bus_space_write_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* Max packet size */ MUSB2_WRITE_2(sc, MUSB2_REG_TXMAXP, td->reg_max_packet); /* write command */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSRL_TXPKTRDY); /* check remainder */ if (td->remainder == 0) { if (td->short_pkt) { musbotg_channel_free(sc, td); return (0); /* complete */ } /* else we need to transmit a short packet */ } if (--to) { goto repeat; } return (1); /* not complete */ } static uint8_t musbotg_host_data_rx(struct musbotg_td *td) { struct usb_page_search buf_res; struct musbotg_softc *sc; uint16_t count; uint8_t csr, csrh; uint8_t to; uint8_t got_short; /* get pointer to softc */ sc = MUSBOTG_PC2SC(td->pc); if (td->channel == -1) td->channel = musbotg_channel_alloc(sc, td, 0); /* No free EPs */ if (td->channel == -1) return (1); DPRINTFN(1, "ep_no=%d\n", td->channel); to = 8; /* don't loop forever! */ got_short = 0; /* select endpoint */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, td->channel); repeat: /* read out FIFO status */ csr = MUSB2_READ_1(sc, MUSB2_REG_RXCSRL); DPRINTFN(4, "csr=0x%02x\n", csr); if (!td->transaction_started) { /* Function address */ MUSB2_WRITE_1(sc, MUSB2_REG_RXFADDR(td->channel), td->dev_addr); /* SPLIT transaction */ MUSB2_WRITE_1(sc, MUSB2_REG_RXHADDR(td->channel), td->haddr); MUSB2_WRITE_1(sc, MUSB2_REG_RXHUBPORT(td->channel), td->hport); /* RX NAK timeout */ if (td->transfer_type & MUSB2_MASK_TI_PROTO_ISOC) MUSB2_WRITE_1(sc, MUSB2_REG_RXNAKLIMIT, 0); else MUSB2_WRITE_1(sc, MUSB2_REG_RXNAKLIMIT, MAX_NAK_TO); /* Protocol, speed, device endpoint */ MUSB2_WRITE_1(sc, MUSB2_REG_RXTI, td->transfer_type); /* Max packet size */ MUSB2_WRITE_2(sc, MUSB2_REG_RXMAXP, td->reg_max_packet); /* Data Toggle */ csrh = MUSB2_READ_1(sc, MUSB2_REG_RXCSRH); DPRINTFN(4, "csrh=0x%02x\n", csrh); csrh |= MUSB2_MASK_CSRH_RXDT_WREN; if (td->toggle) csrh |= MUSB2_MASK_CSRH_RXDT_VAL; else csrh &= ~MUSB2_MASK_CSRH_RXDT_VAL; /* Set data toggle */ MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRH, csrh); /* write command */ MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRL, MUSB2_MASK_CSRL_RXREQPKT); td->transaction_started = 1; return (1); } /* clear NAK timeout */ if (csr & MUSB2_MASK_CSRL_RXNAKTO) { DPRINTFN(4, "NAK Timeout\n"); if (csr & MUSB2_MASK_CSRL_RXREQPKT) { csr &= ~MUSB2_MASK_CSRL_RXREQPKT; MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRL, csr); csr &= ~MUSB2_MASK_CSRL_RXNAKTO; MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRL, csr); } td->error = 1; } if (csr & MUSB2_MASK_CSRL_RXERROR) { DPRINTFN(4, "RXERROR\n"); td->error = 1; } if (csr & MUSB2_MASK_CSRL_RXSTALL) { DPRINTFN(4, "RXSTALL\n"); td->error = 1; } if (td->error) { musbotg_channel_free(sc, td); return (0); /* we are complete */ } if (!(csr & MUSB2_MASK_CSRL_RXPKTRDY)) { /* No data available yet */ return (1); } td->toggle ^= 1; /* get the packet byte count */ count = MUSB2_READ_2(sc, MUSB2_REG_RXCOUNT); DPRINTFN(4, "count=0x%04x\n", count); /* * Check for short or invalid packet: */ if (count != td->max_frame_size) { if (count < td->max_frame_size) { /* we have a short packet */ td->short_pkt = 1; got_short = 1; } else { /* invalid USB packet */ td->error = 1; musbotg_channel_free(sc, td); return (0); /* we are complete */ } } /* verify the packet byte count */ if (count > td->remainder) { /* invalid USB packet */ td->error = 1; musbotg_channel_free(sc, td); return (0); /* we are complete */ } while (count > 0) { uint32_t temp; usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* check for unaligned memory address */ if (USB_P2U(buf_res.buffer) & 3) { temp = count & ~3; if (temp) { /* receive data 4 bytes at a time */ bus_space_read_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), sc->sc_bounce_buf, temp / 4); } temp = count & 3; if (temp) { /* receive data 1 byte at a time */ bus_space_read_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), ((void *)&sc->sc_bounce_buf[count / 4]), temp); } usbd_copy_in(td->pc, td->offset, sc->sc_bounce_buf, count); /* update offset and remainder */ td->offset += count; td->remainder -= count; break; } /* check if we can optimise */ if (buf_res.length >= 4) { /* receive data 4 bytes at a time */ bus_space_read_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), buf_res.buffer, buf_res.length / 4); temp = buf_res.length & ~3; /* update counters */ count -= temp; td->offset += temp; td->remainder -= temp; continue; } /* receive data */ bus_space_read_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* clear status bits */ MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRL, 0); /* check if we are complete */ if ((td->remainder == 0) || got_short) { if (td->short_pkt) { /* we are complete */ musbotg_channel_free(sc, td); return (0); } /* else need to receive a zero length packet */ } /* Reset transaction state and restart */ td->transaction_started = 0; if (--to) goto repeat; return (1); /* not complete */ } static uint8_t musbotg_host_data_tx(struct musbotg_td *td) { struct usb_page_search buf_res; struct musbotg_softc *sc; uint16_t count; uint8_t csr, csrh; /* get pointer to softc */ sc = MUSBOTG_PC2SC(td->pc); if (td->channel == -1) td->channel = musbotg_channel_alloc(sc, td, 1); /* No free EPs */ if (td->channel == -1) return (1); DPRINTFN(1, "ep_no=%d\n", td->channel); /* select endpoint */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, td->channel); /* read out FIFO status */ csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); DPRINTFN(4, "csr=0x%02x\n", csr); if (csr & (MUSB2_MASK_CSRL_TXSTALLED | MUSB2_MASK_CSRL_TXERROR)) { /* clear status bits */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, 0); td->error = 1; musbotg_channel_free(sc, td); return (0); /* complete */ } if (csr & MUSB2_MASK_CSRL_TXNAKTO) { /* * Flush TX FIFO before clearing NAK TO */ if (csr & MUSB2_MASK_CSRL_TXFIFONEMPTY) { csr |= MUSB2_MASK_CSRL_TXFFLUSH; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, csr); csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); if (csr & MUSB2_MASK_CSRL_TXFIFONEMPTY) { csr |= MUSB2_MASK_CSRL_TXFFLUSH; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, csr); csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); } } csr &= ~MUSB2_MASK_CSRL_TXNAKTO; MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, csr); td->error = 1; musbotg_channel_free(sc, td); return (0); /* complete */ } /* * Wait while FIFO is empty. * Do not flush it because it will cause transactions * with size more then packet size. It might upset * some devices */ if (csr & MUSB2_MASK_CSRL_TXFIFONEMPTY) return (1); /* Packet still being processed */ if (csr & MUSB2_MASK_CSRL_TXPKTRDY) return (1); if (td->transaction_started) { /* check remainder */ if (td->remainder == 0) { if (td->short_pkt) { musbotg_channel_free(sc, td); return (0); /* complete */ } /* else we need to transmit a short packet */ } /* We're not complete - more transactions required */ td->transaction_started = 0; } /* check for short packet */ count = td->max_frame_size; if (td->remainder < count) { /* we have a short packet */ td->short_pkt = 1; count = td->remainder; } while (count > 0) { uint32_t temp; usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* check for unaligned memory address */ if (USB_P2U(buf_res.buffer) & 3) { usbd_copy_out(td->pc, td->offset, sc->sc_bounce_buf, count); temp = count & ~3; if (temp) { /* transmit data 4 bytes at a time */ bus_space_write_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), sc->sc_bounce_buf, temp / 4); } temp = count & 3; if (temp) { /* receive data 1 byte at a time */ bus_space_write_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), ((void *)&sc->sc_bounce_buf[count / 4]), temp); } /* update offset and remainder */ td->offset += count; td->remainder -= count; break; } /* check if we can optimise */ if (buf_res.length >= 4) { /* transmit data 4 bytes at a time */ bus_space_write_multi_4(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), buf_res.buffer, buf_res.length / 4); temp = buf_res.length & ~3; /* update counters */ count -= temp; td->offset += temp; td->remainder -= temp; continue; } /* transmit data */ bus_space_write_multi_1(sc->sc_io_tag, sc->sc_io_hdl, MUSB2_REG_EPFIFO(td->channel), buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* Function address */ MUSB2_WRITE_1(sc, MUSB2_REG_TXFADDR(td->channel), td->dev_addr); /* SPLIT transaction */ MUSB2_WRITE_1(sc, MUSB2_REG_TXHADDR(td->channel), td->haddr); MUSB2_WRITE_1(sc, MUSB2_REG_TXHUBPORT(td->channel), td->hport); /* TX NAK timeout */ if (td->transfer_type & MUSB2_MASK_TI_PROTO_ISOC) MUSB2_WRITE_1(sc, MUSB2_REG_TXNAKLIMIT, 0); else MUSB2_WRITE_1(sc, MUSB2_REG_TXNAKLIMIT, MAX_NAK_TO); /* Protocol, speed, device endpoint */ MUSB2_WRITE_1(sc, MUSB2_REG_TXTI, td->transfer_type); /* Max packet size */ MUSB2_WRITE_2(sc, MUSB2_REG_TXMAXP, td->reg_max_packet); if (!td->transaction_started) { csrh = MUSB2_READ_1(sc, MUSB2_REG_TXCSRH); DPRINTFN(4, "csrh=0x%02x\n", csrh); csrh |= MUSB2_MASK_CSRH_TXDT_WREN; if (td->toggle) csrh |= MUSB2_MASK_CSRH_TXDT_VAL; else csrh &= ~MUSB2_MASK_CSRH_TXDT_VAL; /* Set data toggle */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRH, csrh); } /* write command */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSRL_TXPKTRDY); /* Update Data Toggle */ td->toggle ^= 1; td->transaction_started = 1; return (1); /* not complete */ } static uint8_t musbotg_xfer_do_fifo(struct usb_xfer *xfer) { struct musbotg_softc *sc; struct musbotg_td *td; DPRINTFN(8, "\n"); sc = MUSBOTG_BUS2SC(xfer->xroot->bus); td = xfer->td_transfer_cache; while (1) { if ((td->func) (td)) { /* operation in progress */ break; } if (((void *)td) == xfer->td_transfer_last) { goto done; } if (td->error) { goto done; } else if (td->remainder > 0) { /* * We had a short transfer. If there is no alternate * next, stop processing ! */ if (!td->alt_next) { goto done; } } /* * Fetch the next transfer descriptor and transfer * some flags to the next transfer descriptor */ td = td->obj_next; xfer->td_transfer_cache = td; } return (1); /* not complete */ done: /* compute all actual lengths */ musbotg_standard_done(xfer); return (0); /* complete */ } static void musbotg_interrupt_poll(struct musbotg_softc *sc) { struct usb_xfer *xfer; repeat: TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) { if (!musbotg_xfer_do_fifo(xfer)) { /* queue has been modified */ goto repeat; } } } void musbotg_vbus_interrupt(struct musbotg_softc *sc, uint8_t is_on) { DPRINTFN(4, "vbus = %u\n", is_on); USB_BUS_LOCK(&sc->sc_bus); if (is_on) { if (!sc->sc_flags.status_vbus) { sc->sc_flags.status_vbus = 1; /* complete root HUB interrupt endpoint */ musbotg_root_intr(sc); } } else { if (sc->sc_flags.status_vbus) { sc->sc_flags.status_vbus = 0; sc->sc_flags.status_bus_reset = 0; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; /* complete root HUB interrupt endpoint */ musbotg_root_intr(sc); } } USB_BUS_UNLOCK(&sc->sc_bus); } void musbotg_connect_interrupt(struct musbotg_softc *sc) { USB_BUS_LOCK(&sc->sc_bus); sc->sc_flags.change_connect = 1; /* complete root HUB interrupt endpoint */ musbotg_root_intr(sc); USB_BUS_UNLOCK(&sc->sc_bus); } void musbotg_interrupt(struct musbotg_softc *sc, uint16_t rxstat, uint16_t txstat, uint8_t stat) { uint16_t rx_status; uint16_t tx_status; uint8_t usb_status; uint8_t temp; uint8_t to = 2; USB_BUS_LOCK(&sc->sc_bus); repeat: /* read all interrupt registers */ usb_status = MUSB2_READ_1(sc, MUSB2_REG_INTUSB); /* read all FIFO interrupts */ rx_status = MUSB2_READ_2(sc, MUSB2_REG_INTRX); tx_status = MUSB2_READ_2(sc, MUSB2_REG_INTTX); rx_status |= rxstat; tx_status |= txstat; usb_status |= stat; /* Clear platform flags after first time */ rxstat = 0; txstat = 0; stat = 0; /* check for any bus state change interrupts */ if (usb_status & (MUSB2_MASK_IRESET | MUSB2_MASK_IRESUME | MUSB2_MASK_ISUSP | MUSB2_MASK_ICONN | MUSB2_MASK_IDISC)) { DPRINTFN(4, "real bus interrupt 0x%08x\n", usb_status); if (usb_status & MUSB2_MASK_IRESET) { /* set correct state */ sc->sc_flags.status_bus_reset = 1; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; /* determine line speed */ temp = MUSB2_READ_1(sc, MUSB2_REG_POWER); if (temp & MUSB2_MASK_HSMODE) sc->sc_flags.status_high_speed = 1; else sc->sc_flags.status_high_speed = 0; /* * After reset all interrupts are on and we need to * turn them off! */ temp = MUSB2_MASK_IRESET; /* disable resume interrupt */ temp &= ~MUSB2_MASK_IRESUME; /* enable suspend interrupt */ temp |= MUSB2_MASK_ISUSP; MUSB2_WRITE_1(sc, MUSB2_REG_INTUSBE, temp); /* disable TX and RX interrupts */ MUSB2_WRITE_2(sc, MUSB2_REG_INTTXE, 0); MUSB2_WRITE_2(sc, MUSB2_REG_INTRXE, 0); } /* * If RXRSM and RXSUSP is set at the same time we interpret * that like RESUME. Resume is set when there is at least 3 * milliseconds of inactivity on the USB BUS. */ if (usb_status & MUSB2_MASK_IRESUME) { if (sc->sc_flags.status_suspend) { sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 1; temp = MUSB2_READ_1(sc, MUSB2_REG_INTUSBE); /* disable resume interrupt */ temp &= ~MUSB2_MASK_IRESUME; /* enable suspend interrupt */ temp |= MUSB2_MASK_ISUSP; MUSB2_WRITE_1(sc, MUSB2_REG_INTUSBE, temp); } } else if (usb_status & MUSB2_MASK_ISUSP) { if (!sc->sc_flags.status_suspend) { sc->sc_flags.status_suspend = 1; sc->sc_flags.change_suspend = 1; temp = MUSB2_READ_1(sc, MUSB2_REG_INTUSBE); /* disable suspend interrupt */ temp &= ~MUSB2_MASK_ISUSP; /* enable resume interrupt */ temp |= MUSB2_MASK_IRESUME; MUSB2_WRITE_1(sc, MUSB2_REG_INTUSBE, temp); } } if (usb_status & (MUSB2_MASK_ICONN | MUSB2_MASK_IDISC)) sc->sc_flags.change_connect = 1; /* * Host Mode: There is no IRESET so assume bus is * always in reset state once device is connected. */ if (sc->sc_mode == MUSB2_HOST_MODE) { if (usb_status & MUSB2_MASK_ICONN) sc->sc_flags.status_bus_reset = 1; if (usb_status & MUSB2_MASK_IDISC) sc->sc_flags.status_bus_reset = 0; } /* complete root HUB interrupt endpoint */ musbotg_root_intr(sc); } /* check for any endpoint interrupts */ if (rx_status || tx_status) { DPRINTFN(4, "real endpoint interrupt " "rx=0x%04x, tx=0x%04x\n", rx_status, tx_status); } /* poll one time regardless of FIFO status */ musbotg_interrupt_poll(sc); if (--to) goto repeat; USB_BUS_UNLOCK(&sc->sc_bus); } static void musbotg_setup_standard_chain_sub(struct musbotg_std_temp *temp) { struct musbotg_td *td; /* get current Transfer Descriptor */ td = temp->td_next; temp->td = td; /* prepare for next TD */ temp->td_next = td->obj_next; /* fill out the Transfer Descriptor */ td->func = temp->func; td->pc = temp->pc; td->offset = temp->offset; td->remainder = temp->len; td->error = 0; td->transaction_started = 0; td->did_stall = temp->did_stall; td->short_pkt = temp->short_pkt; td->alt_next = temp->setup_alt_next; td->channel = temp->channel; td->dev_addr = temp->dev_addr; td->haddr = temp->haddr; td->hport = temp->hport; td->transfer_type = temp->transfer_type; } static void musbotg_setup_standard_chain(struct usb_xfer *xfer) { struct musbotg_std_temp temp; struct musbotg_softc *sc; struct musbotg_td *td; uint32_t x; uint8_t ep_no; uint8_t xfer_type; enum usb_dev_speed speed; int tx; int dev_addr; DPRINTFN(8, "addr=%d endpt=%d sumlen=%d speed=%d\n", xfer->address, UE_GET_ADDR(xfer->endpointno), xfer->sumlen, usbd_get_speed(xfer->xroot->udev)); sc = MUSBOTG_BUS2SC(xfer->xroot->bus); ep_no = (xfer->endpointno & UE_ADDR); temp.max_frame_size = xfer->max_frame_size; td = xfer->td_start[0]; xfer->td_transfer_first = td; xfer->td_transfer_cache = td; /* setup temp */ dev_addr = xfer->address; xfer_type = xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE; temp.pc = NULL; temp.td = NULL; temp.td_next = xfer->td_start[0]; temp.offset = 0; temp.setup_alt_next = xfer->flags_int.short_frames_ok || xfer->flags_int.isochronous_xfr; temp.did_stall = !xfer->flags_int.control_stall; temp.channel = -1; temp.dev_addr = dev_addr; temp.haddr = xfer->xroot->udev->hs_hub_addr; temp.hport = xfer->xroot->udev->hs_port_no; if (xfer->flags_int.usb_mode == USB_MODE_HOST) { speed = usbd_get_speed(xfer->xroot->udev); switch (speed) { case USB_SPEED_LOW: temp.transfer_type = MUSB2_MASK_TI_SPEED_LO; break; case USB_SPEED_FULL: temp.transfer_type = MUSB2_MASK_TI_SPEED_FS; break; case USB_SPEED_HIGH: temp.transfer_type = MUSB2_MASK_TI_SPEED_HS; break; default: temp.transfer_type = 0; DPRINTFN(-1, "Invalid USB speed: %d\n", speed); break; } switch (xfer_type) { case UE_CONTROL: temp.transfer_type |= MUSB2_MASK_TI_PROTO_CTRL; break; case UE_ISOCHRONOUS: temp.transfer_type |= MUSB2_MASK_TI_PROTO_ISOC; break; case UE_BULK: temp.transfer_type |= MUSB2_MASK_TI_PROTO_BULK; break; case UE_INTERRUPT: temp.transfer_type |= MUSB2_MASK_TI_PROTO_INTR; break; default: DPRINTFN(-1, "Invalid USB transfer type: %d\n", xfer_type); break; } temp.transfer_type |= ep_no; td->toggle = xfer->endpoint->toggle_next; } /* check if we should prepend a setup message */ if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_hdr) { if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) temp.func = &musbotg_dev_ctrl_setup_rx; else temp.func = &musbotg_host_ctrl_setup_tx; temp.len = xfer->frlengths[0]; temp.pc = xfer->frbuffers + 0; temp.short_pkt = temp.len ? 1 : 0; musbotg_setup_standard_chain_sub(&temp); } x = 1; } else { x = 0; } tx = 0; if (x != xfer->nframes) { if (xfer->endpointno & UE_DIR_IN) tx = 1; if (xfer->flags_int.usb_mode == USB_MODE_HOST) { tx = !tx; if (tx) { if (xfer->flags_int.control_xfr) temp.func = &musbotg_host_ctrl_data_tx; else temp.func = &musbotg_host_data_tx; } else { if (xfer->flags_int.control_xfr) temp.func = &musbotg_host_ctrl_data_rx; else temp.func = &musbotg_host_data_rx; } } else { if (tx) { if (xfer->flags_int.control_xfr) temp.func = &musbotg_dev_ctrl_data_tx; else temp.func = &musbotg_dev_data_tx; } else { if (xfer->flags_int.control_xfr) temp.func = &musbotg_dev_ctrl_data_rx; else temp.func = &musbotg_dev_data_rx; } } /* setup "pc" pointer */ temp.pc = xfer->frbuffers + x; } while (x != xfer->nframes) { /* DATA0 / DATA1 message */ temp.len = xfer->frlengths[x]; x++; if (x == xfer->nframes) { if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_act) { temp.setup_alt_next = 0; } } else { temp.setup_alt_next = 0; } } if (temp.len == 0) { /* make sure that we send an USB packet */ temp.short_pkt = 0; } else { if (xfer->flags_int.isochronous_xfr) { /* isochronous data transfer */ /* don't force short */ temp.short_pkt = 1; } else { /* regular data transfer */ temp.short_pkt = (xfer->flags.force_short_xfer ? 0 : 1); } } musbotg_setup_standard_chain_sub(&temp); if (xfer->flags_int.isochronous_xfr) { temp.offset += temp.len; } else { /* get next Page Cache pointer */ temp.pc = xfer->frbuffers + x; } } /* check for control transfer */ if (xfer->flags_int.control_xfr) { /* always setup a valid "pc" pointer for status and sync */ temp.pc = xfer->frbuffers + 0; temp.len = 0; temp.short_pkt = 0; temp.setup_alt_next = 0; /* check if we should append a status stage */ if (!xfer->flags_int.control_act) { /* * Send a DATA1 message and invert the current * endpoint direction. */ if (sc->sc_mode == MUSB2_DEVICE_MODE) temp.func = &musbotg_dev_ctrl_status; else { if (xfer->endpointno & UE_DIR_IN) temp.func = musbotg_host_ctrl_status_tx; else temp.func = musbotg_host_ctrl_status_rx; } musbotg_setup_standard_chain_sub(&temp); } } /* must have at least one frame! */ td = temp.td; xfer->td_transfer_last = td; } static void musbotg_timeout(void *arg) { struct usb_xfer *xfer = arg; DPRINTFN(1, "xfer=%p\n", xfer); USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED); /* transfer is transferred */ musbotg_device_done(xfer, USB_ERR_TIMEOUT); } static void musbotg_ep_int_set(struct musbotg_softc *sc, int channel, int on) { uint16_t temp; /* * Only enable the endpoint interrupt when we are * actually waiting for data, hence we are dealing * with level triggered interrupts ! */ DPRINTFN(1, "ep_no=%d, on=%d\n", channel, on); if (channel == -1) return; if (channel == 0) { temp = MUSB2_READ_2(sc, MUSB2_REG_INTTXE); if (on) temp |= MUSB2_MASK_EPINT(0); else temp &= ~MUSB2_MASK_EPINT(0); MUSB2_WRITE_2(sc, MUSB2_REG_INTTXE, temp); } else { temp = MUSB2_READ_2(sc, MUSB2_REG_INTRXE); if (on) temp |= MUSB2_MASK_EPINT(channel); else temp &= ~MUSB2_MASK_EPINT(channel); MUSB2_WRITE_2(sc, MUSB2_REG_INTRXE, temp); temp = MUSB2_READ_2(sc, MUSB2_REG_INTTXE); if (on) temp |= MUSB2_MASK_EPINT(channel); else temp &= ~MUSB2_MASK_EPINT(channel); MUSB2_WRITE_2(sc, MUSB2_REG_INTTXE, temp); } if (sc->sc_ep_int_set) sc->sc_ep_int_set(sc, channel, on); } static void musbotg_start_standard_chain(struct usb_xfer *xfer) { DPRINTFN(8, "\n"); /* poll one time */ if (musbotg_xfer_do_fifo(xfer)) { DPRINTFN(14, "enabled interrupts on endpoint\n"); /* put transfer on interrupt queue */ usbd_transfer_enqueue(&xfer->xroot->bus->intr_q, xfer); /* start timeout, if any */ if (xfer->timeout != 0) { usbd_transfer_timeout_ms(xfer, &musbotg_timeout, xfer->timeout); } } } static void musbotg_root_intr(struct musbotg_softc *sc) { DPRINTFN(8, "\n"); USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); /* set port bit */ sc->sc_hub_idata[0] = 0x02; /* we only have one port */ uhub_root_intr(&sc->sc_bus, sc->sc_hub_idata, sizeof(sc->sc_hub_idata)); } static usb_error_t musbotg_standard_done_sub(struct usb_xfer *xfer) { struct musbotg_td *td; uint32_t len; uint8_t error; DPRINTFN(8, "\n"); td = xfer->td_transfer_cache; do { len = td->remainder; xfer->endpoint->toggle_next = td->toggle; if (xfer->aframes != xfer->nframes) { /* * Verify the length and subtract * the remainder from "frlengths[]": */ if (len > xfer->frlengths[xfer->aframes]) { td->error = 1; } else { xfer->frlengths[xfer->aframes] -= len; } } /* Check for transfer error */ if (td->error) { /* the transfer is finished */ error = 1; td = NULL; break; } /* Check for short transfer */ if (len > 0) { if (xfer->flags_int.short_frames_ok || xfer->flags_int.isochronous_xfr) { /* follow alt next */ if (td->alt_next) { td = td->obj_next; } else { td = NULL; } } else { /* the transfer is finished */ td = NULL; } error = 0; break; } td = td->obj_next; /* this USB frame is complete */ error = 0; break; } while (0); /* update transfer cache */ xfer->td_transfer_cache = td; return (error ? USB_ERR_STALLED : USB_ERR_NORMAL_COMPLETION); } static void musbotg_standard_done(struct usb_xfer *xfer) { usb_error_t err = 0; DPRINTFN(12, "xfer=%p endpoint=%p transfer done\n", xfer, xfer->endpoint); /* reset scanner */ xfer->td_transfer_cache = xfer->td_transfer_first; if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_hdr) { err = musbotg_standard_done_sub(xfer); } xfer->aframes = 1; if (xfer->td_transfer_cache == NULL) { goto done; } } while (xfer->aframes != xfer->nframes) { err = musbotg_standard_done_sub(xfer); xfer->aframes++; if (xfer->td_transfer_cache == NULL) { goto done; } } if (xfer->flags_int.control_xfr && !xfer->flags_int.control_act) { err = musbotg_standard_done_sub(xfer); } done: musbotg_device_done(xfer, err); } /*------------------------------------------------------------------------* * musbotg_device_done * * NOTE: this function can be called more than one time on the * same USB transfer! *------------------------------------------------------------------------*/ static void musbotg_device_done(struct usb_xfer *xfer, usb_error_t error) { struct musbotg_td *td; struct musbotg_softc *sc; USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED); DPRINTFN(1, "xfer=%p, endpoint=%p, error=%d\n", xfer, xfer->endpoint, error); DPRINTFN(14, "disabled interrupts on endpoint\n"); sc = MUSBOTG_BUS2SC(xfer->xroot->bus); td = xfer->td_transfer_cache; if (td && (td->channel != -1)) musbotg_channel_free(sc, td); /* dequeue transfer and start next transfer */ usbd_transfer_done(xfer, error); } static void musbotg_xfer_stall(struct usb_xfer *xfer) { musbotg_device_done(xfer, USB_ERR_STALLED); } static void musbotg_set_stall(struct usb_device *udev, struct usb_endpoint *ep, uint8_t *did_stall) { struct musbotg_softc *sc; uint8_t ep_no; USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED); DPRINTFN(4, "endpoint=%p\n", ep); /* set FORCESTALL */ sc = MUSBOTG_BUS2SC(udev->bus); ep_no = (ep->edesc->bEndpointAddress & UE_ADDR); /* select endpoint */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, ep_no); if (ep->edesc->bEndpointAddress & UE_DIR_IN) { MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSRL_TXSENDSTALL); } else { MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRL, MUSB2_MASK_CSRL_RXSENDSTALL); } } static void musbotg_clear_stall_sub(struct musbotg_softc *sc, uint16_t wMaxPacket, uint8_t ep_no, uint8_t ep_type, uint8_t ep_dir) { uint16_t mps; uint16_t temp; uint8_t csr; if (ep_type == UE_CONTROL) { /* clearing stall is not needed */ return; } /* select endpoint */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, ep_no); /* compute max frame size */ mps = wMaxPacket & 0x7FF; switch ((wMaxPacket >> 11) & 3) { case 1: mps *= 2; break; case 2: mps *= 3; break; default: break; } if (ep_dir == UE_DIR_IN) { temp = 0; /* Configure endpoint */ switch (ep_type) { case UE_INTERRUPT: MUSB2_WRITE_2(sc, MUSB2_REG_TXMAXP, wMaxPacket); MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRH, MUSB2_MASK_CSRH_TXMODE | temp); break; case UE_ISOCHRONOUS: MUSB2_WRITE_2(sc, MUSB2_REG_TXMAXP, wMaxPacket); MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRH, MUSB2_MASK_CSRH_TXMODE | MUSB2_MASK_CSRH_TXISO | temp); break; case UE_BULK: MUSB2_WRITE_2(sc, MUSB2_REG_TXMAXP, wMaxPacket); MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRH, MUSB2_MASK_CSRH_TXMODE | temp); break; default: break; } /* Need to flush twice in case of double bufring */ csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); if (csr & MUSB2_MASK_CSRL_TXFIFONEMPTY) { MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSRL_TXFFLUSH); csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); if (csr & MUSB2_MASK_CSRL_TXFIFONEMPTY) { MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSRL_TXFFLUSH); csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); } } /* reset data toggle */ MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, MUSB2_MASK_CSRL_TXDT_CLR); MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, 0); csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); /* set double/single buffering */ temp = MUSB2_READ_2(sc, MUSB2_REG_TXDBDIS); if (mps <= (sc->sc_hw_ep_profile[ep_no]. max_in_frame_size / 2)) { /* double buffer */ temp &= ~(1 << ep_no); } else { /* single buffer */ temp |= (1 << ep_no); } MUSB2_WRITE_2(sc, MUSB2_REG_TXDBDIS, temp); /* clear sent stall */ if (csr & MUSB2_MASK_CSRL_TXSENTSTALL) { MUSB2_WRITE_1(sc, MUSB2_REG_TXCSRL, 0); csr = MUSB2_READ_1(sc, MUSB2_REG_TXCSRL); } } else { temp = 0; /* Configure endpoint */ switch (ep_type) { case UE_INTERRUPT: MUSB2_WRITE_2(sc, MUSB2_REG_RXMAXP, wMaxPacket); MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRH, MUSB2_MASK_CSRH_RXNYET | temp); break; case UE_ISOCHRONOUS: MUSB2_WRITE_2(sc, MUSB2_REG_RXMAXP, wMaxPacket); MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRH, MUSB2_MASK_CSRH_RXNYET | MUSB2_MASK_CSRH_RXISO | temp); break; case UE_BULK: MUSB2_WRITE_2(sc, MUSB2_REG_RXMAXP, wMaxPacket); MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRH, temp); break; default: break; } /* Need to flush twice in case of double bufring */ csr = MUSB2_READ_1(sc, MUSB2_REG_RXCSRL); if (csr & MUSB2_MASK_CSRL_RXPKTRDY) { MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRL, MUSB2_MASK_CSRL_RXFFLUSH); csr = MUSB2_READ_1(sc, MUSB2_REG_RXCSRL); if (csr & MUSB2_MASK_CSRL_RXPKTRDY) { MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRL, MUSB2_MASK_CSRL_RXFFLUSH); csr = MUSB2_READ_1(sc, MUSB2_REG_RXCSRL); } } /* reset data toggle */ MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRL, MUSB2_MASK_CSRL_RXDT_CLR); MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRL, 0); csr = MUSB2_READ_1(sc, MUSB2_REG_RXCSRL); /* set double/single buffering */ temp = MUSB2_READ_2(sc, MUSB2_REG_RXDBDIS); if (mps <= (sc->sc_hw_ep_profile[ep_no]. max_out_frame_size / 2)) { /* double buffer */ temp &= ~(1 << ep_no); } else { /* single buffer */ temp |= (1 << ep_no); } MUSB2_WRITE_2(sc, MUSB2_REG_RXDBDIS, temp); /* clear sent stall */ if (csr & MUSB2_MASK_CSRL_RXSENTSTALL) { MUSB2_WRITE_1(sc, MUSB2_REG_RXCSRL, 0); } } } static void musbotg_clear_stall(struct usb_device *udev, struct usb_endpoint *ep) { struct musbotg_softc *sc; struct usb_endpoint_descriptor *ed; DPRINTFN(4, "endpoint=%p\n", ep); USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED); /* check mode */ if (udev->flags.usb_mode != USB_MODE_DEVICE) { /* not supported */ return; } /* get softc */ sc = MUSBOTG_BUS2SC(udev->bus); /* get endpoint descriptor */ ed = ep->edesc; /* reset endpoint */ musbotg_clear_stall_sub(sc, UGETW(ed->wMaxPacketSize), (ed->bEndpointAddress & UE_ADDR), (ed->bmAttributes & UE_XFERTYPE), (ed->bEndpointAddress & (UE_DIR_IN | UE_DIR_OUT))); } usb_error_t musbotg_init(struct musbotg_softc *sc) { struct usb_hw_ep_profile *pf; uint16_t offset; uint8_t nrx; uint8_t ntx; uint8_t temp; uint8_t fsize; uint8_t frx; uint8_t ftx; uint8_t dynfifo; DPRINTFN(1, "start\n"); /* set up the bus structure */ sc->sc_bus.usbrev = USB_REV_2_0; sc->sc_bus.methods = &musbotg_bus_methods; USB_BUS_LOCK(&sc->sc_bus); /* turn on clocks */ if (sc->sc_clocks_on) { (sc->sc_clocks_on) (sc->sc_clocks_arg); } /* wait a little for things to stabilise */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 1000); /* disable all interrupts */ temp = MUSB2_READ_1(sc, MUSB2_REG_DEVCTL); DPRINTF("pre-DEVCTL=0x%02x\n", temp); MUSB2_WRITE_1(sc, MUSB2_REG_INTUSBE, 0); MUSB2_WRITE_2(sc, MUSB2_REG_INTTXE, 0); MUSB2_WRITE_2(sc, MUSB2_REG_INTRXE, 0); /* disable pullup */ musbotg_pull_common(sc, 0); /* wait a little bit (10ms) */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 100); /* disable double packet buffering */ MUSB2_WRITE_2(sc, MUSB2_REG_RXDBDIS, 0xFFFF); MUSB2_WRITE_2(sc, MUSB2_REG_TXDBDIS, 0xFFFF); /* enable HighSpeed and ISO Update flags */ MUSB2_WRITE_1(sc, MUSB2_REG_POWER, MUSB2_MASK_HSENAB | MUSB2_MASK_ISOUPD); if (sc->sc_mode == MUSB2_DEVICE_MODE) { /* clear Session bit, if set */ temp = MUSB2_READ_1(sc, MUSB2_REG_DEVCTL); temp &= ~MUSB2_MASK_SESS; MUSB2_WRITE_1(sc, MUSB2_REG_DEVCTL, temp); } else { /* Enter session for Host mode */ temp = MUSB2_READ_1(sc, MUSB2_REG_DEVCTL); temp |= MUSB2_MASK_SESS; MUSB2_WRITE_1(sc, MUSB2_REG_DEVCTL, temp); } /* wait a little for things to stabilise */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 10); DPRINTF("DEVCTL=0x%02x\n", temp); /* disable testmode */ MUSB2_WRITE_1(sc, MUSB2_REG_TESTMODE, 0); /* set default value */ MUSB2_WRITE_1(sc, MUSB2_REG_MISC, 0); /* select endpoint index 0 */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, 0); /* read out number of endpoints */ nrx = (MUSB2_READ_1(sc, MUSB2_REG_EPINFO) / 16); ntx = (MUSB2_READ_1(sc, MUSB2_REG_EPINFO) % 16); /* these numbers exclude the control endpoint */ DPRINTFN(2, "RX/TX endpoints: %u/%u\n", nrx, ntx); sc->sc_ep_max = (nrx > ntx) ? nrx : ntx; if (sc->sc_ep_max == 0) { DPRINTFN(2, "ERROR: Looks like the clocks are off!\n"); } /* read out configuration data */ sc->sc_conf_data = MUSB2_READ_1(sc, MUSB2_REG_CONFDATA); DPRINTFN(2, "Config Data: 0x%02x\n", sc->sc_conf_data); dynfifo = (sc->sc_conf_data & MUSB2_MASK_CD_DYNFIFOSZ) ? 1 : 0; if (dynfifo) { device_printf(sc->sc_bus.bdev, "Dynamic FIFO sizing detected, " "assuming 16Kbytes of FIFO RAM\n"); } DPRINTFN(2, "HW version: 0x%04x\n", MUSB2_READ_1(sc, MUSB2_REG_HWVERS)); /* initialise endpoint profiles */ offset = 0; for (temp = 1; temp <= sc->sc_ep_max; temp++) { pf = sc->sc_hw_ep_profile + temp; /* select endpoint */ MUSB2_WRITE_1(sc, MUSB2_REG_EPINDEX, temp); fsize = MUSB2_READ_1(sc, MUSB2_REG_FSIZE); frx = (fsize & MUSB2_MASK_RX_FSIZE) / 16; ftx = (fsize & MUSB2_MASK_TX_FSIZE); DPRINTF("Endpoint %u FIFO size: IN=%u, OUT=%u, DYN=%d\n", temp, ftx, frx, dynfifo); if (dynfifo) { if (frx && (temp <= nrx)) { if (temp == 1) { frx = 12; /* 4K */ MUSB2_WRITE_1(sc, MUSB2_REG_RXFIFOSZ, MUSB2_VAL_FIFOSZ_4096 | MUSB2_MASK_FIFODB); } else if (temp < 8) { frx = 10; /* 1K */ MUSB2_WRITE_1(sc, MUSB2_REG_RXFIFOSZ, MUSB2_VAL_FIFOSZ_512 | MUSB2_MASK_FIFODB); } else { frx = 7; /* 128 bytes */ MUSB2_WRITE_1(sc, MUSB2_REG_RXFIFOSZ, MUSB2_VAL_FIFOSZ_128); } MUSB2_WRITE_2(sc, MUSB2_REG_RXFIFOADD, offset >> 3); offset += (1 << frx); } if (ftx && (temp <= ntx)) { if (temp == 1) { ftx = 12; /* 4K */ MUSB2_WRITE_1(sc, MUSB2_REG_TXFIFOSZ, MUSB2_VAL_FIFOSZ_4096 | MUSB2_MASK_FIFODB); } else if (temp < 8) { ftx = 10; /* 1K */ MUSB2_WRITE_1(sc, MUSB2_REG_TXFIFOSZ, MUSB2_VAL_FIFOSZ_512 | MUSB2_MASK_FIFODB); } else { ftx = 7; /* 128 bytes */ MUSB2_WRITE_1(sc, MUSB2_REG_TXFIFOSZ, MUSB2_VAL_FIFOSZ_128); } MUSB2_WRITE_2(sc, MUSB2_REG_TXFIFOADD, offset >> 3); offset += (1 << ftx); } } if (frx && ftx && (temp <= nrx) && (temp <= ntx)) { pf->max_in_frame_size = 1 << ftx; pf->max_out_frame_size = 1 << frx; pf->is_simplex = 0; /* duplex */ pf->support_multi_buffer = 1; pf->support_bulk = 1; pf->support_interrupt = 1; pf->support_isochronous = 1; pf->support_in = 1; pf->support_out = 1; } else if (frx && (temp <= nrx)) { pf->max_out_frame_size = 1 << frx; pf->max_in_frame_size = 0; pf->is_simplex = 1; /* simplex */ pf->support_multi_buffer = 1; pf->support_bulk = 1; pf->support_interrupt = 1; pf->support_isochronous = 1; pf->support_out = 1; } else if (ftx && (temp <= ntx)) { pf->max_in_frame_size = 1 << ftx; pf->max_out_frame_size = 0; pf->is_simplex = 1; /* simplex */ pf->support_multi_buffer = 1; pf->support_bulk = 1; pf->support_interrupt = 1; pf->support_isochronous = 1; pf->support_in = 1; } } DPRINTFN(2, "Dynamic FIFO size = %d bytes\n", offset); /* turn on default interrupts */ if (sc->sc_mode == MUSB2_HOST_MODE) MUSB2_WRITE_1(sc, MUSB2_REG_INTUSBE, 0xff); else MUSB2_WRITE_1(sc, MUSB2_REG_INTUSBE, MUSB2_MASK_IRESET); musbotg_clocks_off(sc); USB_BUS_UNLOCK(&sc->sc_bus); /* catch any lost interrupts */ musbotg_do_poll(&sc->sc_bus); return (0); /* success */ } void musbotg_uninit(struct musbotg_softc *sc) { USB_BUS_LOCK(&sc->sc_bus); /* disable all interrupts */ MUSB2_WRITE_1(sc, MUSB2_REG_INTUSBE, 0); MUSB2_WRITE_2(sc, MUSB2_REG_INTTXE, 0); MUSB2_WRITE_2(sc, MUSB2_REG_INTRXE, 0); sc->sc_flags.port_powered = 0; sc->sc_flags.status_vbus = 0; sc->sc_flags.status_bus_reset = 0; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; musbotg_pull_down(sc); musbotg_clocks_off(sc); USB_BUS_UNLOCK(&sc->sc_bus); } static void musbotg_do_poll(struct usb_bus *bus) { struct musbotg_softc *sc = MUSBOTG_BUS2SC(bus); USB_BUS_LOCK(&sc->sc_bus); musbotg_interrupt_poll(sc); USB_BUS_UNLOCK(&sc->sc_bus); } /*------------------------------------------------------------------------* * musbotg bulk support *------------------------------------------------------------------------*/ static void musbotg_device_bulk_open(struct usb_xfer *xfer) { return; } static void musbotg_device_bulk_close(struct usb_xfer *xfer) { musbotg_device_done(xfer, USB_ERR_CANCELLED); } static void musbotg_device_bulk_enter(struct usb_xfer *xfer) { return; } static void musbotg_device_bulk_start(struct usb_xfer *xfer) { /* setup TDs */ musbotg_setup_standard_chain(xfer); musbotg_start_standard_chain(xfer); } static const struct usb_pipe_methods musbotg_device_bulk_methods = { .open = musbotg_device_bulk_open, .close = musbotg_device_bulk_close, .enter = musbotg_device_bulk_enter, .start = musbotg_device_bulk_start, }; /*------------------------------------------------------------------------* * musbotg control support *------------------------------------------------------------------------*/ static void musbotg_device_ctrl_open(struct usb_xfer *xfer) { return; } static void musbotg_device_ctrl_close(struct usb_xfer *xfer) { musbotg_device_done(xfer, USB_ERR_CANCELLED); } static void musbotg_device_ctrl_enter(struct usb_xfer *xfer) { return; } static void musbotg_device_ctrl_start(struct usb_xfer *xfer) { /* setup TDs */ musbotg_setup_standard_chain(xfer); musbotg_start_standard_chain(xfer); } static const struct usb_pipe_methods musbotg_device_ctrl_methods = { .open = musbotg_device_ctrl_open, .close = musbotg_device_ctrl_close, .enter = musbotg_device_ctrl_enter, .start = musbotg_device_ctrl_start, }; /*------------------------------------------------------------------------* * musbotg interrupt support *------------------------------------------------------------------------*/ static void musbotg_device_intr_open(struct usb_xfer *xfer) { return; } static void musbotg_device_intr_close(struct usb_xfer *xfer) { musbotg_device_done(xfer, USB_ERR_CANCELLED); } static void musbotg_device_intr_enter(struct usb_xfer *xfer) { return; } static void musbotg_device_intr_start(struct usb_xfer *xfer) { /* setup TDs */ musbotg_setup_standard_chain(xfer); musbotg_start_standard_chain(xfer); } static const struct usb_pipe_methods musbotg_device_intr_methods = { .open = musbotg_device_intr_open, .close = musbotg_device_intr_close, .enter = musbotg_device_intr_enter, .start = musbotg_device_intr_start, }; /*------------------------------------------------------------------------* * musbotg full speed isochronous support *------------------------------------------------------------------------*/ static void musbotg_device_isoc_open(struct usb_xfer *xfer) { return; } static void musbotg_device_isoc_close(struct usb_xfer *xfer) { musbotg_device_done(xfer, USB_ERR_CANCELLED); } static void musbotg_device_isoc_enter(struct usb_xfer *xfer) { struct musbotg_softc *sc = MUSBOTG_BUS2SC(xfer->xroot->bus); uint32_t temp; uint32_t nframes; uint32_t fs_frames; DPRINTFN(5, "xfer=%p next=%d nframes=%d\n", xfer, xfer->endpoint->isoc_next, xfer->nframes); /* get the current frame index */ nframes = MUSB2_READ_2(sc, MUSB2_REG_FRAME); /* * check if the frame index is within the window where the frames * will be inserted */ temp = (nframes - xfer->endpoint->isoc_next) & MUSB2_MASK_FRAME; if (usbd_get_speed(xfer->xroot->udev) == USB_SPEED_HIGH) { fs_frames = (xfer->nframes + 7) / 8; } else { fs_frames = xfer->nframes; } if ((xfer->endpoint->is_synced == 0) || (temp < fs_frames)) { /* * If there is data underflow or the pipe queue is * empty we schedule the transfer a few frames ahead * of the current frame position. Else two isochronous * transfers might overlap. */ xfer->endpoint->isoc_next = (nframes + 3) & MUSB2_MASK_FRAME; xfer->endpoint->is_synced = 1; DPRINTFN(2, "start next=%d\n", xfer->endpoint->isoc_next); } /* * compute how many milliseconds the insertion is ahead of the * current frame position: */ temp = (xfer->endpoint->isoc_next - nframes) & MUSB2_MASK_FRAME; /* * pre-compute when the isochronous transfer will be finished: */ xfer->isoc_time_complete = usb_isoc_time_expand(&sc->sc_bus, nframes) + temp + fs_frames; /* compute frame number for next insertion */ xfer->endpoint->isoc_next += fs_frames; /* setup TDs */ musbotg_setup_standard_chain(xfer); } static void musbotg_device_isoc_start(struct usb_xfer *xfer) { /* start TD chain */ musbotg_start_standard_chain(xfer); } static const struct usb_pipe_methods musbotg_device_isoc_methods = { .open = musbotg_device_isoc_open, .close = musbotg_device_isoc_close, .enter = musbotg_device_isoc_enter, .start = musbotg_device_isoc_start, }; /*------------------------------------------------------------------------* * musbotg root control support *------------------------------------------------------------------------* * Simulate a hardware HUB by handling all the necessary requests. *------------------------------------------------------------------------*/ static const struct usb_device_descriptor musbotg_devd = { .bLength = sizeof(struct usb_device_descriptor), .bDescriptorType = UDESC_DEVICE, .bcdUSB = {0x00, 0x02}, .bDeviceClass = UDCLASS_HUB, .bDeviceSubClass = UDSUBCLASS_HUB, .bDeviceProtocol = UDPROTO_HSHUBSTT, .bMaxPacketSize = 64, .bcdDevice = {0x00, 0x01}, .iManufacturer = 1, .iProduct = 2, .bNumConfigurations = 1, }; static const struct usb_device_qualifier musbotg_odevd = { .bLength = sizeof(struct usb_device_qualifier), .bDescriptorType = UDESC_DEVICE_QUALIFIER, .bcdUSB = {0x00, 0x02}, .bDeviceClass = UDCLASS_HUB, .bDeviceSubClass = UDSUBCLASS_HUB, .bDeviceProtocol = UDPROTO_FSHUB, .bMaxPacketSize0 = 0, .bNumConfigurations = 0, }; static const struct musbotg_config_desc musbotg_confd = { .confd = { .bLength = sizeof(struct usb_config_descriptor), .bDescriptorType = UDESC_CONFIG, .wTotalLength[0] = sizeof(musbotg_confd), .bNumInterface = 1, .bConfigurationValue = 1, .iConfiguration = 0, .bmAttributes = UC_SELF_POWERED, .bMaxPower = 0, }, .ifcd = { .bLength = sizeof(struct usb_interface_descriptor), .bDescriptorType = UDESC_INTERFACE, .bNumEndpoints = 1, .bInterfaceClass = UICLASS_HUB, .bInterfaceSubClass = UISUBCLASS_HUB, .bInterfaceProtocol = 0, }, .endpd = { .bLength = sizeof(struct usb_endpoint_descriptor), .bDescriptorType = UDESC_ENDPOINT, .bEndpointAddress = (UE_DIR_IN | MUSBOTG_INTR_ENDPT), .bmAttributes = UE_INTERRUPT, .wMaxPacketSize[0] = 8, .bInterval = 255, }, }; #define HSETW(ptr, val) ptr = { (uint8_t)(val), (uint8_t)((val) >> 8) } static const struct usb_hub_descriptor_min musbotg_hubd = { .bDescLength = sizeof(musbotg_hubd), .bDescriptorType = UDESC_HUB, .bNbrPorts = 1, HSETW(.wHubCharacteristics, (UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL)), .bPwrOn2PwrGood = 50, .bHubContrCurrent = 0, .DeviceRemovable = {0}, /* port is removable */ }; #define STRING_VENDOR \ "M\0e\0n\0t\0o\0r\0 \0G\0r\0a\0p\0h\0i\0c\0s" #define STRING_PRODUCT \ "O\0T\0G\0 \0R\0o\0o\0t\0 \0H\0U\0B" USB_MAKE_STRING_DESC(STRING_VENDOR, musbotg_vendor); USB_MAKE_STRING_DESC(STRING_PRODUCT, musbotg_product); static usb_error_t musbotg_roothub_exec(struct usb_device *udev, struct usb_device_request *req, const void **pptr, uint16_t *plength) { struct musbotg_softc *sc = MUSBOTG_BUS2SC(udev->bus); const void *ptr; uint16_t len; uint16_t value; uint16_t index; uint8_t reg; usb_error_t err; USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); /* buffer reset */ ptr = (const void *)&sc->sc_hub_temp; len = 0; err = 0; value = UGETW(req->wValue); index = UGETW(req->wIndex); /* demultiplex the control request */ switch (req->bmRequestType) { case UT_READ_DEVICE: switch (req->bRequest) { case UR_GET_DESCRIPTOR: goto tr_handle_get_descriptor; case UR_GET_CONFIG: goto tr_handle_get_config; case UR_GET_STATUS: goto tr_handle_get_status; default: goto tr_stalled; } break; case UT_WRITE_DEVICE: switch (req->bRequest) { case UR_SET_ADDRESS: goto tr_handle_set_address; case UR_SET_CONFIG: goto tr_handle_set_config; case UR_CLEAR_FEATURE: goto tr_valid; /* nop */ case UR_SET_DESCRIPTOR: goto tr_valid; /* nop */ case UR_SET_FEATURE: default: goto tr_stalled; } break; case UT_WRITE_ENDPOINT: switch (req->bRequest) { case UR_CLEAR_FEATURE: switch (UGETW(req->wValue)) { case UF_ENDPOINT_HALT: goto tr_handle_clear_halt; case UF_DEVICE_REMOTE_WAKEUP: goto tr_handle_clear_wakeup; default: goto tr_stalled; } break; case UR_SET_FEATURE: switch (UGETW(req->wValue)) { case UF_ENDPOINT_HALT: goto tr_handle_set_halt; case UF_DEVICE_REMOTE_WAKEUP: goto tr_handle_set_wakeup; default: goto tr_stalled; } break; case UR_SYNCH_FRAME: goto tr_valid; /* nop */ default: goto tr_stalled; } break; case UT_READ_ENDPOINT: switch (req->bRequest) { case UR_GET_STATUS: goto tr_handle_get_ep_status; default: goto tr_stalled; } break; case UT_WRITE_INTERFACE: switch (req->bRequest) { case UR_SET_INTERFACE: goto tr_handle_set_interface; case UR_CLEAR_FEATURE: goto tr_valid; /* nop */ case UR_SET_FEATURE: default: goto tr_stalled; } break; case UT_READ_INTERFACE: switch (req->bRequest) { case UR_GET_INTERFACE: goto tr_handle_get_interface; case UR_GET_STATUS: goto tr_handle_get_iface_status; default: goto tr_stalled; } break; case UT_WRITE_CLASS_INTERFACE: case UT_WRITE_VENDOR_INTERFACE: /* XXX forward */ break; case UT_READ_CLASS_INTERFACE: case UT_READ_VENDOR_INTERFACE: /* XXX forward */ break; case UT_WRITE_CLASS_DEVICE: switch (req->bRequest) { case UR_CLEAR_FEATURE: goto tr_valid; case UR_SET_DESCRIPTOR: case UR_SET_FEATURE: break; default: goto tr_stalled; } break; case UT_WRITE_CLASS_OTHER: switch (req->bRequest) { case UR_CLEAR_FEATURE: goto tr_handle_clear_port_feature; case UR_SET_FEATURE: goto tr_handle_set_port_feature; case UR_CLEAR_TT_BUFFER: case UR_RESET_TT: case UR_STOP_TT: goto tr_valid; default: goto tr_stalled; } break; case UT_READ_CLASS_OTHER: switch (req->bRequest) { case UR_GET_TT_STATE: goto tr_handle_get_tt_state; case UR_GET_STATUS: goto tr_handle_get_port_status; default: goto tr_stalled; } break; case UT_READ_CLASS_DEVICE: switch (req->bRequest) { case UR_GET_DESCRIPTOR: goto tr_handle_get_class_descriptor; case UR_GET_STATUS: goto tr_handle_get_class_status; default: goto tr_stalled; } break; default: goto tr_stalled; } goto tr_valid; tr_handle_get_descriptor: switch (value >> 8) { case UDESC_DEVICE: if (value & 0xff) { goto tr_stalled; } len = sizeof(musbotg_devd); ptr = (const void *)&musbotg_devd; goto tr_valid; case UDESC_DEVICE_QUALIFIER: if (value & 0xff) { goto tr_stalled; } len = sizeof(musbotg_odevd); ptr = (const void *)&musbotg_odevd; goto tr_valid; case UDESC_CONFIG: if (value & 0xff) { goto tr_stalled; } len = sizeof(musbotg_confd); ptr = (const void *)&musbotg_confd; goto tr_valid; case UDESC_STRING: switch (value & 0xff) { case 0: /* Language table */ len = sizeof(usb_string_lang_en); ptr = (const void *)&usb_string_lang_en; goto tr_valid; case 1: /* Vendor */ len = sizeof(musbotg_vendor); ptr = (const void *)&musbotg_vendor; goto tr_valid; case 2: /* Product */ len = sizeof(musbotg_product); ptr = (const void *)&musbotg_product; goto tr_valid; default: break; } break; default: goto tr_stalled; } goto tr_stalled; tr_handle_get_config: len = 1; sc->sc_hub_temp.wValue[0] = sc->sc_conf; goto tr_valid; tr_handle_get_status: len = 2; USETW(sc->sc_hub_temp.wValue, UDS_SELF_POWERED); goto tr_valid; tr_handle_set_address: if (value & 0xFF00) { goto tr_stalled; } sc->sc_rt_addr = value; goto tr_valid; tr_handle_set_config: if (value >= 2) { goto tr_stalled; } sc->sc_conf = value; goto tr_valid; tr_handle_get_interface: len = 1; sc->sc_hub_temp.wValue[0] = 0; goto tr_valid; tr_handle_get_tt_state: tr_handle_get_class_status: tr_handle_get_iface_status: tr_handle_get_ep_status: len = 2; USETW(sc->sc_hub_temp.wValue, 0); goto tr_valid; tr_handle_set_halt: tr_handle_set_interface: tr_handle_set_wakeup: tr_handle_clear_wakeup: tr_handle_clear_halt: goto tr_valid; tr_handle_clear_port_feature: if (index != 1) { goto tr_stalled; } DPRINTFN(8, "UR_CLEAR_PORT_FEATURE on port %d\n", index); switch (value) { case UHF_PORT_SUSPEND: if (sc->sc_mode == MUSB2_HOST_MODE) musbotg_wakeup_host(sc); else musbotg_wakeup_peer(sc); break; case UHF_PORT_ENABLE: sc->sc_flags.port_enabled = 0; break; case UHF_C_PORT_ENABLE: sc->sc_flags.change_enabled = 0; break; case UHF_C_PORT_OVER_CURRENT: sc->sc_flags.change_over_current = 0; break; case UHF_C_PORT_RESET: sc->sc_flags.change_reset = 0; break; case UHF_PORT_TEST: case UHF_PORT_INDICATOR: /* nops */ break; case UHF_PORT_POWER: sc->sc_flags.port_powered = 0; musbotg_pull_down(sc); musbotg_clocks_off(sc); break; case UHF_C_PORT_CONNECTION: sc->sc_flags.change_connect = 0; break; case UHF_C_PORT_SUSPEND: sc->sc_flags.change_suspend = 0; break; default: err = USB_ERR_IOERROR; goto done; } goto tr_valid; tr_handle_set_port_feature: if (index != 1) { goto tr_stalled; } DPRINTFN(8, "UR_SET_PORT_FEATURE\n"); switch (value) { case UHF_PORT_ENABLE: sc->sc_flags.port_enabled = 1; break; case UHF_PORT_SUSPEND: if (sc->sc_mode == MUSB2_HOST_MODE) musbotg_suspend_host(sc); break; case UHF_PORT_RESET: if (sc->sc_mode == MUSB2_HOST_MODE) { reg = MUSB2_READ_1(sc, MUSB2_REG_POWER); reg |= MUSB2_MASK_RESET; MUSB2_WRITE_1(sc, MUSB2_REG_POWER, reg); /* Wait for 20 msec */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 5); reg = MUSB2_READ_1(sc, MUSB2_REG_POWER); reg &= ~MUSB2_MASK_RESET; MUSB2_WRITE_1(sc, MUSB2_REG_POWER, reg); /* determine line speed */ reg = MUSB2_READ_1(sc, MUSB2_REG_POWER); if (reg & MUSB2_MASK_HSMODE) sc->sc_flags.status_high_speed = 1; else sc->sc_flags.status_high_speed = 0; sc->sc_flags.change_reset = 1; } else err = USB_ERR_IOERROR; break; case UHF_PORT_TEST: case UHF_PORT_INDICATOR: /* nops */ break; case UHF_PORT_POWER: sc->sc_flags.port_powered = 1; break; default: err = USB_ERR_IOERROR; goto done; } goto tr_valid; tr_handle_get_port_status: DPRINTFN(8, "UR_GET_PORT_STATUS\n"); if (index != 1) { goto tr_stalled; } if (sc->sc_flags.status_vbus) { musbotg_clocks_on(sc); musbotg_pull_up(sc); } else { musbotg_pull_down(sc); musbotg_clocks_off(sc); } /* Select Device Side Mode */ if (sc->sc_mode == MUSB2_DEVICE_MODE) value = UPS_PORT_MODE_DEVICE; else value = 0; if (sc->sc_flags.status_high_speed) { value |= UPS_HIGH_SPEED; } if (sc->sc_flags.port_powered) { value |= UPS_PORT_POWER; } if (sc->sc_flags.port_enabled) { value |= UPS_PORT_ENABLED; } if (sc->sc_flags.port_over_current) value |= UPS_OVERCURRENT_INDICATOR; if (sc->sc_flags.status_vbus && sc->sc_flags.status_bus_reset) { value |= UPS_CURRENT_CONNECT_STATUS; } if (sc->sc_flags.status_suspend) { value |= UPS_SUSPEND; } USETW(sc->sc_hub_temp.ps.wPortStatus, value); value = 0; if (sc->sc_flags.change_connect) { value |= UPS_C_CONNECT_STATUS; if (sc->sc_mode == MUSB2_DEVICE_MODE) { if (sc->sc_flags.status_vbus && sc->sc_flags.status_bus_reset) { /* reset EP0 state */ sc->sc_ep0_busy = 0; sc->sc_ep0_cmd = 0; } } } if (sc->sc_flags.change_suspend) value |= UPS_C_SUSPEND; if (sc->sc_flags.change_reset) value |= UPS_C_PORT_RESET; if (sc->sc_flags.change_over_current) value |= UPS_C_OVERCURRENT_INDICATOR; USETW(sc->sc_hub_temp.ps.wPortChange, value); len = sizeof(sc->sc_hub_temp.ps); goto tr_valid; tr_handle_get_class_descriptor: if (value & 0xFF) { goto tr_stalled; } ptr = (const void *)&musbotg_hubd; len = sizeof(musbotg_hubd); goto tr_valid; tr_stalled: err = USB_ERR_STALLED; tr_valid: done: *plength = len; *pptr = ptr; return (err); } static void musbotg_xfer_setup(struct usb_setup_params *parm) { struct musbotg_softc *sc; struct usb_xfer *xfer; void *last_obj; uint32_t ntd; uint32_t n; uint8_t ep_no; sc = MUSBOTG_BUS2SC(parm->udev->bus); xfer = parm->curr_xfer; /* * NOTE: This driver does not use any of the parameters that * are computed from the following values. Just set some * reasonable dummies: */ parm->hc_max_packet_size = 0x400; parm->hc_max_frame_size = 0xc00; if ((parm->methods == &musbotg_device_isoc_methods) || (parm->methods == &musbotg_device_intr_methods)) parm->hc_max_packet_count = 3; else parm->hc_max_packet_count = 1; usbd_transfer_setup_sub(parm); /* * compute maximum number of TDs */ if (parm->methods == &musbotg_device_ctrl_methods) { ntd = xfer->nframes + 1 /* STATUS */ + 1 /* SYNC */ ; } else if (parm->methods == &musbotg_device_bulk_methods) { ntd = xfer->nframes + 1 /* SYNC */ ; } else if (parm->methods == &musbotg_device_intr_methods) { ntd = xfer->nframes + 1 /* SYNC */ ; } else if (parm->methods == &musbotg_device_isoc_methods) { ntd = xfer->nframes + 1 /* SYNC */ ; } else { ntd = 0; } /* * check if "usbd_transfer_setup_sub" set an error */ if (parm->err) { return; } /* * allocate transfer descriptors */ last_obj = NULL; ep_no = xfer->endpointno & UE_ADDR; /* * Check for a valid endpoint profile in USB device mode: */ if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) { const struct usb_hw_ep_profile *pf; musbotg_get_hw_ep_profile(parm->udev, &pf, ep_no); if (pf == NULL) { /* should not happen */ parm->err = USB_ERR_INVAL; return; } } /* align data */ parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1)); for (n = 0; n != ntd; n++) { struct musbotg_td *td; if (parm->buf) { td = USB_ADD_BYTES(parm->buf, parm->size[0]); /* init TD */ td->max_frame_size = xfer->max_frame_size; td->reg_max_packet = xfer->max_packet_size | ((xfer->max_packet_count - 1) << 11); td->ep_no = ep_no; td->obj_next = last_obj; last_obj = td; } parm->size[0] += sizeof(*td); } xfer->td_start[0] = last_obj; } static void musbotg_xfer_unsetup(struct usb_xfer *xfer) { return; } static void musbotg_get_dma_delay(struct usb_device *udev, uint32_t *pus) { struct musbotg_softc *sc = MUSBOTG_BUS2SC(udev->bus); if (sc->sc_mode == MUSB2_HOST_MODE) *pus = 2000; /* microseconds */ else *pus = 0; } static void musbotg_ep_init(struct usb_device *udev, struct usb_endpoint_descriptor *edesc, struct usb_endpoint *ep) { struct musbotg_softc *sc = MUSBOTG_BUS2SC(udev->bus); DPRINTFN(2, "endpoint=%p, addr=%d, endpt=%d, mode=%d (%d)\n", ep, udev->address, edesc->bEndpointAddress, udev->flags.usb_mode, sc->sc_rt_addr); if (udev->device_index != sc->sc_rt_addr) { switch (edesc->bmAttributes & UE_XFERTYPE) { case UE_CONTROL: ep->methods = &musbotg_device_ctrl_methods; break; case UE_INTERRUPT: ep->methods = &musbotg_device_intr_methods; break; case UE_ISOCHRONOUS: ep->methods = &musbotg_device_isoc_methods; break; case UE_BULK: ep->methods = &musbotg_device_bulk_methods; break; default: /* do nothing */ break; } } } static void musbotg_set_hw_power_sleep(struct usb_bus *bus, uint32_t state) { struct musbotg_softc *sc = MUSBOTG_BUS2SC(bus); switch (state) { case USB_HW_POWER_SUSPEND: musbotg_uninit(sc); break; case USB_HW_POWER_SHUTDOWN: musbotg_uninit(sc); break; case USB_HW_POWER_RESUME: musbotg_init(sc); break; default: break; } } static const struct usb_bus_methods musbotg_bus_methods = { .endpoint_init = &musbotg_ep_init, .get_dma_delay = &musbotg_get_dma_delay, .xfer_setup = &musbotg_xfer_setup, .xfer_unsetup = &musbotg_xfer_unsetup, .get_hw_ep_profile = &musbotg_get_hw_ep_profile, .xfer_stall = &musbotg_xfer_stall, .set_stall = &musbotg_set_stall, .clear_stall = &musbotg_clear_stall, .roothub_exec = &musbotg_roothub_exec, .xfer_poll = &musbotg_do_poll, .set_hw_power_sleep = &musbotg_set_hw_power_sleep, }; Index: head/sys/dev/usb/controller/saf1761_otg.c =================================================================== --- head/sys/dev/usb/controller/saf1761_otg.c (revision 276700) +++ head/sys/dev/usb/controller/saf1761_otg.c (revision 276701) @@ -1,3713 +1,3713 @@ /* $FreeBSD$ */ /*- * Copyright (c) 2014 Hans Petter Selasky * All rights reserved. * * This software was developed by SRI International and the University of * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237) * ("CTSRD"), as part of the DARPA CRASH research programme. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * This file contains the driver for the SAF1761 series USB OTG * controller. * * Datasheet is available from: * http://www.nxp.com/products/automotive/multimedia/usb/SAF1761BE.html */ #ifdef USB_GLOBAL_INCLUDE_FILE #include USB_GLOBAL_INCLUDE_FILE #else #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define USB_DEBUG_VAR saf1761_otg_debug #include #include #include #include #include #include #include #include #include #include #endif /* USB_GLOBAL_INCLUDE_FILE */ #include #include #define SAF1761_OTG_BUS2SC(bus) \ ((struct saf1761_otg_softc *)(((uint8_t *)(bus)) - \ ((uint8_t *)&(((struct saf1761_otg_softc *)0)->sc_bus)))) #define SAF1761_OTG_PC2UDEV(pc) \ (USB_DMATAG_TO_XROOT((pc)->tag_parent)->udev) #define SAF1761_DCINTERRUPT_THREAD_IRQ \ (SOTG_DCINTERRUPT_IEVBUS | SOTG_DCINTERRUPT_IEBRST | \ SOTG_DCINTERRUPT_IERESM | SOTG_DCINTERRUPT_IESUSP) #ifdef USB_DEBUG static int saf1761_otg_debug = 0; static int saf1761_otg_forcefs = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, saf1761_otg, CTLFLAG_RW, 0, "USB SAF1761 DCI"); -SYSCTL_INT(_hw_usb_saf1761_otg, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_saf1761_otg, OID_AUTO, debug, CTLFLAG_RWTUN, &saf1761_otg_debug, 0, "SAF1761 DCI debug level"); -SYSCTL_INT(_hw_usb_saf1761_otg, OID_AUTO, forcefs, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_saf1761_otg, OID_AUTO, forcefs, CTLFLAG_RWTUN, &saf1761_otg_forcefs, 0, "SAF1761 DCI force FULL speed"); #endif #define SAF1761_OTG_INTR_ENDPT 1 /* prototypes */ static const struct usb_bus_methods saf1761_otg_bus_methods; static const struct usb_pipe_methods saf1761_otg_non_isoc_methods; static const struct usb_pipe_methods saf1761_otg_device_isoc_methods; static const struct usb_pipe_methods saf1761_otg_host_isoc_methods; static saf1761_otg_cmd_t saf1761_host_setup_tx; static saf1761_otg_cmd_t saf1761_host_bulk_data_rx; static saf1761_otg_cmd_t saf1761_host_bulk_data_tx; static saf1761_otg_cmd_t saf1761_host_intr_data_rx; static saf1761_otg_cmd_t saf1761_host_intr_data_tx; static saf1761_otg_cmd_t saf1761_host_isoc_data_rx; static saf1761_otg_cmd_t saf1761_host_isoc_data_tx; static saf1761_otg_cmd_t saf1761_device_setup_rx; static saf1761_otg_cmd_t saf1761_device_data_rx; static saf1761_otg_cmd_t saf1761_device_data_tx; static saf1761_otg_cmd_t saf1761_device_data_tx_sync; static void saf1761_otg_device_done(struct usb_xfer *, usb_error_t); static void saf1761_otg_do_poll(struct usb_bus *); static void saf1761_otg_standard_done(struct usb_xfer *); static void saf1761_otg_intr_set(struct usb_xfer *, uint8_t); static void saf1761_otg_root_intr(struct saf1761_otg_softc *); static void saf1761_otg_enable_psof(struct saf1761_otg_softc *, uint8_t); /* * Here is a list of what the SAF1761 chip can support. The main * limitation is that the sum of the buffer sizes must be less than * 8192 bytes. */ static const struct usb_hw_ep_profile saf1761_otg_ep_profile[] = { [0] = { .max_in_frame_size = 64, .max_out_frame_size = 64, .is_simplex = 0, .support_control = 1, }, [1] = { .max_in_frame_size = SOTG_HS_MAX_PACKET_SIZE, .max_out_frame_size = SOTG_HS_MAX_PACKET_SIZE, .is_simplex = 0, .support_interrupt = 1, .support_bulk = 1, .support_isochronous = 1, .support_in = 1, .support_out = 1, }, }; static void saf1761_otg_get_hw_ep_profile(struct usb_device *udev, const struct usb_hw_ep_profile **ppf, uint8_t ep_addr) { if (ep_addr == 0) { *ppf = saf1761_otg_ep_profile + 0; } else if (ep_addr < 8) { *ppf = saf1761_otg_ep_profile + 1; } else { *ppf = NULL; } } static void saf1761_otg_pull_up(struct saf1761_otg_softc *sc) { /* activate pullup on D+, if possible */ if (!sc->sc_flags.d_pulled_up && sc->sc_flags.port_powered) { DPRINTF("\n"); sc->sc_flags.d_pulled_up = 1; } } static void saf1761_otg_pull_down(struct saf1761_otg_softc *sc) { /* release pullup on D+, if possible */ if (sc->sc_flags.d_pulled_up) { DPRINTF("\n"); sc->sc_flags.d_pulled_up = 0; } } static void saf1761_otg_wakeup_peer(struct saf1761_otg_softc *sc) { uint16_t temp; if (!(sc->sc_flags.status_suspend)) return; DPRINTFN(5, "\n"); temp = SAF1761_READ_LE_4(sc, SOTG_MODE); SAF1761_WRITE_LE_4(sc, SOTG_MODE, temp | SOTG_MODE_SNDRSU); SAF1761_WRITE_LE_4(sc, SOTG_MODE, temp & ~SOTG_MODE_SNDRSU); /* Wait 8ms for remote wakeup to complete. */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 125); } static uint8_t saf1761_host_channel_alloc(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td) { uint32_t map; int x; if (td->channel < SOTG_HOST_CHANNEL_MAX) return (0); /* check if device is suspended */ if (SAF1761_OTG_PC2UDEV(td->pc)->flags.self_suspended != 0) return (1); /* busy - cannot transfer data */ switch (td->ep_type) { case UE_INTERRUPT: map = ~(sc->sc_host_intr_map | sc->sc_host_intr_busy_map[0] | sc->sc_host_intr_busy_map[1]); /* find first set bit */ x = ffs(map) - 1; if (x < 0 || x > 31) break; sc->sc_host_intr_map |= (1U << x); td->channel = 32 + x; return (0); case UE_ISOCHRONOUS: map = ~(sc->sc_host_isoc_map | sc->sc_host_isoc_busy_map[0] | sc->sc_host_isoc_busy_map[1]); /* find first set bit */ x = ffs(map) - 1; if (x < 0 || x > 31) break; sc->sc_host_isoc_map |= (1U << x); td->channel = x; return (0); default: map = ~(sc->sc_host_async_map | sc->sc_host_async_busy_map[0] | sc->sc_host_async_busy_map[1]); /* find first set bit */ x = ffs(map) - 1; if (x < 0 || x > 31) break; sc->sc_host_async_map |= (1U << x); td->channel = 64 + x; return (0); } return (1); } static void saf1761_host_channel_free(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td) { uint32_t x; if (td->channel >= SOTG_HOST_CHANNEL_MAX) return; switch (td->ep_type) { case UE_INTERRUPT: x = td->channel - 32; td->channel = SOTG_HOST_CHANNEL_MAX; sc->sc_host_intr_map &= ~(1U << x); sc->sc_host_intr_suspend_map &= ~(1U << x); sc->sc_host_intr_busy_map[0] |= (1U << x); SAF1761_WRITE_LE_4(sc, SOTG_INT_PTD_SKIP_PTD, (~sc->sc_host_intr_map) | sc->sc_host_intr_suspend_map); break; case UE_ISOCHRONOUS: x = td->channel; td->channel = SOTG_HOST_CHANNEL_MAX; sc->sc_host_isoc_map &= ~(1U << x); sc->sc_host_isoc_suspend_map &= ~(1U << x); sc->sc_host_isoc_busy_map[0] |= (1U << x); SAF1761_WRITE_LE_4(sc, SOTG_ISO_PTD_SKIP_PTD, (~sc->sc_host_isoc_map) | sc->sc_host_isoc_suspend_map); break; default: x = td->channel - 64; td->channel = SOTG_HOST_CHANNEL_MAX; sc->sc_host_async_map &= ~(1U << x); sc->sc_host_async_suspend_map &= ~(1U << x); sc->sc_host_async_busy_map[0] |= (1U << x); SAF1761_WRITE_LE_4(sc, SOTG_ATL_PTD_SKIP_PTD, (~sc->sc_host_async_map) | sc->sc_host_async_suspend_map); break; } saf1761_otg_enable_psof(sc, 1); } static uint32_t saf1761_peek_host_status_le_4(struct saf1761_otg_softc *sc, uint32_t offset) { uint32_t x = 0; while (1) { uint32_t retval; SAF1761_WRITE_LE_4(sc, SOTG_MEMORY_REG, offset); SAF1761_90NS_DELAY(sc); /* read prefetch time is 90ns */ retval = SAF1761_READ_LE_4(sc, offset); if (retval != 0) return (retval); if (++x == 8) { DPRINTF("STAUS is zero at offset 0x%x\n", offset); break; } } return (0); } static void saf1761_read_host_memory(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td, uint32_t len) { struct usb_page_search buf_res; uint32_t offset; uint32_t count; if (len == 0) return; offset = SOTG_DATA_ADDR(td->channel); SAF1761_WRITE_LE_4(sc, SOTG_MEMORY_REG, offset); SAF1761_90NS_DELAY(sc); /* read prefetch time is 90ns */ /* optimised read first */ while (len > 0) { usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > len) buf_res.length = len; /* check buffer alignment */ if (((uintptr_t)buf_res.buffer) & 3) break; count = buf_res.length & ~3; if (count == 0) break; bus_space_read_region_4((sc)->sc_io_tag, (sc)->sc_io_hdl, offset, buf_res.buffer, count / 4); len -= count; offset += count; /* update remainder and offset */ td->remainder -= count; td->offset += count; } if (len > 0) { /* use bounce buffer */ bus_space_read_region_4((sc)->sc_io_tag, (sc)->sc_io_hdl, offset, sc->sc_bounce_buffer, (len + 3) / 4); usbd_copy_in(td->pc, td->offset, sc->sc_bounce_buffer, len); /* update remainder and offset */ td->remainder -= len; td->offset += len; } } static void saf1761_write_host_memory(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td, uint32_t len) { struct usb_page_search buf_res; uint32_t offset; uint32_t count; if (len == 0) return; offset = SOTG_DATA_ADDR(td->channel); /* optimised write first */ while (len > 0) { usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > len) buf_res.length = len; /* check buffer alignment */ if (((uintptr_t)buf_res.buffer) & 3) break; count = buf_res.length & ~3; if (count == 0) break; bus_space_write_region_4((sc)->sc_io_tag, (sc)->sc_io_hdl, offset, buf_res.buffer, count / 4); len -= count; offset += count; /* update remainder and offset */ td->remainder -= count; td->offset += count; } if (len > 0) { /* use bounce buffer */ usbd_copy_out(td->pc, td->offset, sc->sc_bounce_buffer, len); bus_space_write_region_4((sc)->sc_io_tag, (sc)->sc_io_hdl, offset, sc->sc_bounce_buffer, (len + 3) / 4); /* update remainder and offset */ td->remainder -= len; td->offset += len; } } static uint8_t saf1761_host_setup_tx(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td) { uint32_t pdt_addr; uint32_t status; uint32_t count; uint32_t temp; if (td->channel < SOTG_HOST_CHANNEL_MAX) { pdt_addr = SOTG_PTD(td->channel); status = saf1761_peek_host_status_le_4(sc, pdt_addr + SOTG_PTD_DW3); DPRINTFN(5, "STATUS=0x%08x\n", status); if (status & SOTG_PTD_DW3_ACTIVE) { goto busy; } else if (status & SOTG_PTD_DW3_HALTED) { td->error_any = 1; } goto complete; } if (saf1761_host_channel_alloc(sc, td)) goto busy; count = 8; if (count != td->remainder) { td->error_any = 1; goto complete; } saf1761_write_host_memory(sc, td, count); pdt_addr = SOTG_PTD(td->channel); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW7, 0); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW6, 0); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW5, 0); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW4, 0); temp = SOTG_PTD_DW3_ACTIVE | (td->toggle << 25) | SOTG_PTD_DW3_CERR_3; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW3, temp); temp = SOTG_HC_MEMORY_ADDR(SOTG_DATA_ADDR(td->channel)) << 8; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW2, temp); temp = td->dw1_value | (2 << 10) /* SETUP PID */ | (td->ep_index >> 1); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW1, temp); temp = (td->ep_index << 31) | (1 << 29) /* pkt-multiplier */ | (td->max_packet_size << 18) /* wMaxPacketSize */ | (count << 3) /* transfer count */ | SOTG_PTD_DW0_VALID; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW0, temp); /* activate PTD */ SAF1761_WRITE_LE_4(sc, SOTG_ATL_PTD_SKIP_PTD, (~sc->sc_host_async_map) | sc->sc_host_async_suspend_map); td->toggle = 1; busy: return (1); /* busy */ complete: saf1761_host_channel_free(sc, td); return (0); /* complete */ } static uint8_t saf1761_host_bulk_data_rx(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td) { uint32_t pdt_addr; uint32_t temp; if (td->channel < SOTG_HOST_CHANNEL_MAX) { uint32_t status; uint32_t count; uint8_t got_short; pdt_addr = SOTG_PTD(td->channel); status = saf1761_peek_host_status_le_4(sc, pdt_addr + SOTG_PTD_DW3); DPRINTFN(5, "STATUS=0x%08x\n", status); if (status & SOTG_PTD_DW3_ACTIVE) { goto busy; } else if (status & SOTG_PTD_DW3_HALTED) { if (!(status & SOTG_PTD_DW3_ERRORS)) td->error_stall = 1; td->error_any = 1; goto complete; } if (td->dw1_value & SOTG_PTD_DW1_ENABLE_SPLIT) count = (status & SOTG_PTD_DW3_XFER_COUNT_SPLIT); else count = (status & SOTG_PTD_DW3_XFER_COUNT_HS); got_short = 0; /* verify the packet byte count */ if (count != td->max_packet_size) { if (count < td->max_packet_size) { /* we have a short packet */ td->short_pkt = 1; got_short = 1; } else { /* invalid USB packet */ td->error_any = 1; goto complete; } } td->toggle ^= 1; /* verify the packet byte count */ if (count > td->remainder) { /* invalid USB packet */ td->error_any = 1; goto complete; } saf1761_read_host_memory(sc, td, count); /* check if we are complete */ if ((td->remainder == 0) || got_short) { if (td->short_pkt) goto complete; /* else need to receive a zero length packet */ } saf1761_host_channel_free(sc, td); } if (saf1761_host_channel_alloc(sc, td)) goto busy; /* set toggle, if any */ if (td->set_toggle) { td->set_toggle = 0; td->toggle = 1; } /* receive one more packet */ pdt_addr = SOTG_PTD(td->channel); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW7, 0); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW6, 0); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW5, 0); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW4, 0); temp = SOTG_PTD_DW3_ACTIVE | (td->toggle << 25) | SOTG_PTD_DW3_CERR_2; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW3, temp); temp = (SOTG_HC_MEMORY_ADDR(SOTG_DATA_ADDR(td->channel)) << 8); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW2, temp); temp = td->dw1_value | (1 << 10) /* IN-PID */ | (td->ep_index >> 1); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW1, temp); temp = (td->ep_index << 31) | (1 << 29) /* pkt-multiplier */ | (td->max_packet_size << 18) /* wMaxPacketSize */ | (td->max_packet_size << 3) /* transfer count */ | SOTG_PTD_DW0_VALID; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW0, temp); /* activate PTD */ SAF1761_WRITE_LE_4(sc, SOTG_ATL_PTD_SKIP_PTD, (~sc->sc_host_async_map) | sc->sc_host_async_suspend_map); busy: return (1); /* busy */ complete: saf1761_host_channel_free(sc, td); return (0); /* complete */ } static uint8_t saf1761_host_bulk_data_tx(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td) { uint32_t pdt_addr; uint32_t temp; uint32_t count; if (td->channel < SOTG_HOST_CHANNEL_MAX) { uint32_t status; pdt_addr = SOTG_PTD(td->channel); status = saf1761_peek_host_status_le_4(sc, pdt_addr + SOTG_PTD_DW3); DPRINTFN(5, "STATUS=0x%08x\n", status); if (status & SOTG_PTD_DW3_ACTIVE) { goto busy; } else if (status & SOTG_PTD_DW3_HALTED) { if (!(status & SOTG_PTD_DW3_ERRORS)) td->error_stall = 1; td->error_any = 1; goto complete; } /* check remainder */ if (td->remainder == 0) { if (td->short_pkt) goto complete; /* else we need to transmit a short packet */ } saf1761_host_channel_free(sc, td); } if (saf1761_host_channel_alloc(sc, td)) goto busy; count = td->max_packet_size; if (td->remainder < count) { /* we have a short packet */ td->short_pkt = 1; count = td->remainder; } saf1761_write_host_memory(sc, td, count); /* set toggle, if any */ if (td->set_toggle) { td->set_toggle = 0; td->toggle = 1; } /* send one more packet */ pdt_addr = SOTG_PTD(td->channel); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW7, 0); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW6, 0); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW5, 0); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW4, 0); temp = SOTG_PTD_DW3_ACTIVE | (td->toggle << 25) | SOTG_PTD_DW3_CERR_2; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW3, temp); temp = (SOTG_HC_MEMORY_ADDR(SOTG_DATA_ADDR(td->channel)) << 8); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW2, temp); temp = td->dw1_value | (0 << 10) /* OUT-PID */ | (td->ep_index >> 1); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW1, temp); temp = (td->ep_index << 31) | (1 << 29) /* pkt-multiplier */ | (td->max_packet_size << 18) /* wMaxPacketSize */ | (count << 3) /* transfer count */ | SOTG_PTD_DW0_VALID; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW0, temp); /* activate PTD */ SAF1761_WRITE_LE_4(sc, SOTG_ATL_PTD_SKIP_PTD, (~sc->sc_host_async_map) | sc->sc_host_async_suspend_map); td->toggle ^= 1; busy: return (1); /* busy */ complete: saf1761_host_channel_free(sc, td); return (0); /* complete */ } static uint8_t saf1761_host_intr_data_rx(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td) { uint32_t pdt_addr; uint32_t temp; if (td->channel < SOTG_HOST_CHANNEL_MAX) { uint32_t status; uint32_t count; uint8_t got_short; pdt_addr = SOTG_PTD(td->channel); status = saf1761_peek_host_status_le_4(sc, pdt_addr + SOTG_PTD_DW3); DPRINTFN(5, "STATUS=0x%08x\n", status); if (status & SOTG_PTD_DW3_ACTIVE) { goto busy; } else if (status & SOTG_PTD_DW3_HALTED) { if (!(status & SOTG_PTD_DW3_ERRORS)) td->error_stall = 1; td->error_any = 1; goto complete; } if (td->dw1_value & SOTG_PTD_DW1_ENABLE_SPLIT) count = (status & SOTG_PTD_DW3_XFER_COUNT_SPLIT); else count = (status & SOTG_PTD_DW3_XFER_COUNT_HS); got_short = 0; /* verify the packet byte count */ if (count != td->max_packet_size) { if (count < td->max_packet_size) { /* we have a short packet */ td->short_pkt = 1; got_short = 1; } else { /* invalid USB packet */ td->error_any = 1; goto complete; } } td->toggle ^= 1; /* verify the packet byte count */ if (count > td->remainder) { /* invalid USB packet */ td->error_any = 1; goto complete; } saf1761_read_host_memory(sc, td, count); /* check if we are complete */ if ((td->remainder == 0) || got_short) { if (td->short_pkt) goto complete; /* else need to receive a zero length packet */ } saf1761_host_channel_free(sc, td); } if (saf1761_host_channel_alloc(sc, td)) goto busy; /* set toggle, if any */ if (td->set_toggle) { td->set_toggle = 0; td->toggle = 1; } /* receive one more packet */ pdt_addr = SOTG_PTD(td->channel); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW7, 0); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW6, 0); if (td->dw1_value & SOTG_PTD_DW1_ENABLE_SPLIT) { temp = (0xFC << td->uframe) & 0xFF; /* complete split */ } else { temp = 0; } SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW5, temp); temp = (1U << td->uframe); /* start mask or start split */ SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW4, temp); temp = SOTG_PTD_DW3_ACTIVE | (td->toggle << 25) | SOTG_PTD_DW3_CERR_3; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW3, temp); temp = (SOTG_HC_MEMORY_ADDR(SOTG_DATA_ADDR(td->channel)) << 8) | (td->interval & 0xF8); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW2, temp); temp = td->dw1_value | (1 << 10) /* IN-PID */ | (td->ep_index >> 1); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW1, temp); temp = (td->ep_index << 31) | (1 << 29) /* pkt-multiplier */ | (td->max_packet_size << 18) /* wMaxPacketSize */ | (td->max_packet_size << 3) /* transfer count */ | SOTG_PTD_DW0_VALID; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW0, temp); /* activate PTD */ SAF1761_WRITE_LE_4(sc, SOTG_INT_PTD_SKIP_PTD, (~sc->sc_host_intr_map) | sc->sc_host_intr_suspend_map); busy: return (1); /* busy */ complete: saf1761_host_channel_free(sc, td); return (0); /* complete */ } static uint8_t saf1761_host_intr_data_tx(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td) { uint32_t pdt_addr; uint32_t temp; uint32_t count; if (td->channel < SOTG_HOST_CHANNEL_MAX) { uint32_t status; pdt_addr = SOTG_PTD(td->channel); status = saf1761_peek_host_status_le_4(sc, pdt_addr + SOTG_PTD_DW3); DPRINTFN(5, "STATUS=0x%08x\n", status); if (status & SOTG_PTD_DW3_ACTIVE) { goto busy; } else if (status & SOTG_PTD_DW3_HALTED) { if (!(status & SOTG_PTD_DW3_ERRORS)) td->error_stall = 1; td->error_any = 1; goto complete; } /* check remainder */ if (td->remainder == 0) { if (td->short_pkt) goto complete; /* else we need to transmit a short packet */ } saf1761_host_channel_free(sc, td); } if (saf1761_host_channel_alloc(sc, td)) goto busy; count = td->max_packet_size; if (td->remainder < count) { /* we have a short packet */ td->short_pkt = 1; count = td->remainder; } saf1761_write_host_memory(sc, td, count); /* set toggle, if any */ if (td->set_toggle) { td->set_toggle = 0; td->toggle = 1; } /* send one more packet */ pdt_addr = SOTG_PTD(td->channel); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW7, 0); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW6, 0); if (td->dw1_value & SOTG_PTD_DW1_ENABLE_SPLIT) { temp = (0xFC << td->uframe) & 0xFF; /* complete split */ } else { temp = 0; } SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW5, temp); temp = (1U << td->uframe); /* start mask or start split */ SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW4, temp); temp = SOTG_PTD_DW3_ACTIVE | (td->toggle << 25) | SOTG_PTD_DW3_CERR_3; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW3, temp); temp = (SOTG_HC_MEMORY_ADDR(SOTG_DATA_ADDR(td->channel)) << 8) | (td->interval & 0xF8); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW2, temp); temp = td->dw1_value | (0 << 10) /* OUT-PID */ | (td->ep_index >> 1); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW1, temp); temp = (td->ep_index << 31) | (1 << 29) /* pkt-multiplier */ | (td->max_packet_size << 18) /* wMaxPacketSize */ | (count << 3) /* transfer count */ | SOTG_PTD_DW0_VALID; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW0, temp); /* activate PTD */ SAF1761_WRITE_LE_4(sc, SOTG_INT_PTD_SKIP_PTD, (~sc->sc_host_intr_map) | sc->sc_host_intr_suspend_map); td->toggle ^= 1; busy: return (1); /* busy */ complete: saf1761_host_channel_free(sc, td); return (0); /* complete */ } static uint8_t saf1761_host_isoc_data_rx(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td) { uint32_t pdt_addr; uint32_t temp; if (td->channel < SOTG_HOST_CHANNEL_MAX) { uint32_t status; uint32_t count; pdt_addr = SOTG_PTD(td->channel); status = saf1761_peek_host_status_le_4(sc, pdt_addr + SOTG_PTD_DW3); DPRINTFN(5, "STATUS=0x%08x\n", status); if (status & SOTG_PTD_DW3_ACTIVE) { goto busy; } else if (status & SOTG_PTD_DW3_HALTED) { goto complete; } if (td->dw1_value & SOTG_PTD_DW1_ENABLE_SPLIT) count = (status & SOTG_PTD_DW3_XFER_COUNT_SPLIT); else count = (status & SOTG_PTD_DW3_XFER_COUNT_HS); /* verify the packet byte count */ if (count != td->max_packet_size) { if (count < td->max_packet_size) { /* we have a short packet */ td->short_pkt = 1; } else { /* invalid USB packet */ td->error_any = 1; goto complete; } } /* verify the packet byte count */ if (count > td->remainder) { /* invalid USB packet */ td->error_any = 1; goto complete; } saf1761_read_host_memory(sc, td, count); goto complete; } if (saf1761_host_channel_alloc(sc, td)) goto busy; /* receive one more packet */ pdt_addr = SOTG_PTD(td->channel); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW7, 0); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW6, 0); if (td->dw1_value & SOTG_PTD_DW1_ENABLE_SPLIT) { temp = (0xFC << (td->uframe & 7)) & 0xFF; /* complete split */ } else { temp = 0; } SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW5, temp); temp = (1U << (td->uframe & 7)); /* start mask or start split */ SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW4, temp); temp = SOTG_PTD_DW3_ACTIVE | SOTG_PTD_DW3_CERR_3; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW3, temp); temp = (SOTG_HC_MEMORY_ADDR(SOTG_DATA_ADDR(td->channel)) << 8) | (td->uframe & 0xF8); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW2, temp); temp = td->dw1_value | (1 << 10) /* IN-PID */ | (td->ep_index >> 1); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW1, temp); temp = (td->ep_index << 31) | (1 << 29) /* pkt-multiplier */ | (td->max_packet_size << 18) /* wMaxPacketSize */ | (td->max_packet_size << 3) /* transfer count */ | SOTG_PTD_DW0_VALID; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW0, temp); /* activate PTD */ SAF1761_WRITE_LE_4(sc, SOTG_ISO_PTD_SKIP_PTD, (~sc->sc_host_isoc_map) | sc->sc_host_isoc_suspend_map); busy: return (1); /* busy */ complete: saf1761_host_channel_free(sc, td); return (0); /* complete */ } static uint8_t saf1761_host_isoc_data_tx(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td) { uint32_t pdt_addr; uint32_t temp; uint32_t count; if (td->channel < SOTG_HOST_CHANNEL_MAX) { uint32_t status; pdt_addr = SOTG_PTD(td->channel); status = saf1761_peek_host_status_le_4(sc, pdt_addr + SOTG_PTD_DW3); DPRINTFN(5, "STATUS=0x%08x\n", status); if (status & SOTG_PTD_DW3_ACTIVE) { goto busy; } else if (status & SOTG_PTD_DW3_HALTED) { goto complete; } goto complete; } if (saf1761_host_channel_alloc(sc, td)) goto busy; count = td->max_packet_size; if (td->remainder < count) { /* we have a short packet */ td->short_pkt = 1; count = td->remainder; } saf1761_write_host_memory(sc, td, count); /* send one more packet */ pdt_addr = SOTG_PTD(td->channel); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW7, 0); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW6, 0); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW5, 0); temp = (1U << (td->uframe & 7)); /* start mask or start split */ SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW4, temp); temp = SOTG_PTD_DW3_ACTIVE | SOTG_PTD_DW3_CERR_3; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW3, temp); temp = (SOTG_HC_MEMORY_ADDR(SOTG_DATA_ADDR(td->channel)) << 8) | (td->uframe & 0xF8); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW2, temp); temp = td->dw1_value | (0 << 10) /* OUT-PID */ | (td->ep_index >> 1); SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW1, temp); temp = (td->ep_index << 31) | (1 << 29) /* pkt-multiplier */ | (count << 18) /* wMaxPacketSize */ | (count << 3) /* transfer count */ | SOTG_PTD_DW0_VALID; SAF1761_WRITE_LE_4(sc, pdt_addr + SOTG_PTD_DW0, temp); /* activate PTD */ SAF1761_WRITE_LE_4(sc, SOTG_ISO_PTD_SKIP_PTD, (~sc->sc_host_isoc_map) | sc->sc_host_isoc_suspend_map); busy: return (1); /* busy */ complete: saf1761_host_channel_free(sc, td); return (0); /* complete */ } static void saf1761_otg_set_address(struct saf1761_otg_softc *sc, uint8_t addr) { DPRINTFN(5, "addr=%d\n", addr); SAF1761_WRITE_LE_4(sc, SOTG_ADDRESS, addr | SOTG_ADDRESS_ENABLE); } static void saf1761_read_device_fifo(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td, uint32_t len) { struct usb_page_search buf_res; uint32_t count; /* optimised read first */ while (len > 0) { usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > len) buf_res.length = len; /* check buffer alignment */ if (((uintptr_t)buf_res.buffer) & 3) break; count = buf_res.length & ~3; if (count == 0) break; bus_space_read_multi_4((sc)->sc_io_tag, (sc)->sc_io_hdl, SOTG_DATA_PORT, buf_res.buffer, count / 4); len -= count; /* update remainder and offset */ td->remainder -= count; td->offset += count; } if (len > 0) { /* use bounce buffer */ bus_space_read_multi_4((sc)->sc_io_tag, (sc)->sc_io_hdl, SOTG_DATA_PORT, sc->sc_bounce_buffer, (len + 3) / 4); usbd_copy_in(td->pc, td->offset, sc->sc_bounce_buffer, len); /* update remainder and offset */ td->remainder -= len; td->offset += len; } } static void saf1761_write_device_fifo(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td, uint32_t len) { struct usb_page_search buf_res; uint32_t count; /* optimised write first */ while (len > 0) { usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > len) buf_res.length = len; /* check buffer alignment */ if (((uintptr_t)buf_res.buffer) & 3) break; count = buf_res.length & ~3; if (count == 0) break; bus_space_write_multi_4((sc)->sc_io_tag, (sc)->sc_io_hdl, SOTG_DATA_PORT, buf_res.buffer, count / 4); len -= count; /* update remainder and offset */ td->remainder -= count; td->offset += count; } if (len > 0) { /* use bounce buffer */ usbd_copy_out(td->pc, td->offset, sc->sc_bounce_buffer, len); bus_space_write_multi_4((sc)->sc_io_tag, (sc)->sc_io_hdl, SOTG_DATA_PORT, sc->sc_bounce_buffer, (len + 3) / 4); /* update remainder and offset */ td->remainder -= len; td->offset += len; } } static uint8_t saf1761_device_setup_rx(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td) { struct usb_device_request req; uint32_t count; /* select the correct endpoint */ SAF1761_WRITE_LE_4(sc, SOTG_EP_INDEX, SOTG_EP_INDEX_EP0SETUP); count = SAF1761_READ_LE_4(sc, SOTG_BUF_LENGTH); /* check buffer status */ if ((count & SOTG_BUF_LENGTH_FILLED_MASK) == 0) goto busy; /* get buffer length */ count &= SOTG_BUF_LENGTH_BUFLEN_MASK; DPRINTFN(5, "count=%u rem=%u\n", count, td->remainder); /* clear did stall */ td->did_stall = 0; /* clear stall */ SAF1761_WRITE_LE_4(sc, SOTG_CTRL_FUNC, 0); /* verify data length */ if (count != td->remainder) { DPRINTFN(0, "Invalid SETUP packet " "length, %d bytes\n", count); goto busy; } if (count != sizeof(req)) { DPRINTFN(0, "Unsupported SETUP packet " "length, %d bytes\n", count); goto busy; } /* receive data */ saf1761_read_device_fifo(sc, td, sizeof(req)); /* extract SETUP packet again */ usbd_copy_out(td->pc, 0, &req, sizeof(req)); /* sneak peek the set address request */ if ((req.bmRequestType == UT_WRITE_DEVICE) && (req.bRequest == UR_SET_ADDRESS)) { sc->sc_dv_addr = req.wValue[0] & 0x7F; DPRINTF("Set address %d\n", sc->sc_dv_addr); } else { sc->sc_dv_addr = 0xFF; } return (0); /* complete */ busy: /* abort any ongoing transfer */ if (!td->did_stall) { DPRINTFN(5, "stalling\n"); /* set stall */ SAF1761_WRITE_LE_4(sc, SOTG_CTRL_FUNC, SOTG_CTRL_FUNC_STALL); td->did_stall = 1; } return (1); /* not complete */ } static uint8_t saf1761_device_data_rx(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td) { uint32_t count; uint8_t got_short = 0; if (td->ep_index == 0) { /* select the correct endpoint */ SAF1761_WRITE_LE_4(sc, SOTG_EP_INDEX, SOTG_EP_INDEX_EP0SETUP); count = SAF1761_READ_LE_4(sc, SOTG_BUF_LENGTH); /* check buffer status */ if ((count & SOTG_BUF_LENGTH_FILLED_MASK) != 0) { if (td->remainder == 0) { /* * We are actually complete and have * received the next SETUP: */ DPRINTFN(5, "faking complete\n"); return (0); /* complete */ } DPRINTFN(5, "SETUP packet while receiving data\n"); /* * USB Host Aborted the transfer. */ td->error_any = 1; return (0); /* complete */ } } /* select the correct endpoint */ SAF1761_WRITE_LE_4(sc, SOTG_EP_INDEX, (td->ep_index << SOTG_EP_INDEX_ENDP_INDEX_SHIFT) | SOTG_EP_INDEX_DIR_OUT); /* enable data stage */ if (td->set_toggle) { td->set_toggle = 0; SAF1761_WRITE_LE_4(sc, SOTG_CTRL_FUNC, SOTG_CTRL_FUNC_DSEN); } count = SAF1761_READ_LE_4(sc, SOTG_BUF_LENGTH); /* check buffer status */ if ((count & SOTG_BUF_LENGTH_FILLED_MASK) == 0) return (1); /* not complete */ /* get buffer length */ count &= SOTG_BUF_LENGTH_BUFLEN_MASK; DPRINTFN(5, "rem=%u count=0x%04x\n", td->remainder, count); /* verify the packet byte count */ if (count != td->max_packet_size) { if (count < td->max_packet_size) { /* we have a short packet */ td->short_pkt = 1; got_short = 1; } else { /* invalid USB packet */ td->error_any = 1; return (0); /* we are complete */ } } /* verify the packet byte count */ if (count > td->remainder) { /* invalid USB packet */ td->error_any = 1; return (0); /* we are complete */ } /* receive data */ saf1761_read_device_fifo(sc, td, count); /* check if we are complete */ if ((td->remainder == 0) || got_short) { if (td->short_pkt) { /* we are complete */ return (0); } /* else need to receive a zero length packet */ } return (1); /* not complete */ } static uint8_t saf1761_device_data_tx(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td) { uint32_t count; if (td->ep_index == 0) { /* select the correct endpoint */ SAF1761_WRITE_LE_4(sc, SOTG_EP_INDEX, SOTG_EP_INDEX_EP0SETUP); count = SAF1761_READ_LE_4(sc, SOTG_BUF_LENGTH); /* check buffer status */ if ((count & SOTG_BUF_LENGTH_FILLED_MASK) != 0) { DPRINTFN(5, "SETUP abort\n"); /* * USB Host Aborted the transfer. */ td->error_any = 1; return (0); /* complete */ } } /* select the correct endpoint */ SAF1761_WRITE_LE_4(sc, SOTG_EP_INDEX, (td->ep_index << SOTG_EP_INDEX_ENDP_INDEX_SHIFT) | SOTG_EP_INDEX_DIR_IN); count = SAF1761_READ_LE_4(sc, SOTG_BUF_LENGTH); /* check buffer status */ if ((count & SOTG_BUF_LENGTH_FILLED_MASK) != 0) return (1); /* not complete */ /* enable data stage */ if (td->set_toggle) { td->set_toggle = 0; SAF1761_WRITE_LE_4(sc, SOTG_CTRL_FUNC, SOTG_CTRL_FUNC_DSEN); } DPRINTFN(5, "rem=%u\n", td->remainder); count = td->max_packet_size; if (td->remainder < count) { /* we have a short packet */ td->short_pkt = 1; count = td->remainder; } /* transmit data */ saf1761_write_device_fifo(sc, td, count); if (td->ep_index == 0) { if (count < SOTG_FS_MAX_PACKET_SIZE) { /* set end of packet */ SAF1761_WRITE_LE_4(sc, SOTG_CTRL_FUNC, SOTG_CTRL_FUNC_VENDP); } } else { if (count < SOTG_HS_MAX_PACKET_SIZE) { /* set end of packet */ SAF1761_WRITE_LE_4(sc, SOTG_CTRL_FUNC, SOTG_CTRL_FUNC_VENDP); } } /* check remainder */ if (td->remainder == 0) { if (td->short_pkt) { return (0); /* complete */ } /* else we need to transmit a short packet */ } return (1); /* not complete */ } static uint8_t saf1761_device_data_tx_sync(struct saf1761_otg_softc *sc, struct saf1761_otg_td *td) { uint32_t count; if (td->ep_index == 0) { /* select the correct endpoint */ SAF1761_WRITE_LE_4(sc, SOTG_EP_INDEX, SOTG_EP_INDEX_EP0SETUP); count = SAF1761_READ_LE_4(sc, SOTG_BUF_LENGTH); /* check buffer status */ if ((count & SOTG_BUF_LENGTH_FILLED_MASK) != 0) { DPRINTFN(5, "Faking complete\n"); return (0); /* complete */ } } /* select the correct endpoint */ SAF1761_WRITE_LE_4(sc, SOTG_EP_INDEX, (td->ep_index << SOTG_EP_INDEX_ENDP_INDEX_SHIFT) | SOTG_EP_INDEX_DIR_IN); count = SAF1761_READ_LE_4(sc, SOTG_BUF_LENGTH); /* check buffer status */ if ((count & SOTG_BUF_LENGTH_FILLED_MASK) != 0) return (1); /* busy */ if (sc->sc_dv_addr != 0xFF) { /* write function address */ saf1761_otg_set_address(sc, sc->sc_dv_addr); } return (0); /* complete */ } static void saf1761_otg_xfer_do_fifo(struct saf1761_otg_softc *sc, struct usb_xfer *xfer) { struct saf1761_otg_td *td; uint8_t toggle; DPRINTFN(9, "\n"); td = xfer->td_transfer_cache; if (td == NULL) return; while (1) { if ((td->func) (sc, td)) { /* operation in progress */ break; } if (((void *)td) == xfer->td_transfer_last) { goto done; } if (td->error_any) { goto done; } else if (td->remainder > 0) { /* * We had a short transfer. If there is no alternate * next, stop processing ! */ if (!td->alt_next) { goto done; } } /* * Fetch the next transfer descriptor. */ toggle = td->toggle; td = td->obj_next; td->toggle = toggle; xfer->td_transfer_cache = td; } return; done: /* compute all actual lengths */ xfer->td_transfer_cache = NULL; sc->sc_xfer_complete = 1; } static uint8_t saf1761_otg_xfer_do_complete(struct saf1761_otg_softc *sc, struct usb_xfer *xfer) { struct saf1761_otg_td *td; DPRINTFN(9, "\n"); td = xfer->td_transfer_cache; if (td == NULL) { /* compute all actual lengths */ saf1761_otg_standard_done(xfer); return (1); } return (0); } static void saf1761_otg_interrupt_poll_locked(struct saf1761_otg_softc *sc) { struct usb_xfer *xfer; TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) saf1761_otg_xfer_do_fifo(sc, xfer); } static void saf1761_otg_enable_psof(struct saf1761_otg_softc *sc, uint8_t on) { if (on) { sc->sc_intr_enable |= SOTG_DCINTERRUPT_IEPSOF; } else { sc->sc_intr_enable &= ~SOTG_DCINTERRUPT_IEPSOF; } SAF1761_WRITE_LE_4(sc, SOTG_DCINTERRUPT_EN, sc->sc_intr_enable); } static void saf1761_otg_wait_suspend(struct saf1761_otg_softc *sc, uint8_t on) { if (on) { sc->sc_intr_enable |= SOTG_DCINTERRUPT_IESUSP; sc->sc_intr_enable &= ~SOTG_DCINTERRUPT_IERESM; } else { sc->sc_intr_enable &= ~SOTG_DCINTERRUPT_IESUSP; sc->sc_intr_enable |= SOTG_DCINTERRUPT_IERESM; } SAF1761_WRITE_LE_4(sc, SOTG_DCINTERRUPT_EN, sc->sc_intr_enable); } static void saf1761_otg_update_vbus(struct saf1761_otg_softc *sc) { uint16_t status; /* read fresh status */ status = SAF1761_READ_LE_4(sc, SOTG_STATUS); DPRINTFN(4, "STATUS=0x%04x\n", status); if ((status & SOTG_STATUS_VBUS_VLD) && (status & SOTG_STATUS_ID)) { /* VBUS present and device mode */ if (!sc->sc_flags.status_vbus) { sc->sc_flags.status_vbus = 1; /* complete root HUB interrupt endpoint */ saf1761_otg_root_intr(sc); } } else { /* VBUS not-present or host mode */ if (sc->sc_flags.status_vbus) { sc->sc_flags.status_vbus = 0; sc->sc_flags.status_bus_reset = 0; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; /* complete root HUB interrupt endpoint */ saf1761_otg_root_intr(sc); } } } static void saf1761_otg_interrupt_complete_locked(struct saf1761_otg_softc *sc) { struct usb_xfer *xfer; repeat: /* scan for completion events */ TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) { if (saf1761_otg_xfer_do_complete(sc, xfer)) goto repeat; } } int saf1761_otg_filter_interrupt(void *arg) { struct saf1761_otg_softc *sc = arg; int retval = FILTER_HANDLED; uint32_t hcstat; uint32_t status; USB_BUS_SPIN_LOCK(&sc->sc_bus); hcstat = SAF1761_READ_LE_4(sc, SOTG_HCINTERRUPT); /* acknowledge all host controller interrupts */ SAF1761_WRITE_LE_4(sc, SOTG_HCINTERRUPT, hcstat); status = SAF1761_READ_LE_4(sc, SOTG_DCINTERRUPT); /* acknowledge all device controller interrupts */ SAF1761_WRITE_LE_4(sc, SOTG_DCINTERRUPT, status & ~SAF1761_DCINTERRUPT_THREAD_IRQ); (void) SAF1761_READ_LE_4(sc, SOTG_ATL_PTD_DONE_PTD); (void) SAF1761_READ_LE_4(sc, SOTG_INT_PTD_DONE_PTD); (void) SAF1761_READ_LE_4(sc, SOTG_ISO_PTD_DONE_PTD); if (status & SOTG_DCINTERRUPT_IEPSOF) { if ((sc->sc_host_async_busy_map[1] | sc->sc_host_async_busy_map[0] | sc->sc_host_intr_busy_map[1] | sc->sc_host_intr_busy_map[0] | sc->sc_host_isoc_busy_map[1] | sc->sc_host_isoc_busy_map[0]) != 0) { /* busy waiting is active */ retval = FILTER_SCHEDULE_THREAD; sc->sc_host_async_busy_map[1] = sc->sc_host_async_busy_map[0]; sc->sc_host_async_busy_map[0] = 0; sc->sc_host_intr_busy_map[1] = sc->sc_host_intr_busy_map[0]; sc->sc_host_intr_busy_map[0] = 0; sc->sc_host_isoc_busy_map[1] = sc->sc_host_isoc_busy_map[0]; sc->sc_host_isoc_busy_map[0] = 0; } else { /* busy waiting is not active */ saf1761_otg_enable_psof(sc, 0); } } if (status & SAF1761_DCINTERRUPT_THREAD_IRQ) retval = FILTER_SCHEDULE_THREAD; /* poll FIFOs, if any */ saf1761_otg_interrupt_poll_locked(sc); if (sc->sc_xfer_complete != 0) retval = FILTER_SCHEDULE_THREAD; USB_BUS_SPIN_UNLOCK(&sc->sc_bus); return (retval); } void saf1761_otg_interrupt(void *arg) { struct saf1761_otg_softc *sc = arg; uint32_t status; USB_BUS_LOCK(&sc->sc_bus); USB_BUS_SPIN_LOCK(&sc->sc_bus); status = SAF1761_READ_LE_4(sc, SOTG_DCINTERRUPT) & SAF1761_DCINTERRUPT_THREAD_IRQ; /* acknowledge all device controller interrupts */ SAF1761_WRITE_LE_4(sc, SOTG_DCINTERRUPT, status); DPRINTF("DCINTERRUPT=0x%08x SOF=0x%08x " "FRINDEX=0x%08x\n", status, SAF1761_READ_LE_4(sc, SOTG_FRAME_NUM), SAF1761_READ_LE_4(sc, SOTG_FRINDEX)); /* update VBUS and ID bits, if any */ if (status & SOTG_DCINTERRUPT_IEVBUS) saf1761_otg_update_vbus(sc); if (status & SOTG_DCINTERRUPT_IEBRST) { /* unlock device */ SAF1761_WRITE_LE_4(sc, SOTG_UNLOCK_DEVICE, SOTG_UNLOCK_DEVICE_CODE); /* Enable device address */ SAF1761_WRITE_LE_4(sc, SOTG_ADDRESS, SOTG_ADDRESS_ENABLE); sc->sc_flags.status_bus_reset = 1; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; /* disable resume interrupt */ saf1761_otg_wait_suspend(sc, 1); /* complete root HUB interrupt endpoint */ saf1761_otg_root_intr(sc); } /* * If "RESUME" and "SUSPEND" is set at the same time we * interpret that like "RESUME". Resume is set when there is * at least 3 milliseconds of inactivity on the USB BUS: */ if (status & SOTG_DCINTERRUPT_IERESM) { /* unlock device */ SAF1761_WRITE_LE_4(sc, SOTG_UNLOCK_DEVICE, SOTG_UNLOCK_DEVICE_CODE); if (sc->sc_flags.status_suspend) { sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 1; /* disable resume interrupt */ saf1761_otg_wait_suspend(sc, 1); /* complete root HUB interrupt endpoint */ saf1761_otg_root_intr(sc); } } else if (status & SOTG_DCINTERRUPT_IESUSP) { if (!sc->sc_flags.status_suspend) { sc->sc_flags.status_suspend = 1; sc->sc_flags.change_suspend = 1; /* enable resume interrupt */ saf1761_otg_wait_suspend(sc, 0); /* complete root HUB interrupt endpoint */ saf1761_otg_root_intr(sc); } } if (sc->sc_xfer_complete != 0) { sc->sc_xfer_complete = 0; /* complete FIFOs, if any */ saf1761_otg_interrupt_complete_locked(sc); } USB_BUS_SPIN_UNLOCK(&sc->sc_bus); USB_BUS_UNLOCK(&sc->sc_bus); } static void saf1761_otg_setup_standard_chain_sub(struct saf1761_otg_std_temp *temp) { struct saf1761_otg_td *td; /* get current Transfer Descriptor */ td = temp->td_next; temp->td = td; /* prepare for next TD */ temp->td_next = td->obj_next; /* fill out the Transfer Descriptor */ td->func = temp->func; td->pc = temp->pc; td->offset = temp->offset; td->remainder = temp->len; td->error_any = 0; td->error_stall = 0; td->set_toggle = 0; td->did_stall = temp->did_stall; td->short_pkt = temp->short_pkt; td->alt_next = temp->setup_alt_next; td->channel = SOTG_HOST_CHANNEL_MAX; } static void saf1761_otg_setup_standard_chain(struct usb_xfer *xfer) { struct saf1761_otg_std_temp temp; struct saf1761_otg_softc *sc; struct saf1761_otg_td *td; uint32_t x; uint8_t ep_no; uint8_t ep_type; uint8_t need_sync; uint8_t is_host; uint8_t uframe_start; uint8_t uframe_interval; DPRINTFN(9, "addr=%d endpt=%d sumlen=%d speed=%d\n", xfer->address, UE_GET_ADDR(xfer->endpointno), xfer->sumlen, usbd_get_speed(xfer->xroot->udev)); temp.max_frame_size = xfer->max_frame_size; td = xfer->td_start[0]; xfer->td_transfer_first = td; xfer->td_transfer_cache = td; /* setup temp */ temp.pc = NULL; temp.td = NULL; temp.td_next = xfer->td_start[0]; temp.offset = 0; temp.setup_alt_next = xfer->flags_int.short_frames_ok || xfer->flags_int.isochronous_xfr; temp.did_stall = !xfer->flags_int.control_stall; is_host = (xfer->xroot->udev->flags.usb_mode == USB_MODE_HOST); sc = SAF1761_OTG_BUS2SC(xfer->xroot->bus); ep_no = (xfer->endpointno & UE_ADDR); ep_type = (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE); /* check if we should prepend a setup message */ if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_hdr) { if (is_host) temp.func = &saf1761_host_setup_tx; else temp.func = &saf1761_device_setup_rx; temp.len = xfer->frlengths[0]; temp.pc = xfer->frbuffers + 0; temp.short_pkt = temp.len ? 1 : 0; /* check for last frame */ if (xfer->nframes == 1) { /* no STATUS stage yet, SETUP is last */ if (xfer->flags_int.control_act) temp.setup_alt_next = 0; } saf1761_otg_setup_standard_chain_sub(&temp); } x = 1; } else { x = 0; } uframe_start = 0; uframe_interval = 0; if (x != xfer->nframes) { if (xfer->endpointno & UE_DIR_IN) { if (is_host) { if (ep_type == UE_INTERRUPT) { temp.func = &saf1761_host_intr_data_rx; } else if (ep_type == UE_ISOCHRONOUS) { temp.func = &saf1761_host_isoc_data_rx; uframe_start = (SAF1761_READ_LE_4(sc, SOTG_FRINDEX) + 8) & (SOTG_FRINDEX_MASK & ~7); if (xfer->xroot->udev->speed == USB_SPEED_HIGH) uframe_interval = 1U << xfer->fps_shift; else uframe_interval = 8U; } else { temp.func = &saf1761_host_bulk_data_rx; } need_sync = 0; } else { temp.func = &saf1761_device_data_tx; need_sync = 1; } } else { if (is_host) { if (ep_type == UE_INTERRUPT) { temp.func = &saf1761_host_intr_data_tx; } else if (ep_type == UE_ISOCHRONOUS) { temp.func = &saf1761_host_isoc_data_tx; uframe_start = (SAF1761_READ_LE_4(sc, SOTG_FRINDEX) + 8) & (SOTG_FRINDEX_MASK & ~7); if (xfer->xroot->udev->speed == USB_SPEED_HIGH) uframe_interval = 1U << xfer->fps_shift; else uframe_interval = 8U; } else { temp.func = &saf1761_host_bulk_data_tx; } need_sync = 0; } else { temp.func = &saf1761_device_data_rx; need_sync = 0; } } /* setup "pc" pointer */ temp.pc = xfer->frbuffers + x; } else { need_sync = 0; } while (x != xfer->nframes) { /* DATA0 / DATA1 message */ temp.len = xfer->frlengths[x]; x++; if (x == xfer->nframes) { if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_act) { temp.setup_alt_next = 0; } } else { temp.setup_alt_next = 0; } } if (temp.len == 0) { /* make sure that we send an USB packet */ temp.short_pkt = 0; } else { /* regular data transfer */ temp.short_pkt = (xfer->flags.force_short_xfer) ? 0 : 1; } saf1761_otg_setup_standard_chain_sub(&temp); if (xfer->flags_int.isochronous_xfr) { temp.offset += temp.len; /* stamp the starting point for this transaction */ temp.td->uframe = uframe_start; /* advance to next */ uframe_start += uframe_interval; } else { /* get next Page Cache pointer */ temp.pc = xfer->frbuffers + x; } } /* check for control transfer */ if (xfer->flags_int.control_xfr) { /* always setup a valid "pc" pointer for status and sync */ temp.pc = xfer->frbuffers + 0; temp.len = 0; temp.short_pkt = 0; temp.setup_alt_next = 0; /* check if we should append a status stage */ if (!xfer->flags_int.control_act) { /* * Send a DATA1 message and invert the current * endpoint direction. */ if (xfer->endpointno & UE_DIR_IN) { if (is_host) { temp.func = &saf1761_host_bulk_data_tx; need_sync = 0; } else { temp.func = &saf1761_device_data_rx; need_sync = 0; } } else { if (is_host) { temp.func = &saf1761_host_bulk_data_rx; need_sync = 0; } else { temp.func = &saf1761_device_data_tx; need_sync = 1; } } temp.len = 0; temp.short_pkt = 0; saf1761_otg_setup_standard_chain_sub(&temp); /* data toggle should be DATA1 */ td = temp.td; td->set_toggle = 1; if (need_sync) { /* we need a SYNC point after TX */ temp.func = &saf1761_device_data_tx_sync; saf1761_otg_setup_standard_chain_sub(&temp); } } } else { if (need_sync) { temp.pc = xfer->frbuffers + 0; temp.len = 0; temp.short_pkt = 0; temp.setup_alt_next = 0; /* we need a SYNC point after TX */ temp.func = &saf1761_device_data_tx_sync; saf1761_otg_setup_standard_chain_sub(&temp); } } /* must have at least one frame! */ td = temp.td; xfer->td_transfer_last = td; if (is_host) { /* get first again */ td = xfer->td_transfer_first; td->toggle = (xfer->endpoint->toggle_next ? 1 : 0); } } static void saf1761_otg_timeout(void *arg) { struct usb_xfer *xfer = arg; DPRINTF("xfer=%p\n", xfer); USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED); /* transfer is transferred */ saf1761_otg_device_done(xfer, USB_ERR_TIMEOUT); } static void saf1761_otg_intr_set(struct usb_xfer *xfer, uint8_t set) { struct saf1761_otg_softc *sc = SAF1761_OTG_BUS2SC(xfer->xroot->bus); uint8_t ep_no = (xfer->endpointno & UE_ADDR); uint32_t mask; DPRINTFN(15, "endpoint=%d set=%d\n", xfer->endpointno, set); if (ep_no == 0) { mask = SOTG_DCINTERRUPT_IEPRX(0) | SOTG_DCINTERRUPT_IEPTX(0) | SOTG_DCINTERRUPT_IEP0SETUP; } else if (xfer->endpointno & UE_DIR_IN) { mask = SOTG_DCINTERRUPT_IEPTX(ep_no); } else { mask = SOTG_DCINTERRUPT_IEPRX(ep_no); } if (set) sc->sc_intr_enable |= mask; else sc->sc_intr_enable &= ~mask; SAF1761_WRITE_LE_4(sc, SOTG_DCINTERRUPT_EN, sc->sc_intr_enable); } static void saf1761_otg_start_standard_chain(struct usb_xfer *xfer) { struct saf1761_otg_softc *sc = SAF1761_OTG_BUS2SC(xfer->xroot->bus); DPRINTFN(9, "\n"); USB_BUS_SPIN_LOCK(&sc->sc_bus); /* poll one time */ saf1761_otg_xfer_do_fifo(sc, xfer); if (saf1761_otg_xfer_do_complete(sc, xfer) == 0) { /* * Only enable the endpoint interrupt when we are * actually waiting for data, hence we are dealing * with level triggered interrupts ! */ saf1761_otg_intr_set(xfer, 1); /* put transfer on interrupt queue */ usbd_transfer_enqueue(&xfer->xroot->bus->intr_q, xfer); /* start timeout, if any */ if (xfer->timeout != 0) { usbd_transfer_timeout_ms(xfer, &saf1761_otg_timeout, xfer->timeout); } } USB_BUS_SPIN_UNLOCK(&sc->sc_bus); } static void saf1761_otg_root_intr(struct saf1761_otg_softc *sc) { DPRINTFN(9, "\n"); USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); /* set port bit - we only have one port */ sc->sc_hub_idata[0] = 0x02; uhub_root_intr(&sc->sc_bus, sc->sc_hub_idata, sizeof(sc->sc_hub_idata)); } static usb_error_t saf1761_otg_standard_done_sub(struct usb_xfer *xfer) { struct saf1761_otg_td *td; uint32_t len; usb_error_t error; DPRINTFN(9, "\n"); td = xfer->td_transfer_cache; do { len = td->remainder; /* store last data toggle */ xfer->endpoint->toggle_next = td->toggle; if (xfer->aframes != xfer->nframes) { /* * Verify the length and subtract * the remainder from "frlengths[]": */ if (len > xfer->frlengths[xfer->aframes]) { td->error_any = 1; } else { xfer->frlengths[xfer->aframes] -= len; } } /* Check for transfer error */ if (td->error_any) { /* the transfer is finished */ error = (td->error_stall ? USB_ERR_STALLED : USB_ERR_IOERROR); td = NULL; break; } /* Check for short transfer */ if (len > 0) { if (xfer->flags_int.short_frames_ok || xfer->flags_int.isochronous_xfr) { /* follow alt next */ if (td->alt_next) { td = td->obj_next; } else { td = NULL; } } else { /* the transfer is finished */ td = NULL; } error = 0; break; } td = td->obj_next; /* this USB frame is complete */ error = 0; break; } while (0); /* update transfer cache */ xfer->td_transfer_cache = td; return (error); } static void saf1761_otg_standard_done(struct usb_xfer *xfer) { usb_error_t err = 0; DPRINTFN(13, "xfer=%p endpoint=%p transfer done\n", xfer, xfer->endpoint); /* reset scanner */ xfer->td_transfer_cache = xfer->td_transfer_first; if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_hdr) { err = saf1761_otg_standard_done_sub(xfer); } xfer->aframes = 1; if (xfer->td_transfer_cache == NULL) { goto done; } } while (xfer->aframes != xfer->nframes) { err = saf1761_otg_standard_done_sub(xfer); xfer->aframes++; if (xfer->td_transfer_cache == NULL) { goto done; } } if (xfer->flags_int.control_xfr && !xfer->flags_int.control_act) { err = saf1761_otg_standard_done_sub(xfer); } done: saf1761_otg_device_done(xfer, err); } /*------------------------------------------------------------------------* * saf1761_otg_device_done * * NOTE: this function can be called more than one time on the * same USB transfer! *------------------------------------------------------------------------*/ static void saf1761_otg_device_done(struct usb_xfer *xfer, usb_error_t error) { struct saf1761_otg_softc *sc = SAF1761_OTG_BUS2SC(xfer->xroot->bus); USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED); DPRINTFN(2, "xfer=%p, endpoint=%p, error=%d\n", xfer, xfer->endpoint, error); USB_BUS_SPIN_LOCK(&sc->sc_bus); if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) { saf1761_otg_intr_set(xfer, 0); } else { struct saf1761_otg_td *td; td = xfer->td_transfer_cache; if (td != NULL) saf1761_host_channel_free(sc, td); } /* dequeue transfer and start next transfer */ usbd_transfer_done(xfer, error); USB_BUS_SPIN_UNLOCK(&sc->sc_bus); } static void saf1761_otg_xfer_stall(struct usb_xfer *xfer) { saf1761_otg_device_done(xfer, USB_ERR_STALLED); } static void saf1761_otg_set_stall(struct usb_device *udev, struct usb_endpoint *ep, uint8_t *did_stall) { struct saf1761_otg_softc *sc; uint8_t ep_no; uint8_t ep_type; uint8_t ep_dir; USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED); /* check mode */ if (udev->flags.usb_mode != USB_MODE_DEVICE) { /* not supported */ return; } DPRINTFN(5, "endpoint=%p\n", ep); /* set STALL bit */ sc = SAF1761_OTG_BUS2SC(udev->bus); ep_no = (ep->edesc->bEndpointAddress & UE_ADDR); ep_dir = (ep->edesc->bEndpointAddress & (UE_DIR_IN | UE_DIR_OUT)); ep_type = (ep->edesc->bmAttributes & UE_XFERTYPE); if (ep_type == UE_CONTROL) { /* should not happen */ return; } USB_BUS_SPIN_LOCK(&sc->sc_bus); /* select the correct endpoint */ SAF1761_WRITE_LE_4(sc, SOTG_EP_INDEX, (ep_no << SOTG_EP_INDEX_ENDP_INDEX_SHIFT) | ((ep_dir == UE_DIR_IN) ? SOTG_EP_INDEX_DIR_IN : SOTG_EP_INDEX_DIR_OUT)); /* set stall */ SAF1761_WRITE_LE_4(sc, SOTG_CTRL_FUNC, SOTG_CTRL_FUNC_STALL); USB_BUS_SPIN_UNLOCK(&sc->sc_bus); } static void saf1761_otg_clear_stall_sub_locked(struct saf1761_otg_softc *sc, uint8_t ep_no, uint8_t ep_type, uint8_t ep_dir) { if (ep_type == UE_CONTROL) { /* clearing stall is not needed */ return; } /* select the correct endpoint */ SAF1761_WRITE_LE_4(sc, SOTG_EP_INDEX, (ep_no << SOTG_EP_INDEX_ENDP_INDEX_SHIFT) | ((ep_dir == UE_DIR_IN) ? SOTG_EP_INDEX_DIR_IN : SOTG_EP_INDEX_DIR_OUT)); /* disable endpoint */ SAF1761_WRITE_LE_4(sc, SOTG_EP_TYPE, 0); /* enable endpoint again - will clear data toggle */ SAF1761_WRITE_LE_4(sc, SOTG_EP_TYPE, ep_type | SOTG_EP_TYPE_ENABLE); /* clear buffer */ SAF1761_WRITE_LE_4(sc, SOTG_CTRL_FUNC, SOTG_CTRL_FUNC_CLBUF); /* clear stall */ SAF1761_WRITE_LE_4(sc, SOTG_CTRL_FUNC, 0); } static void saf1761_otg_clear_stall(struct usb_device *udev, struct usb_endpoint *ep) { struct saf1761_otg_softc *sc; struct usb_endpoint_descriptor *ed; USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED); DPRINTFN(5, "endpoint=%p\n", ep); /* check mode */ if (udev->flags.usb_mode != USB_MODE_DEVICE) { /* not supported */ return; } /* get softc */ sc = SAF1761_OTG_BUS2SC(udev->bus); USB_BUS_SPIN_LOCK(&sc->sc_bus); /* get endpoint descriptor */ ed = ep->edesc; /* reset endpoint */ saf1761_otg_clear_stall_sub_locked(sc, (ed->bEndpointAddress & UE_ADDR), (ed->bmAttributes & UE_XFERTYPE), (ed->bEndpointAddress & (UE_DIR_IN | UE_DIR_OUT))); USB_BUS_SPIN_UNLOCK(&sc->sc_bus); } usb_error_t saf1761_otg_init(struct saf1761_otg_softc *sc) { const struct usb_hw_ep_profile *pf; uint32_t x; DPRINTF("\n"); /* set up the bus structure */ sc->sc_bus.usbrev = USB_REV_2_0; sc->sc_bus.methods = &saf1761_otg_bus_methods; USB_BUS_LOCK(&sc->sc_bus); /* Reset Host controller, including HW mode */ SAF1761_WRITE_LE_4(sc, SOTG_SW_RESET, SOTG_SW_RESET_ALL); DELAY(1000); /* Reset Host controller, including HW mode */ SAF1761_WRITE_LE_4(sc, SOTG_SW_RESET, SOTG_SW_RESET_HC); /* wait a bit */ DELAY(1000); SAF1761_WRITE_LE_4(sc, SOTG_SW_RESET, 0); /* wait a bit */ DELAY(1000); /* Enable interrupts */ sc->sc_hw_mode |= SOTG_HW_MODE_CTRL_GLOBAL_INTR_EN | SOTG_HW_MODE_CTRL_COMN_INT; /* unlock device */ SAF1761_WRITE_LE_4(sc, SOTG_UNLOCK_DEVICE, SOTG_UNLOCK_DEVICE_CODE); /* * Set correct hardware mode, must be written twice if bus * width is changed: */ SAF1761_WRITE_LE_4(sc, SOTG_HW_MODE_CTRL, sc->sc_hw_mode); SAF1761_WRITE_LE_4(sc, SOTG_HW_MODE_CTRL, sc->sc_hw_mode); SAF1761_WRITE_LE_4(sc, SOTG_DCSCRATCH, 0xdeadbeef); SAF1761_WRITE_LE_4(sc, SOTG_HCSCRATCH, 0xdeadbeef); DPRINTF("DCID=0x%08x VEND_PROD=0x%08x HWMODE=0x%08x SCRATCH=0x%08x,0x%08x\n", SAF1761_READ_LE_4(sc, SOTG_DCCHIP_ID), SAF1761_READ_LE_4(sc, SOTG_VEND_PROD_ID), SAF1761_READ_LE_4(sc, SOTG_HW_MODE_CTRL), SAF1761_READ_LE_4(sc, SOTG_DCSCRATCH), SAF1761_READ_LE_4(sc, SOTG_HCSCRATCH)); /* reset device controller */ SAF1761_WRITE_LE_4(sc, SOTG_MODE, SOTG_MODE_SFRESET); SAF1761_WRITE_LE_4(sc, SOTG_MODE, 0); /* wait a bit */ DELAY(1000); /* reset host controller */ SAF1761_WRITE_LE_4(sc, SOTG_USBCMD, SOTG_USBCMD_HCRESET); /* wait for reset to clear */ for (x = 0; x != 10; x++) { if ((SAF1761_READ_LE_4(sc, SOTG_USBCMD) & SOTG_USBCMD_HCRESET) == 0) break; usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 10); } SAF1761_WRITE_LE_4(sc, SOTG_HW_MODE_CTRL, sc->sc_hw_mode | SOTG_HW_MODE_CTRL_ALL_ATX_RESET); /* wait a bit */ DELAY(1000); SAF1761_WRITE_LE_4(sc, SOTG_HW_MODE_CTRL, sc->sc_hw_mode); /* wait a bit */ DELAY(1000); /* do a pulldown */ saf1761_otg_pull_down(sc); /* wait 10ms for pulldown to stabilise */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 100); for (x = 1;; x++) { saf1761_otg_get_hw_ep_profile(NULL, &pf, x); if (pf == NULL) break; /* select the correct endpoint */ SAF1761_WRITE_LE_4(sc, SOTG_EP_INDEX, (x << SOTG_EP_INDEX_ENDP_INDEX_SHIFT) | SOTG_EP_INDEX_DIR_IN); /* select the maximum packet size */ SAF1761_WRITE_LE_4(sc, SOTG_EP_MAXPACKET, pf->max_in_frame_size); /* select the correct endpoint */ SAF1761_WRITE_LE_4(sc, SOTG_EP_INDEX, (x << SOTG_EP_INDEX_ENDP_INDEX_SHIFT) | SOTG_EP_INDEX_DIR_OUT); /* select the maximum packet size */ SAF1761_WRITE_LE_4(sc, SOTG_EP_MAXPACKET, pf->max_out_frame_size); } /* enable interrupts */ SAF1761_WRITE_LE_4(sc, SOTG_MODE, SOTG_MODE_GLINTENA | SOTG_MODE_CLKAON | SOTG_MODE_WKUPCS); sc->sc_interrupt_cfg |= SOTG_INTERRUPT_CFG_CDBGMOD | SOTG_INTERRUPT_CFG_DDBGMODIN | SOTG_INTERRUPT_CFG_DDBGMODOUT; /* set default values */ SAF1761_WRITE_LE_4(sc, SOTG_INTERRUPT_CFG, sc->sc_interrupt_cfg); /* enable VBUS and ID interrupt */ SAF1761_WRITE_LE_4(sc, SOTG_IRQ_ENABLE_SET_CLR, SOTG_IRQ_ENABLE_CLR(0xFFFF)); SAF1761_WRITE_LE_4(sc, SOTG_IRQ_ENABLE_SET_CLR, SOTG_IRQ_ENABLE_SET(SOTG_IRQ_ID | SOTG_IRQ_VBUS_VLD)); /* enable interrupts */ sc->sc_intr_enable = SOTG_DCINTERRUPT_IEVBUS | SOTG_DCINTERRUPT_IEBRST | SOTG_DCINTERRUPT_IESUSP; SAF1761_WRITE_LE_4(sc, SOTG_DCINTERRUPT_EN, sc->sc_intr_enable); /* * Connect ATX port 1 to device controller, select external * charge pump and driver VBUS to +5V: */ SAF1761_WRITE_LE_4(sc, SOTG_CTRL_SET_CLR, SOTG_CTRL_CLR(0xFFFF)); SAF1761_WRITE_LE_4(sc, SOTG_CTRL_SET_CLR, SOTG_CTRL_SET(SOTG_CTRL_SW_SEL_HC_DC | SOTG_CTRL_BDIS_ACON_EN | SOTG_CTRL_SEL_CP_EXT | SOTG_CTRL_VBUS_DRV)); /* disable device address */ SAF1761_WRITE_LE_4(sc, SOTG_ADDRESS, 0); /* enable host controller clock and preserve reserved bits */ x = SAF1761_READ_LE_4(sc, SOTG_POWER_DOWN); SAF1761_WRITE_LE_4(sc, SOTG_POWER_DOWN, x | SOTG_POWER_DOWN_HC_CLK_EN); /* wait 10ms for clock */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 100); /* enable configuration flag */ SAF1761_WRITE_LE_4(sc, SOTG_CONFIGFLAG, SOTG_CONFIGFLAG_ENABLE); /* clear RAM block */ for (x = 0x400; x != 0x10000; x += 4) SAF1761_WRITE_LE_4(sc, x, 0); /* start the HC */ SAF1761_WRITE_LE_4(sc, SOTG_USBCMD, SOTG_USBCMD_RS); DPRINTF("USBCMD=0x%08x\n", SAF1761_READ_LE_4(sc, SOTG_USBCMD)); /* make HC scan all PTDs */ SAF1761_WRITE_LE_4(sc, SOTG_ATL_PTD_LAST_PTD, (1 << 31)); SAF1761_WRITE_LE_4(sc, SOTG_INT_PTD_LAST_PTD, (1 << 31)); SAF1761_WRITE_LE_4(sc, SOTG_ISO_PTD_LAST_PTD, (1 << 31)); /* skip all PTDs by default */ SAF1761_WRITE_LE_4(sc, SOTG_ATL_PTD_SKIP_PTD, -1U); SAF1761_WRITE_LE_4(sc, SOTG_INT_PTD_SKIP_PTD, -1U); SAF1761_WRITE_LE_4(sc, SOTG_ISO_PTD_SKIP_PTD, -1U); /* activate all PTD types */ SAF1761_WRITE_LE_4(sc, SOTG_HCBUFFERSTATUS, SOTG_HCBUFFERSTATUS_ISO_BUF_FILL | SOTG_HCBUFFERSTATUS_INT_BUF_FILL | SOTG_HCBUFFERSTATUS_ATL_BUF_FILL); /* we don't use the AND mask */ SAF1761_WRITE_LE_4(sc, SOTG_ISO_IRQ_MASK_AND, 0); SAF1761_WRITE_LE_4(sc, SOTG_INT_IRQ_MASK_AND, 0); SAF1761_WRITE_LE_4(sc, SOTG_ATL_IRQ_MASK_AND, 0); /* enable all PTD OR interrupts by default */ SAF1761_WRITE_LE_4(sc, SOTG_ISO_IRQ_MASK_OR, -1U); SAF1761_WRITE_LE_4(sc, SOTG_INT_IRQ_MASK_OR, -1U); SAF1761_WRITE_LE_4(sc, SOTG_ATL_IRQ_MASK_OR, -1U); /* enable HC interrupts */ SAF1761_WRITE_LE_4(sc, SOTG_HCINTERRUPT_ENABLE, SOTG_HCINTERRUPT_OTG_IRQ | SOTG_HCINTERRUPT_ISO_IRQ | SOTG_HCINTERRUPT_ALT_IRQ | SOTG_HCINTERRUPT_INT_IRQ); /* poll initial VBUS status */ saf1761_otg_update_vbus(sc); USB_BUS_UNLOCK(&sc->sc_bus); /* catch any lost interrupts */ saf1761_otg_do_poll(&sc->sc_bus); return (0); /* success */ } void saf1761_otg_uninit(struct saf1761_otg_softc *sc) { USB_BUS_LOCK(&sc->sc_bus); /* disable all interrupts */ SAF1761_WRITE_LE_4(sc, SOTG_MODE, 0); sc->sc_flags.port_powered = 0; sc->sc_flags.status_vbus = 0; sc->sc_flags.status_bus_reset = 0; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; saf1761_otg_pull_down(sc); USB_BUS_UNLOCK(&sc->sc_bus); } static void saf1761_otg_suspend(struct saf1761_otg_softc *sc) { /* TODO */ } static void saf1761_otg_resume(struct saf1761_otg_softc *sc) { /* TODO */ } static void saf1761_otg_do_poll(struct usb_bus *bus) { struct saf1761_otg_softc *sc = SAF1761_OTG_BUS2SC(bus); USB_BUS_LOCK(&sc->sc_bus); USB_BUS_SPIN_LOCK(&sc->sc_bus); saf1761_otg_interrupt_poll_locked(sc); saf1761_otg_interrupt_complete_locked(sc); USB_BUS_SPIN_UNLOCK(&sc->sc_bus); USB_BUS_UNLOCK(&sc->sc_bus); } /*------------------------------------------------------------------------* * saf1761_otg control support * saf1761_otg interrupt support * saf1761_otg bulk support *------------------------------------------------------------------------*/ static void saf1761_otg_device_non_isoc_open(struct usb_xfer *xfer) { return; } static void saf1761_otg_device_non_isoc_close(struct usb_xfer *xfer) { saf1761_otg_device_done(xfer, USB_ERR_CANCELLED); } static void saf1761_otg_device_non_isoc_enter(struct usb_xfer *xfer) { return; } static void saf1761_otg_device_non_isoc_start(struct usb_xfer *xfer) { /* setup TDs */ saf1761_otg_setup_standard_chain(xfer); saf1761_otg_start_standard_chain(xfer); } static const struct usb_pipe_methods saf1761_otg_non_isoc_methods = { .open = saf1761_otg_device_non_isoc_open, .close = saf1761_otg_device_non_isoc_close, .enter = saf1761_otg_device_non_isoc_enter, .start = saf1761_otg_device_non_isoc_start, }; /*------------------------------------------------------------------------* * saf1761_otg device side isochronous support *------------------------------------------------------------------------*/ static void saf1761_otg_device_isoc_open(struct usb_xfer *xfer) { return; } static void saf1761_otg_device_isoc_close(struct usb_xfer *xfer) { saf1761_otg_device_done(xfer, USB_ERR_CANCELLED); } static void saf1761_otg_device_isoc_enter(struct usb_xfer *xfer) { struct saf1761_otg_softc *sc = SAF1761_OTG_BUS2SC(xfer->xroot->bus); uint32_t temp; uint32_t nframes; DPRINTFN(6, "xfer=%p next=%d nframes=%d\n", xfer, xfer->endpoint->isoc_next, xfer->nframes); /* get the current frame index - we don't need the high bits */ nframes = SAF1761_READ_LE_4(sc, SOTG_FRAME_NUM); /* * check if the frame index is within the window where the * frames will be inserted */ temp = (nframes - xfer->endpoint->isoc_next) & SOTG_FRAME_NUM_SOFR_MASK; if ((xfer->endpoint->is_synced == 0) || (temp < xfer->nframes)) { /* * If there is data underflow or the pipe queue is * empty we schedule the transfer a few frames ahead * of the current frame position. Else two isochronous * transfers might overlap. */ xfer->endpoint->isoc_next = (nframes + 3) & SOTG_FRAME_NUM_SOFR_MASK; xfer->endpoint->is_synced = 1; DPRINTFN(3, "start next=%d\n", xfer->endpoint->isoc_next); } /* * compute how many milliseconds the insertion is ahead of the * current frame position: */ temp = (xfer->endpoint->isoc_next - nframes) & SOTG_FRAME_NUM_SOFR_MASK; /* * pre-compute when the isochronous transfer will be finished: */ xfer->isoc_time_complete = usb_isoc_time_expand(&sc->sc_bus, nframes) + temp + xfer->nframes; /* compute frame number for next insertion */ xfer->endpoint->isoc_next += xfer->nframes; /* setup TDs */ saf1761_otg_setup_standard_chain(xfer); } static void saf1761_otg_device_isoc_start(struct usb_xfer *xfer) { /* start TD chain */ saf1761_otg_start_standard_chain(xfer); } static const struct usb_pipe_methods saf1761_otg_device_isoc_methods = { .open = saf1761_otg_device_isoc_open, .close = saf1761_otg_device_isoc_close, .enter = saf1761_otg_device_isoc_enter, .start = saf1761_otg_device_isoc_start, }; /*------------------------------------------------------------------------* * saf1761_otg host side isochronous support *------------------------------------------------------------------------*/ static void saf1761_otg_host_isoc_open(struct usb_xfer *xfer) { return; } static void saf1761_otg_host_isoc_close(struct usb_xfer *xfer) { saf1761_otg_device_done(xfer, USB_ERR_CANCELLED); } static void saf1761_otg_host_isoc_enter(struct usb_xfer *xfer) { struct saf1761_otg_softc *sc = SAF1761_OTG_BUS2SC(xfer->xroot->bus); uint32_t temp; uint32_t nframes; DPRINTFN(6, "xfer=%p next=%d nframes=%d\n", xfer, xfer->endpoint->isoc_next, xfer->nframes); /* get the current frame index - we don't need the high bits */ nframes = (SAF1761_READ_LE_4(sc, SOTG_FRINDEX) & SOTG_FRINDEX_MASK) >> 3; /* * check if the frame index is within the window where the * frames will be inserted */ temp = (nframes - xfer->endpoint->isoc_next) & (SOTG_FRINDEX_MASK >> 3); if ((xfer->endpoint->is_synced == 0) || (temp < xfer->nframes)) { /* * If there is data underflow or the pipe queue is * empty we schedule the transfer a few frames ahead * of the current frame position. Else two isochronous * transfers might overlap. */ xfer->endpoint->isoc_next = (nframes + 3) & (SOTG_FRINDEX_MASK >> 3); xfer->endpoint->is_synced = 1; DPRINTFN(3, "start next=%d\n", xfer->endpoint->isoc_next); } /* * compute how many milliseconds the insertion is ahead of the * current frame position: */ temp = (xfer->endpoint->isoc_next - nframes) & (SOTG_FRINDEX_MASK >> 3); /* * pre-compute when the isochronous transfer will be finished: */ xfer->isoc_time_complete = usb_isoc_time_expand(&sc->sc_bus, nframes) + temp + xfer->nframes; /* compute frame number for next insertion */ xfer->endpoint->isoc_next += xfer->nframes; /* setup TDs */ saf1761_otg_setup_standard_chain(xfer); } static void saf1761_otg_host_isoc_start(struct usb_xfer *xfer) { /* start TD chain */ saf1761_otg_start_standard_chain(xfer); } static const struct usb_pipe_methods saf1761_otg_host_isoc_methods = { .open = saf1761_otg_host_isoc_open, .close = saf1761_otg_host_isoc_close, .enter = saf1761_otg_host_isoc_enter, .start = saf1761_otg_host_isoc_start, }; /*------------------------------------------------------------------------* * saf1761_otg root control support *------------------------------------------------------------------------* * Simulate a hardware HUB by handling all the necessary requests. *------------------------------------------------------------------------*/ #define HSETW(ptr, val) ptr = { (uint8_t)(val), (uint8_t)((val) >> 8) } static const struct usb_device_descriptor saf1761_otg_devd = { .bLength = sizeof(struct usb_device_descriptor), .bDescriptorType = UDESC_DEVICE, HSETW(.idVendor, 0x04cc), HSETW(.idProduct, 0x1761), .bcdUSB = {0x00, 0x02}, .bDeviceClass = UDCLASS_HUB, .bDeviceSubClass = UDSUBCLASS_HUB, .bDeviceProtocol = UDPROTO_FSHUB, .bMaxPacketSize = 64, .bcdDevice = {0x00, 0x01}, .iManufacturer = 1, .iProduct = 2, .bNumConfigurations = 1, }; static const struct usb_device_qualifier saf1761_otg_odevd = { .bLength = sizeof(struct usb_device_qualifier), .bDescriptorType = UDESC_DEVICE_QUALIFIER, .bcdUSB = {0x00, 0x02}, .bDeviceClass = UDCLASS_HUB, .bDeviceSubClass = UDSUBCLASS_HUB, .bDeviceProtocol = UDPROTO_FSHUB, .bMaxPacketSize0 = 0, .bNumConfigurations = 0, }; static const struct saf1761_otg_config_desc saf1761_otg_confd = { .confd = { .bLength = sizeof(struct usb_config_descriptor), .bDescriptorType = UDESC_CONFIG, .wTotalLength[0] = sizeof(saf1761_otg_confd), .bNumInterface = 1, .bConfigurationValue = 1, .iConfiguration = 0, .bmAttributes = UC_SELF_POWERED, .bMaxPower = 0, }, .ifcd = { .bLength = sizeof(struct usb_interface_descriptor), .bDescriptorType = UDESC_INTERFACE, .bNumEndpoints = 1, .bInterfaceClass = UICLASS_HUB, .bInterfaceSubClass = UISUBCLASS_HUB, .bInterfaceProtocol = 0, }, .endpd = { .bLength = sizeof(struct usb_endpoint_descriptor), .bDescriptorType = UDESC_ENDPOINT, .bEndpointAddress = (UE_DIR_IN | SAF1761_OTG_INTR_ENDPT), .bmAttributes = UE_INTERRUPT, .wMaxPacketSize[0] = 8, .bInterval = 255, }, }; static const struct usb_hub_descriptor_min saf1761_otg_hubd = { .bDescLength = sizeof(saf1761_otg_hubd), .bDescriptorType = UDESC_HUB, .bNbrPorts = SOTG_NUM_PORTS, HSETW(.wHubCharacteristics, (UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL)), .bPwrOn2PwrGood = 50, .bHubContrCurrent = 0, .DeviceRemovable = {0}, /* port is removable */ }; #define STRING_VENDOR \ "N\0X\0P" #define STRING_PRODUCT \ "D\0C\0I\0 \0R\0o\0o\0t\0 \0H\0U\0B" USB_MAKE_STRING_DESC(STRING_VENDOR, saf1761_otg_vendor); USB_MAKE_STRING_DESC(STRING_PRODUCT, saf1761_otg_product); static usb_error_t saf1761_otg_roothub_exec(struct usb_device *udev, struct usb_device_request *req, const void **pptr, uint16_t *plength) { struct saf1761_otg_softc *sc = SAF1761_OTG_BUS2SC(udev->bus); const void *ptr; uint16_t len; uint16_t value; uint16_t index; uint32_t temp; uint32_t i; usb_error_t err; USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); /* buffer reset */ ptr = (const void *)&sc->sc_hub_temp; len = 0; err = 0; value = UGETW(req->wValue); index = UGETW(req->wIndex); /* demultiplex the control request */ switch (req->bmRequestType) { case UT_READ_DEVICE: switch (req->bRequest) { case UR_GET_DESCRIPTOR: goto tr_handle_get_descriptor; case UR_GET_CONFIG: goto tr_handle_get_config; case UR_GET_STATUS: goto tr_handle_get_status; default: goto tr_stalled; } break; case UT_WRITE_DEVICE: switch (req->bRequest) { case UR_SET_ADDRESS: goto tr_handle_set_address; case UR_SET_CONFIG: goto tr_handle_set_config; case UR_CLEAR_FEATURE: goto tr_valid; /* nop */ case UR_SET_DESCRIPTOR: goto tr_valid; /* nop */ case UR_SET_FEATURE: default: goto tr_stalled; } break; case UT_WRITE_ENDPOINT: switch (req->bRequest) { case UR_CLEAR_FEATURE: switch (UGETW(req->wValue)) { case UF_ENDPOINT_HALT: goto tr_handle_clear_halt; case UF_DEVICE_REMOTE_WAKEUP: goto tr_handle_clear_wakeup; default: goto tr_stalled; } break; case UR_SET_FEATURE: switch (UGETW(req->wValue)) { case UF_ENDPOINT_HALT: goto tr_handle_set_halt; case UF_DEVICE_REMOTE_WAKEUP: goto tr_handle_set_wakeup; default: goto tr_stalled; } break; case UR_SYNCH_FRAME: goto tr_valid; /* nop */ default: goto tr_stalled; } break; case UT_READ_ENDPOINT: switch (req->bRequest) { case UR_GET_STATUS: goto tr_handle_get_ep_status; default: goto tr_stalled; } break; case UT_WRITE_INTERFACE: switch (req->bRequest) { case UR_SET_INTERFACE: goto tr_handle_set_interface; case UR_CLEAR_FEATURE: goto tr_valid; /* nop */ case UR_SET_FEATURE: default: goto tr_stalled; } break; case UT_READ_INTERFACE: switch (req->bRequest) { case UR_GET_INTERFACE: goto tr_handle_get_interface; case UR_GET_STATUS: goto tr_handle_get_iface_status; default: goto tr_stalled; } break; case UT_WRITE_CLASS_INTERFACE: case UT_WRITE_VENDOR_INTERFACE: /* XXX forward */ break; case UT_READ_CLASS_INTERFACE: case UT_READ_VENDOR_INTERFACE: /* XXX forward */ break; case UT_WRITE_CLASS_DEVICE: switch (req->bRequest) { case UR_CLEAR_FEATURE: goto tr_valid; case UR_SET_DESCRIPTOR: case UR_SET_FEATURE: break; default: goto tr_stalled; } break; case UT_WRITE_CLASS_OTHER: switch (req->bRequest) { case UR_CLEAR_FEATURE: if (index == SOTG_HOST_PORT_NUM) goto tr_handle_clear_port_feature_host; else if (index == SOTG_DEVICE_PORT_NUM) goto tr_handle_clear_port_feature_device; else goto tr_stalled; case UR_SET_FEATURE: if (index == SOTG_HOST_PORT_NUM) goto tr_handle_set_port_feature_host; else if (index == SOTG_DEVICE_PORT_NUM) goto tr_handle_set_port_feature_device; else goto tr_stalled; case UR_CLEAR_TT_BUFFER: case UR_RESET_TT: case UR_STOP_TT: goto tr_valid; default: goto tr_stalled; } break; case UT_READ_CLASS_OTHER: switch (req->bRequest) { case UR_GET_TT_STATE: goto tr_handle_get_tt_state; case UR_GET_STATUS: if (index == SOTG_HOST_PORT_NUM) goto tr_handle_get_port_status_host; else if (index == SOTG_DEVICE_PORT_NUM) goto tr_handle_get_port_status_device; else goto tr_stalled; default: goto tr_stalled; } break; case UT_READ_CLASS_DEVICE: switch (req->bRequest) { case UR_GET_DESCRIPTOR: goto tr_handle_get_class_descriptor; case UR_GET_STATUS: goto tr_handle_get_class_status; default: goto tr_stalled; } break; default: goto tr_stalled; } goto tr_valid; tr_handle_get_descriptor: switch (value >> 8) { case UDESC_DEVICE: if (value & 0xff) goto tr_stalled; len = sizeof(saf1761_otg_devd); ptr = (const void *)&saf1761_otg_devd; goto tr_valid; case UDESC_DEVICE_QUALIFIER: if (value & 0xff) goto tr_stalled; len = sizeof(saf1761_otg_odevd); ptr = (const void *)&saf1761_otg_odevd; goto tr_valid; case UDESC_CONFIG: if (value & 0xff) goto tr_stalled; len = sizeof(saf1761_otg_confd); ptr = (const void *)&saf1761_otg_confd; goto tr_valid; case UDESC_STRING: switch (value & 0xff) { case 0: /* Language table */ len = sizeof(usb_string_lang_en); ptr = (const void *)&usb_string_lang_en; goto tr_valid; case 1: /* Vendor */ len = sizeof(saf1761_otg_vendor); ptr = (const void *)&saf1761_otg_vendor; goto tr_valid; case 2: /* Product */ len = sizeof(saf1761_otg_product); ptr = (const void *)&saf1761_otg_product; goto tr_valid; default: break; } break; default: goto tr_stalled; } goto tr_stalled; tr_handle_get_config: len = 1; sc->sc_hub_temp.wValue[0] = sc->sc_conf; goto tr_valid; tr_handle_get_status: len = 2; USETW(sc->sc_hub_temp.wValue, UDS_SELF_POWERED); goto tr_valid; tr_handle_set_address: if (value & 0xFF00) goto tr_stalled; sc->sc_rt_addr = value; goto tr_valid; tr_handle_set_config: if (value >= 2) goto tr_stalled; sc->sc_conf = value; goto tr_valid; tr_handle_get_interface: len = 1; sc->sc_hub_temp.wValue[0] = 0; goto tr_valid; tr_handle_get_tt_state: tr_handle_get_class_status: tr_handle_get_iface_status: tr_handle_get_ep_status: len = 2; USETW(sc->sc_hub_temp.wValue, 0); goto tr_valid; tr_handle_set_halt: tr_handle_set_interface: tr_handle_set_wakeup: tr_handle_clear_wakeup: tr_handle_clear_halt: goto tr_valid; tr_handle_clear_port_feature_device: DPRINTFN(9, "UR_CLEAR_FEATURE on port %d\n", index); switch (value) { case UHF_PORT_SUSPEND: saf1761_otg_wakeup_peer(sc); break; case UHF_PORT_ENABLE: sc->sc_flags.port_enabled = 0; break; case UHF_PORT_TEST: case UHF_PORT_INDICATOR: case UHF_C_PORT_ENABLE: case UHF_C_PORT_OVER_CURRENT: case UHF_C_PORT_RESET: /* nops */ break; case UHF_PORT_POWER: sc->sc_flags.port_powered = 0; saf1761_otg_pull_down(sc); break; case UHF_C_PORT_CONNECTION: sc->sc_flags.change_connect = 0; break; case UHF_C_PORT_SUSPEND: sc->sc_flags.change_suspend = 0; break; default: err = USB_ERR_IOERROR; goto tr_valid; } goto tr_valid; tr_handle_clear_port_feature_host: DPRINTFN(9, "UR_CLEAR_FEATURE on port %d\n", index); temp = SAF1761_READ_LE_4(sc, SOTG_PORTSC1); switch (value) { case UHF_PORT_ENABLE: SAF1761_WRITE_LE_4(sc, SOTG_PORTSC1, temp & ~SOTG_PORTSC1_PED); break; case UHF_PORT_SUSPEND: if ((temp & SOTG_PORTSC1_SUSP) && (!(temp & SOTG_PORTSC1_FPR))) SAF1761_WRITE_LE_4(sc, SOTG_PORTSC1, temp | SOTG_PORTSC1_FPR); /* wait 20ms for resume sequence to complete */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 50); SAF1761_WRITE_LE_4(sc, SOTG_PORTSC1, temp & ~(SOTG_PORTSC1_SUSP | SOTG_PORTSC1_FPR | SOTG_PORTSC1_LS /* High Speed */ )); /* 4ms settle time */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 250); break; case UHF_PORT_INDICATOR: SAF1761_WRITE_LE_4(sc, SOTG_PORTSC1, temp & ~SOTG_PORTSC1_PIC); break; case UHF_PORT_TEST: case UHF_C_PORT_ENABLE: case UHF_C_PORT_OVER_CURRENT: case UHF_C_PORT_RESET: case UHF_C_PORT_SUSPEND: /* NOPs */ break; case UHF_PORT_POWER: SAF1761_WRITE_LE_4(sc, SOTG_PORTSC1, temp & ~SOTG_PORTSC1_PP); break; case UHF_C_PORT_CONNECTION: SAF1761_WRITE_LE_4(sc, SOTG_PORTSC1, temp & ~SOTG_PORTSC1_ECSC); break; default: err = USB_ERR_IOERROR; goto tr_valid; } goto tr_valid; tr_handle_set_port_feature_device: DPRINTFN(9, "UR_SET_FEATURE on port %d\n", index); switch (value) { case UHF_PORT_ENABLE: sc->sc_flags.port_enabled = 1; break; case UHF_PORT_SUSPEND: case UHF_PORT_RESET: case UHF_PORT_TEST: case UHF_PORT_INDICATOR: /* nops */ break; case UHF_PORT_POWER: sc->sc_flags.port_powered = 1; break; default: err = USB_ERR_IOERROR; goto tr_valid; } goto tr_valid; tr_handle_set_port_feature_host: DPRINTFN(9, "UR_SET_FEATURE on port %d\n", index); temp = SAF1761_READ_LE_4(sc, SOTG_PORTSC1); switch (value) { case UHF_PORT_ENABLE: SAF1761_WRITE_LE_4(sc, SOTG_PORTSC1, temp | SOTG_PORTSC1_PED); break; case UHF_PORT_SUSPEND: SAF1761_WRITE_LE_4(sc, SOTG_PORTSC1, temp | SOTG_PORTSC1_SUSP); break; case UHF_PORT_RESET: DPRINTFN(6, "reset port %d\n", index); /* Start reset sequence. */ temp &= ~(SOTG_PORTSC1_PED | SOTG_PORTSC1_PR); SAF1761_WRITE_LE_4(sc, SOTG_PORTSC1, temp | SOTG_PORTSC1_PR); /* Wait for reset to complete. */ usb_pause_mtx(&sc->sc_bus.bus_mtx, USB_MS_TO_TICKS(usb_port_root_reset_delay)); SAF1761_WRITE_LE_4(sc, SOTG_PORTSC1, temp); /* Wait for HC to complete reset. */ usb_pause_mtx(&sc->sc_bus.bus_mtx, USB_MS_TO_TICKS(2)); temp = SAF1761_READ_LE_4(sc, SOTG_PORTSC1); DPRINTF("After reset, status=0x%08x\n", temp); if (temp & SOTG_PORTSC1_PR) { device_printf(sc->sc_bus.bdev, "port reset timeout\n"); err = USB_ERR_TIMEOUT; goto tr_valid; } if (!(temp & SOTG_PORTSC1_PED)) { /* Not a high speed device, give up ownership.*/ SAF1761_WRITE_LE_4(sc, SOTG_PORTSC1, temp | SOTG_PORTSC1_PO); break; } sc->sc_isreset = 1; DPRINTF("port %d reset, status = 0x%08x\n", index, temp); break; case UHF_PORT_POWER: DPRINTFN(3, "set port power %d\n", index); SAF1761_WRITE_LE_4(sc, SOTG_PORTSC1, temp | SOTG_PORTSC1_PP); break; case UHF_PORT_TEST: DPRINTFN(3, "set port test %d\n", index); break; case UHF_PORT_INDICATOR: DPRINTFN(3, "set port ind %d\n", index); SAF1761_WRITE_LE_4(sc, SOTG_PORTSC1, temp | SOTG_PORTSC1_PIC); break; default: err = USB_ERR_IOERROR; goto tr_valid; } goto tr_valid; tr_handle_get_port_status_device: DPRINTFN(9, "UR_GET_PORT_STATUS on port %d\n", index); if (sc->sc_flags.status_vbus) { saf1761_otg_pull_up(sc); } else { saf1761_otg_pull_down(sc); } /* Select FULL-speed and Device Side Mode */ value = UPS_PORT_MODE_DEVICE; if (sc->sc_flags.port_powered) value |= UPS_PORT_POWER; if (sc->sc_flags.port_enabled) value |= UPS_PORT_ENABLED; if (sc->sc_flags.status_vbus && sc->sc_flags.status_bus_reset) value |= UPS_CURRENT_CONNECT_STATUS; if (sc->sc_flags.status_suspend) value |= UPS_SUSPEND; USETW(sc->sc_hub_temp.ps.wPortStatus, value); value = 0; if (sc->sc_flags.change_connect) value |= UPS_C_CONNECT_STATUS; if (sc->sc_flags.change_suspend) value |= UPS_C_SUSPEND; USETW(sc->sc_hub_temp.ps.wPortChange, value); len = sizeof(sc->sc_hub_temp.ps); goto tr_valid; tr_handle_get_port_status_host: temp = SAF1761_READ_LE_4(sc, SOTG_PORTSC1); DPRINTFN(9, "UR_GET_PORT_STATUS on port %d = 0x%08x\n", index, temp); i = UPS_HIGH_SPEED; if (temp & SOTG_PORTSC1_ECCS) i |= UPS_CURRENT_CONNECT_STATUS; if (temp & SOTG_PORTSC1_PED) i |= UPS_PORT_ENABLED; if ((temp & SOTG_PORTSC1_SUSP) && !(temp & SOTG_PORTSC1_FPR)) i |= UPS_SUSPEND; if (temp & SOTG_PORTSC1_PR) i |= UPS_RESET; if (temp & SOTG_PORTSC1_PP) i |= UPS_PORT_POWER; USETW(sc->sc_hub_temp.ps.wPortStatus, i); i = 0; if (temp & SOTG_PORTSC1_ECSC) i |= UPS_C_CONNECT_STATUS; if (temp & SOTG_PORTSC1_FPR) i |= UPS_C_SUSPEND; if (sc->sc_isreset) i |= UPS_C_PORT_RESET; USETW(sc->sc_hub_temp.ps.wPortChange, i); len = sizeof(sc->sc_hub_temp.ps); goto tr_valid; tr_handle_get_class_descriptor: if (value & 0xFF) goto tr_stalled; ptr = (const void *)&saf1761_otg_hubd; len = sizeof(saf1761_otg_hubd); goto tr_valid; tr_stalled: err = USB_ERR_STALLED; tr_valid: *plength = len; *pptr = ptr; return (err); } static void saf1761_otg_xfer_setup(struct usb_setup_params *parm) { struct saf1761_otg_softc *sc; struct usb_xfer *xfer; void *last_obj; uint32_t dw1; uint32_t ntd; uint32_t n; uint8_t ep_no; uint8_t ep_type; sc = SAF1761_OTG_BUS2SC(parm->udev->bus); xfer = parm->curr_xfer; /* * NOTE: This driver does not use any of the parameters that * are computed from the following values. Just set some * reasonable dummies: */ parm->hc_max_packet_size = 0x500; parm->hc_max_packet_count = 1; parm->hc_max_frame_size = 0x500; usbd_transfer_setup_sub(parm); /* * Compute maximum number of TDs: */ ep_type = (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE); if (ep_type == UE_CONTROL) { ntd = xfer->nframes + 1 /* STATUS */ + 1 /* SYNC */ ; } else { ntd = xfer->nframes + 1 /* SYNC */ ; } /* * check if "usbd_transfer_setup_sub" set an error */ if (parm->err) return; /* * allocate transfer descriptors */ last_obj = NULL; ep_no = xfer->endpointno & UE_ADDR; /* * Check profile stuff */ if (parm->udev->flags.usb_mode == USB_MODE_DEVICE) { const struct usb_hw_ep_profile *pf; saf1761_otg_get_hw_ep_profile(parm->udev, &pf, ep_no); if (pf == NULL) { /* should not happen */ parm->err = USB_ERR_INVAL; return; } } dw1 = (xfer->address << 3) | (ep_type << 12); switch (parm->udev->speed) { case USB_SPEED_FULL: case USB_SPEED_LOW: /* check if root HUB port is running High Speed */ if (parm->udev->parent_hs_hub != NULL) { dw1 |= SOTG_PTD_DW1_ENABLE_SPLIT; dw1 |= (parm->udev->hs_port_no << 18); dw1 |= (parm->udev->hs_hub_addr << 25); if (parm->udev->speed == USB_SPEED_LOW) dw1 |= (1 << 17); } break; default: break; } /* align data */ parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1)); for (n = 0; n != ntd; n++) { struct saf1761_otg_td *td; if (parm->buf) { td = USB_ADD_BYTES(parm->buf, parm->size[0]); /* init TD */ td->max_packet_size = xfer->max_packet_size; td->ep_index = ep_no; td->ep_type = ep_type; td->dw1_value = dw1; td->uframe = 0; if (ep_type == UE_INTERRUPT) { if (xfer->interval > 32) td->interval = (32 / 2) << 3; else td->interval = (xfer->interval / 2) << 3; } else { td->interval = 0; } td->obj_next = last_obj; last_obj = td; } parm->size[0] += sizeof(*td); } xfer->td_start[0] = last_obj; } static void saf1761_otg_xfer_unsetup(struct usb_xfer *xfer) { } static void saf1761_otg_ep_init(struct usb_device *udev, struct usb_endpoint_descriptor *edesc, struct usb_endpoint *ep) { uint16_t mps; DPRINTFN(2, "endpoint=%p, addr=%d, endpt=%d, mode=%d\n", ep, udev->address, edesc->bEndpointAddress, udev->flags.usb_mode); if (udev->parent_hub == NULL) { /* root HUB has special endpoint handling */ return; } /* Verify wMaxPacketSize */ mps = UGETW(edesc->wMaxPacketSize); if (udev->speed == USB_SPEED_HIGH) { if ((mps >> 11) & 3) { DPRINTF("A packet multiplier different from " "1 is not supported\n"); return; } } if (mps > SOTG_HS_MAX_PACKET_SIZE) { DPRINTF("Packet size %d bigger than %d\n", (int)mps, SOTG_HS_MAX_PACKET_SIZE); return; } if (udev->flags.usb_mode == USB_MODE_DEVICE) { if (udev->speed != USB_SPEED_FULL && udev->speed != USB_SPEED_HIGH) { /* not supported */ return; } switch (edesc->bmAttributes & UE_XFERTYPE) { case UE_ISOCHRONOUS: ep->methods = &saf1761_otg_device_isoc_methods; break; default: ep->methods = &saf1761_otg_non_isoc_methods; break; } } else { switch (edesc->bmAttributes & UE_XFERTYPE) { case UE_ISOCHRONOUS: ep->methods = &saf1761_otg_host_isoc_methods; break; default: ep->methods = &saf1761_otg_non_isoc_methods; break; } } } static void saf1761_otg_set_hw_power_sleep(struct usb_bus *bus, uint32_t state) { struct saf1761_otg_softc *sc = SAF1761_OTG_BUS2SC(bus); switch (state) { case USB_HW_POWER_SUSPEND: saf1761_otg_suspend(sc); break; case USB_HW_POWER_SHUTDOWN: saf1761_otg_uninit(sc); break; case USB_HW_POWER_RESUME: saf1761_otg_resume(sc); break; default: break; } } static void saf1761_otg_device_resume(struct usb_device *udev) { struct saf1761_otg_softc *sc; struct saf1761_otg_td *td; struct usb_xfer *xfer; uint8_t x; DPRINTF("\n"); if (udev->flags.usb_mode != USB_MODE_HOST) return; sc = SAF1761_OTG_BUS2SC(udev->bus); USB_BUS_LOCK(&sc->sc_bus); USB_BUS_SPIN_LOCK(&sc->sc_bus); TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) { if (xfer->xroot->udev != udev) continue; td = xfer->td_transfer_cache; if (td == NULL || td->channel >= SOTG_HOST_CHANNEL_MAX) continue; switch (td->ep_type) { case UE_INTERRUPT: x = td->channel - 32; sc->sc_host_intr_suspend_map &= ~(1U << x); SAF1761_WRITE_LE_4(sc, SOTG_INT_PTD_SKIP_PTD, (~sc->sc_host_intr_map) | sc->sc_host_intr_suspend_map); break; case UE_ISOCHRONOUS: x = td->channel; sc->sc_host_isoc_suspend_map &= ~(1U << x); SAF1761_WRITE_LE_4(sc, SOTG_ISO_PTD_SKIP_PTD, (~sc->sc_host_isoc_map) | sc->sc_host_isoc_suspend_map); break; default: x = td->channel - 64; sc->sc_host_async_suspend_map &= ~(1U << x); SAF1761_WRITE_LE_4(sc, SOTG_ATL_PTD_SKIP_PTD, (~sc->sc_host_async_map) | sc->sc_host_async_suspend_map); break; } } USB_BUS_SPIN_UNLOCK(&sc->sc_bus); USB_BUS_UNLOCK(&sc->sc_bus); /* poll all transfers again to restart resumed ones */ saf1761_otg_do_poll(&sc->sc_bus); } static void saf1761_otg_device_suspend(struct usb_device *udev) { struct saf1761_otg_softc *sc; struct saf1761_otg_td *td; struct usb_xfer *xfer; uint8_t x; DPRINTF("\n"); if (udev->flags.usb_mode != USB_MODE_HOST) return; sc = SAF1761_OTG_BUS2SC(udev->bus); USB_BUS_LOCK(&sc->sc_bus); USB_BUS_SPIN_LOCK(&sc->sc_bus); TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) { if (xfer->xroot->udev != udev) continue; td = xfer->td_transfer_cache; if (td == NULL || td->channel >= SOTG_HOST_CHANNEL_MAX) continue; switch (td->ep_type) { case UE_INTERRUPT: x = td->channel - 32; sc->sc_host_intr_suspend_map |= (1U << x); SAF1761_WRITE_LE_4(sc, SOTG_INT_PTD_SKIP_PTD, (~sc->sc_host_intr_map) | sc->sc_host_intr_suspend_map); break; case UE_ISOCHRONOUS: x = td->channel; sc->sc_host_isoc_suspend_map |= (1U << x); SAF1761_WRITE_LE_4(sc, SOTG_ISO_PTD_SKIP_PTD, (~sc->sc_host_isoc_map) | sc->sc_host_isoc_suspend_map); break; default: x = td->channel - 64; sc->sc_host_async_suspend_map |= (1U << x); SAF1761_WRITE_LE_4(sc, SOTG_ATL_PTD_SKIP_PTD, (~sc->sc_host_async_map) | sc->sc_host_async_suspend_map); break; } } USB_BUS_SPIN_UNLOCK(&sc->sc_bus); USB_BUS_UNLOCK(&sc->sc_bus); } static const struct usb_bus_methods saf1761_otg_bus_methods = { .endpoint_init = &saf1761_otg_ep_init, .xfer_setup = &saf1761_otg_xfer_setup, .xfer_unsetup = &saf1761_otg_xfer_unsetup, .get_hw_ep_profile = &saf1761_otg_get_hw_ep_profile, .xfer_stall = &saf1761_otg_xfer_stall, .set_stall = &saf1761_otg_set_stall, .clear_stall = &saf1761_otg_clear_stall, .roothub_exec = &saf1761_otg_roothub_exec, .xfer_poll = &saf1761_otg_do_poll, .set_hw_power_sleep = saf1761_otg_set_hw_power_sleep, .device_resume = &saf1761_otg_device_resume, .device_suspend = &saf1761_otg_device_suspend, }; Index: head/sys/dev/usb/controller/usb_controller.c =================================================================== --- head/sys/dev/usb/controller/usb_controller.c (revision 276700) +++ head/sys/dev/usb/controller/usb_controller.c (revision 276701) @@ -1,990 +1,990 @@ /* $FreeBSD$ */ /*- * Copyright (c) 2008 Hans Petter Selasky. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifdef USB_GLOBAL_INCLUDE_FILE #include USB_GLOBAL_INCLUDE_FILE #else #include "opt_ddb.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define USB_DEBUG_VAR usb_ctrl_debug #include #include #include #include #include #include #include #include #include #include #include "usb_if.h" #endif /* USB_GLOBAL_INCLUDE_FILE */ /* function prototypes */ static device_probe_t usb_probe; static device_attach_t usb_attach; static device_detach_t usb_detach; static device_suspend_t usb_suspend; static device_resume_t usb_resume; static device_shutdown_t usb_shutdown; static void usb_attach_sub(device_t, struct usb_bus *); /* static variables */ #ifdef USB_DEBUG static int usb_ctrl_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, ctrl, CTLFLAG_RW, 0, "USB controller"); -SYSCTL_INT(_hw_usb_ctrl, OID_AUTO, debug, CTLFLAG_RW, &usb_ctrl_debug, 0, +SYSCTL_INT(_hw_usb_ctrl, OID_AUTO, debug, CTLFLAG_RWTUN, &usb_ctrl_debug, 0, "Debug level"); #endif #if USB_HAVE_ROOT_MOUNT_HOLD static int usb_no_boot_wait = 0; SYSCTL_INT(_hw_usb, OID_AUTO, no_boot_wait, CTLFLAG_RDTUN, &usb_no_boot_wait, 0, "No USB device enumerate waiting at boot."); #endif static int usb_no_suspend_wait = 0; SYSCTL_INT(_hw_usb, OID_AUTO, no_suspend_wait, CTLFLAG_RWTUN, &usb_no_suspend_wait, 0, "No USB device waiting at system suspend."); static int usb_no_shutdown_wait = 0; SYSCTL_INT(_hw_usb, OID_AUTO, no_shutdown_wait, CTLFLAG_RWTUN, &usb_no_shutdown_wait, 0, "No USB device waiting at system shutdown."); static devclass_t usb_devclass; static device_method_t usb_methods[] = { DEVMETHOD(device_probe, usb_probe), DEVMETHOD(device_attach, usb_attach), DEVMETHOD(device_detach, usb_detach), DEVMETHOD(device_suspend, usb_suspend), DEVMETHOD(device_resume, usb_resume), DEVMETHOD(device_shutdown, usb_shutdown), DEVMETHOD_END }; static driver_t usb_driver = { .name = "usbus", .methods = usb_methods, .size = 0, }; /* Host Only Drivers */ DRIVER_MODULE(usbus, ohci, usb_driver, usb_devclass, 0, 0); DRIVER_MODULE(usbus, uhci, usb_driver, usb_devclass, 0, 0); DRIVER_MODULE(usbus, ehci, usb_driver, usb_devclass, 0, 0); DRIVER_MODULE(usbus, xhci, usb_driver, usb_devclass, 0, 0); /* Device Only Drivers */ DRIVER_MODULE(usbus, at91_udp, usb_driver, usb_devclass, 0, 0); DRIVER_MODULE(usbus, musbotg, usb_driver, usb_devclass, 0, 0); DRIVER_MODULE(usbus, uss820dci, usb_driver, usb_devclass, 0, 0); DRIVER_MODULE(usbus, octusb, usb_driver, usb_devclass, 0, 0); /* Dual Mode Drivers */ DRIVER_MODULE(usbus, dwcotg, usb_driver, usb_devclass, 0, 0); DRIVER_MODULE(usbus, saf1761otg, usb_driver, usb_devclass, 0, 0); /*------------------------------------------------------------------------* * usb_probe * * This function is called from "{ehci,ohci,uhci}_pci_attach()". *------------------------------------------------------------------------*/ static int usb_probe(device_t dev) { DPRINTF("\n"); return (0); } #if USB_HAVE_ROOT_MOUNT_HOLD static void usb_root_mount_rel(struct usb_bus *bus) { if (bus->bus_roothold != NULL) { DPRINTF("Releasing root mount hold %p\n", bus->bus_roothold); root_mount_rel(bus->bus_roothold); bus->bus_roothold = NULL; } } #endif /*------------------------------------------------------------------------* * usb_attach *------------------------------------------------------------------------*/ static int usb_attach(device_t dev) { struct usb_bus *bus = device_get_ivars(dev); DPRINTF("\n"); if (bus == NULL) { device_printf(dev, "USB device has no ivars\n"); return (ENXIO); } #if USB_HAVE_ROOT_MOUNT_HOLD if (usb_no_boot_wait == 0) { /* delay vfs_mountroot until the bus is explored */ bus->bus_roothold = root_mount_hold(device_get_nameunit(dev)); } #endif usb_attach_sub(dev, bus); return (0); /* return success */ } /*------------------------------------------------------------------------* * usb_detach *------------------------------------------------------------------------*/ static int usb_detach(device_t dev) { struct usb_bus *bus = device_get_softc(dev); DPRINTF("\n"); if (bus == NULL) { /* was never setup properly */ return (0); } /* Stop power watchdog */ usb_callout_drain(&bus->power_wdog); #if USB_HAVE_ROOT_MOUNT_HOLD /* Let the USB explore process detach all devices. */ usb_root_mount_rel(bus); #endif USB_BUS_LOCK(bus); /* Queue detach job */ usb_proc_msignal(USB_BUS_EXPLORE_PROC(bus), &bus->detach_msg[0], &bus->detach_msg[1]); /* Wait for detach to complete */ usb_proc_mwait(USB_BUS_EXPLORE_PROC(bus), &bus->detach_msg[0], &bus->detach_msg[1]); USB_BUS_UNLOCK(bus); #if USB_HAVE_PER_BUS_PROCESS /* Get rid of USB callback processes */ usb_proc_free(USB_BUS_GIANT_PROC(bus)); usb_proc_free(USB_BUS_NON_GIANT_PROC(bus)); /* Get rid of USB explore process */ usb_proc_free(USB_BUS_EXPLORE_PROC(bus)); /* Get rid of control transfer process */ usb_proc_free(USB_BUS_CONTROL_XFER_PROC(bus)); #endif #if USB_HAVE_PF usbpf_detach(bus); #endif return (0); } /*------------------------------------------------------------------------* * usb_suspend *------------------------------------------------------------------------*/ static int usb_suspend(device_t dev) { struct usb_bus *bus = device_get_softc(dev); DPRINTF("\n"); if (bus == NULL) { /* was never setup properly */ return (0); } USB_BUS_LOCK(bus); usb_proc_msignal(USB_BUS_EXPLORE_PROC(bus), &bus->suspend_msg[0], &bus->suspend_msg[1]); if (usb_no_suspend_wait == 0) { /* wait for suspend callback to be executed */ usb_proc_mwait(USB_BUS_EXPLORE_PROC(bus), &bus->suspend_msg[0], &bus->suspend_msg[1]); } USB_BUS_UNLOCK(bus); return (0); } /*------------------------------------------------------------------------* * usb_resume *------------------------------------------------------------------------*/ static int usb_resume(device_t dev) { struct usb_bus *bus = device_get_softc(dev); DPRINTF("\n"); if (bus == NULL) { /* was never setup properly */ return (0); } USB_BUS_LOCK(bus); usb_proc_msignal(USB_BUS_EXPLORE_PROC(bus), &bus->resume_msg[0], &bus->resume_msg[1]); USB_BUS_UNLOCK(bus); return (0); } /*------------------------------------------------------------------------* * usb_bus_reset_async_locked *------------------------------------------------------------------------*/ void usb_bus_reset_async_locked(struct usb_bus *bus) { USB_BUS_LOCK_ASSERT(bus, MA_OWNED); DPRINTF("\n"); if (bus->reset_msg[0].hdr.pm_qentry.tqe_prev != NULL || bus->reset_msg[1].hdr.pm_qentry.tqe_prev != NULL) { DPRINTF("Reset already pending\n"); return; } device_printf(bus->parent, "Resetting controller\n"); usb_proc_msignal(USB_BUS_EXPLORE_PROC(bus), &bus->reset_msg[0], &bus->reset_msg[1]); } /*------------------------------------------------------------------------* * usb_shutdown *------------------------------------------------------------------------*/ static int usb_shutdown(device_t dev) { struct usb_bus *bus = device_get_softc(dev); DPRINTF("\n"); if (bus == NULL) { /* was never setup properly */ return (0); } DPRINTF("%s: Controller shutdown\n", device_get_nameunit(bus->bdev)); USB_BUS_LOCK(bus); usb_proc_msignal(USB_BUS_EXPLORE_PROC(bus), &bus->shutdown_msg[0], &bus->shutdown_msg[1]); if (usb_no_shutdown_wait == 0) { /* wait for shutdown callback to be executed */ usb_proc_mwait(USB_BUS_EXPLORE_PROC(bus), &bus->shutdown_msg[0], &bus->shutdown_msg[1]); } USB_BUS_UNLOCK(bus); DPRINTF("%s: Controller shutdown complete\n", device_get_nameunit(bus->bdev)); return (0); } /*------------------------------------------------------------------------* * usb_bus_explore * * This function is used to explore the device tree from the root. *------------------------------------------------------------------------*/ static void usb_bus_explore(struct usb_proc_msg *pm) { struct usb_bus *bus; struct usb_device *udev; bus = ((struct usb_bus_msg *)pm)->bus; udev = bus->devices[USB_ROOT_HUB_ADDR]; if (bus->no_explore != 0) return; if (udev != NULL) { USB_BUS_UNLOCK(bus); uhub_explore_handle_re_enumerate(udev); USB_BUS_LOCK(bus); } if (udev != NULL && udev->hub != NULL) { if (bus->do_probe) { bus->do_probe = 0; bus->driver_added_refcount++; } if (bus->driver_added_refcount == 0) { /* avoid zero, hence that is memory default */ bus->driver_added_refcount = 1; } #ifdef DDB /* * The following three lines of code are only here to * recover from DDB: */ usb_proc_rewakeup(USB_BUS_CONTROL_XFER_PROC(bus)); usb_proc_rewakeup(USB_BUS_GIANT_PROC(bus)); usb_proc_rewakeup(USB_BUS_NON_GIANT_PROC(bus)); #endif USB_BUS_UNLOCK(bus); #if USB_HAVE_POWERD /* * First update the USB power state! */ usb_bus_powerd(bus); #endif /* Explore the Root USB HUB. */ (udev->hub->explore) (udev); USB_BUS_LOCK(bus); } #if USB_HAVE_ROOT_MOUNT_HOLD usb_root_mount_rel(bus); #endif } /*------------------------------------------------------------------------* * usb_bus_detach * * This function is used to detach the device tree from the root. *------------------------------------------------------------------------*/ static void usb_bus_detach(struct usb_proc_msg *pm) { struct usb_bus *bus; struct usb_device *udev; device_t dev; bus = ((struct usb_bus_msg *)pm)->bus; udev = bus->devices[USB_ROOT_HUB_ADDR]; dev = bus->bdev; /* clear the softc */ device_set_softc(dev, NULL); USB_BUS_UNLOCK(bus); /* detach children first */ mtx_lock(&Giant); bus_generic_detach(dev); mtx_unlock(&Giant); /* * Free USB device and all subdevices, if any. */ usb_free_device(udev, 0); USB_BUS_LOCK(bus); /* clear bdev variable last */ bus->bdev = NULL; } /*------------------------------------------------------------------------* * usb_bus_suspend * * This function is used to suspend the USB controller. *------------------------------------------------------------------------*/ static void usb_bus_suspend(struct usb_proc_msg *pm) { struct usb_bus *bus; struct usb_device *udev; usb_error_t err; uint8_t do_unlock; DPRINTF("\n"); bus = ((struct usb_bus_msg *)pm)->bus; udev = bus->devices[USB_ROOT_HUB_ADDR]; if (udev == NULL || bus->bdev == NULL) return; USB_BUS_UNLOCK(bus); /* * We use the shutdown event here because the suspend and * resume events are reserved for the USB port suspend and * resume. The USB system suspend is implemented like full * shutdown and all connected USB devices will be disconnected * subsequently. At resume all USB devices will be * re-connected again. */ bus_generic_shutdown(bus->bdev); do_unlock = usbd_enum_lock(udev); err = usbd_set_config_index(udev, USB_UNCONFIG_INDEX); if (err) device_printf(bus->bdev, "Could not unconfigure root HUB\n"); USB_BUS_LOCK(bus); bus->hw_power_state = 0; bus->no_explore = 1; USB_BUS_UNLOCK(bus); if (bus->methods->set_hw_power != NULL) (bus->methods->set_hw_power) (bus); if (bus->methods->set_hw_power_sleep != NULL) (bus->methods->set_hw_power_sleep) (bus, USB_HW_POWER_SUSPEND); if (do_unlock) usbd_enum_unlock(udev); USB_BUS_LOCK(bus); } /*------------------------------------------------------------------------* * usb_bus_resume * * This function is used to resume the USB controller. *------------------------------------------------------------------------*/ static void usb_bus_resume(struct usb_proc_msg *pm) { struct usb_bus *bus; struct usb_device *udev; usb_error_t err; uint8_t do_unlock; DPRINTF("\n"); bus = ((struct usb_bus_msg *)pm)->bus; udev = bus->devices[USB_ROOT_HUB_ADDR]; if (udev == NULL || bus->bdev == NULL) return; USB_BUS_UNLOCK(bus); do_unlock = usbd_enum_lock(udev); #if 0 DEVMETHOD(usb_take_controller, NULL); /* dummy */ #endif USB_TAKE_CONTROLLER(device_get_parent(bus->bdev)); USB_BUS_LOCK(bus); bus->hw_power_state = USB_HW_POWER_CONTROL | USB_HW_POWER_BULK | USB_HW_POWER_INTERRUPT | USB_HW_POWER_ISOC | USB_HW_POWER_NON_ROOT_HUB; bus->no_explore = 0; USB_BUS_UNLOCK(bus); if (bus->methods->set_hw_power_sleep != NULL) (bus->methods->set_hw_power_sleep) (bus, USB_HW_POWER_RESUME); if (bus->methods->set_hw_power != NULL) (bus->methods->set_hw_power) (bus); /* restore USB configuration to index 0 */ err = usbd_set_config_index(udev, 0); if (err) device_printf(bus->bdev, "Could not configure root HUB\n"); /* probe and attach */ err = usb_probe_and_attach(udev, USB_IFACE_INDEX_ANY); if (err) { device_printf(bus->bdev, "Could not probe and " "attach root HUB\n"); } if (do_unlock) usbd_enum_unlock(udev); USB_BUS_LOCK(bus); } /*------------------------------------------------------------------------* * usb_bus_reset * * This function is used to reset the USB controller. *------------------------------------------------------------------------*/ static void usb_bus_reset(struct usb_proc_msg *pm) { struct usb_bus *bus; DPRINTF("\n"); bus = ((struct usb_bus_msg *)pm)->bus; if (bus->bdev == NULL || bus->no_explore != 0) return; /* a suspend and resume will reset the USB controller */ usb_bus_suspend(pm); usb_bus_resume(pm); } /*------------------------------------------------------------------------* * usb_bus_shutdown * * This function is used to shutdown the USB controller. *------------------------------------------------------------------------*/ static void usb_bus_shutdown(struct usb_proc_msg *pm) { struct usb_bus *bus; struct usb_device *udev; usb_error_t err; uint8_t do_unlock; bus = ((struct usb_bus_msg *)pm)->bus; udev = bus->devices[USB_ROOT_HUB_ADDR]; if (udev == NULL || bus->bdev == NULL) return; USB_BUS_UNLOCK(bus); bus_generic_shutdown(bus->bdev); do_unlock = usbd_enum_lock(udev); err = usbd_set_config_index(udev, USB_UNCONFIG_INDEX); if (err) device_printf(bus->bdev, "Could not unconfigure root HUB\n"); USB_BUS_LOCK(bus); bus->hw_power_state = 0; bus->no_explore = 1; USB_BUS_UNLOCK(bus); if (bus->methods->set_hw_power != NULL) (bus->methods->set_hw_power) (bus); if (bus->methods->set_hw_power_sleep != NULL) (bus->methods->set_hw_power_sleep) (bus, USB_HW_POWER_SHUTDOWN); if (do_unlock) usbd_enum_unlock(udev); USB_BUS_LOCK(bus); } static void usb_power_wdog(void *arg) { struct usb_bus *bus = arg; USB_BUS_LOCK_ASSERT(bus, MA_OWNED); usb_callout_reset(&bus->power_wdog, 4 * hz, usb_power_wdog, arg); #ifdef DDB /* * The following line of code is only here to recover from * DDB: */ usb_proc_rewakeup(USB_BUS_EXPLORE_PROC(bus)); /* recover from DDB */ #endif #if USB_HAVE_POWERD USB_BUS_UNLOCK(bus); usb_bus_power_update(bus); USB_BUS_LOCK(bus); #endif } /*------------------------------------------------------------------------* * usb_bus_attach * * This function attaches USB in context of the explore thread. *------------------------------------------------------------------------*/ static void usb_bus_attach(struct usb_proc_msg *pm) { struct usb_bus *bus; struct usb_device *child; device_t dev; usb_error_t err; enum usb_dev_speed speed; bus = ((struct usb_bus_msg *)pm)->bus; dev = bus->bdev; DPRINTF("\n"); switch (bus->usbrev) { case USB_REV_1_0: speed = USB_SPEED_FULL; device_printf(bus->bdev, "12Mbps Full Speed USB v1.0\n"); break; case USB_REV_1_1: speed = USB_SPEED_FULL; device_printf(bus->bdev, "12Mbps Full Speed USB v1.1\n"); break; case USB_REV_2_0: speed = USB_SPEED_HIGH; device_printf(bus->bdev, "480Mbps High Speed USB v2.0\n"); break; case USB_REV_2_5: speed = USB_SPEED_VARIABLE; device_printf(bus->bdev, "480Mbps Wireless USB v2.5\n"); break; case USB_REV_3_0: speed = USB_SPEED_SUPER; device_printf(bus->bdev, "5.0Gbps Super Speed USB v3.0\n"); break; default: device_printf(bus->bdev, "Unsupported USB revision\n"); #if USB_HAVE_ROOT_MOUNT_HOLD usb_root_mount_rel(bus); #endif return; } /* default power_mask value */ bus->hw_power_state = USB_HW_POWER_CONTROL | USB_HW_POWER_BULK | USB_HW_POWER_INTERRUPT | USB_HW_POWER_ISOC | USB_HW_POWER_NON_ROOT_HUB; USB_BUS_UNLOCK(bus); /* make sure power is set at least once */ if (bus->methods->set_hw_power != NULL) { (bus->methods->set_hw_power) (bus); } /* allocate the Root USB device */ child = usb_alloc_device(bus->bdev, bus, NULL, 0, 0, 1, speed, USB_MODE_HOST); if (child) { err = usb_probe_and_attach(child, USB_IFACE_INDEX_ANY); if (!err) { if ((bus->devices[USB_ROOT_HUB_ADDR] == NULL) || (bus->devices[USB_ROOT_HUB_ADDR]->hub == NULL)) { err = USB_ERR_NO_ROOT_HUB; } } } else { err = USB_ERR_NOMEM; } USB_BUS_LOCK(bus); if (err) { device_printf(bus->bdev, "Root HUB problem, error=%s\n", usbd_errstr(err)); #if USB_HAVE_ROOT_MOUNT_HOLD usb_root_mount_rel(bus); #endif } /* set softc - we are ready */ device_set_softc(dev, bus); /* start watchdog */ usb_power_wdog(bus); } /*------------------------------------------------------------------------* * usb_attach_sub * * This function creates a thread which runs the USB attach code. *------------------------------------------------------------------------*/ static void usb_attach_sub(device_t dev, struct usb_bus *bus) { mtx_lock(&Giant); if (usb_devclass_ptr == NULL) usb_devclass_ptr = devclass_find("usbus"); mtx_unlock(&Giant); #if USB_HAVE_PF usbpf_attach(bus); #endif /* Initialise USB process messages */ bus->explore_msg[0].hdr.pm_callback = &usb_bus_explore; bus->explore_msg[0].bus = bus; bus->explore_msg[1].hdr.pm_callback = &usb_bus_explore; bus->explore_msg[1].bus = bus; bus->detach_msg[0].hdr.pm_callback = &usb_bus_detach; bus->detach_msg[0].bus = bus; bus->detach_msg[1].hdr.pm_callback = &usb_bus_detach; bus->detach_msg[1].bus = bus; bus->attach_msg[0].hdr.pm_callback = &usb_bus_attach; bus->attach_msg[0].bus = bus; bus->attach_msg[1].hdr.pm_callback = &usb_bus_attach; bus->attach_msg[1].bus = bus; bus->suspend_msg[0].hdr.pm_callback = &usb_bus_suspend; bus->suspend_msg[0].bus = bus; bus->suspend_msg[1].hdr.pm_callback = &usb_bus_suspend; bus->suspend_msg[1].bus = bus; bus->resume_msg[0].hdr.pm_callback = &usb_bus_resume; bus->resume_msg[0].bus = bus; bus->resume_msg[1].hdr.pm_callback = &usb_bus_resume; bus->resume_msg[1].bus = bus; bus->reset_msg[0].hdr.pm_callback = &usb_bus_reset; bus->reset_msg[0].bus = bus; bus->reset_msg[1].hdr.pm_callback = &usb_bus_reset; bus->reset_msg[1].bus = bus; bus->shutdown_msg[0].hdr.pm_callback = &usb_bus_shutdown; bus->shutdown_msg[0].bus = bus; bus->shutdown_msg[1].hdr.pm_callback = &usb_bus_shutdown; bus->shutdown_msg[1].bus = bus; #if USB_HAVE_PER_BUS_PROCESS /* Create USB explore and callback processes */ if (usb_proc_create(USB_BUS_GIANT_PROC(bus), &bus->bus_mtx, device_get_nameunit(dev), USB_PRI_MED)) { device_printf(dev, "WARNING: Creation of USB Giant " "callback process failed.\n"); } else if (usb_proc_create(USB_BUS_NON_GIANT_PROC(bus), &bus->bus_mtx, device_get_nameunit(dev), USB_PRI_HIGH)) { device_printf(dev, "WARNING: Creation of USB non-Giant " "callback process failed.\n"); } else if (usb_proc_create(USB_BUS_EXPLORE_PROC(bus), &bus->bus_mtx, device_get_nameunit(dev), USB_PRI_MED)) { device_printf(dev, "WARNING: Creation of USB explore " "process failed.\n"); } else if (usb_proc_create(USB_BUS_CONTROL_XFER_PROC(bus), &bus->bus_mtx, device_get_nameunit(dev), USB_PRI_MED)) { device_printf(dev, "WARNING: Creation of USB control transfer " "process failed.\n"); } else #endif { /* Get final attach going */ USB_BUS_LOCK(bus); usb_proc_msignal(USB_BUS_EXPLORE_PROC(bus), &bus->attach_msg[0], &bus->attach_msg[1]); USB_BUS_UNLOCK(bus); /* Do initial explore */ usb_needs_explore(bus, 1); } } SYSUNINIT(usb_bus_unload, SI_SUB_KLD, SI_ORDER_ANY, usb_bus_unload, NULL); /*------------------------------------------------------------------------* * usb_bus_mem_flush_all_cb *------------------------------------------------------------------------*/ #if USB_HAVE_BUSDMA static void usb_bus_mem_flush_all_cb(struct usb_bus *bus, struct usb_page_cache *pc, struct usb_page *pg, usb_size_t size, usb_size_t align) { usb_pc_cpu_flush(pc); } #endif /*------------------------------------------------------------------------* * usb_bus_mem_flush_all - factored out code *------------------------------------------------------------------------*/ #if USB_HAVE_BUSDMA void usb_bus_mem_flush_all(struct usb_bus *bus, usb_bus_mem_cb_t *cb) { if (cb) { cb(bus, &usb_bus_mem_flush_all_cb); } } #endif /*------------------------------------------------------------------------* * usb_bus_mem_alloc_all_cb *------------------------------------------------------------------------*/ #if USB_HAVE_BUSDMA static void usb_bus_mem_alloc_all_cb(struct usb_bus *bus, struct usb_page_cache *pc, struct usb_page *pg, usb_size_t size, usb_size_t align) { /* need to initialize the page cache */ pc->tag_parent = bus->dma_parent_tag; if (usb_pc_alloc_mem(pc, pg, size, align)) { bus->alloc_failed = 1; } } #endif /*------------------------------------------------------------------------* * usb_bus_mem_alloc_all - factored out code * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ uint8_t usb_bus_mem_alloc_all(struct usb_bus *bus, bus_dma_tag_t dmat, usb_bus_mem_cb_t *cb) { bus->alloc_failed = 0; mtx_init(&bus->bus_mtx, device_get_nameunit(bus->parent), "usb_def_mtx", MTX_DEF | MTX_RECURSE); mtx_init(&bus->bus_spin_lock, device_get_nameunit(bus->parent), "usb_spin_mtx", MTX_SPIN | MTX_RECURSE); usb_callout_init_mtx(&bus->power_wdog, &bus->bus_mtx, 0); TAILQ_INIT(&bus->intr_q.head); #if USB_HAVE_BUSDMA usb_dma_tag_setup(bus->dma_parent_tag, bus->dma_tags, dmat, &bus->bus_mtx, NULL, 32, USB_BUS_DMA_TAG_MAX); #endif if ((bus->devices_max > USB_MAX_DEVICES) || (bus->devices_max < USB_MIN_DEVICES) || (bus->devices == NULL)) { DPRINTFN(0, "Devices field has not been " "initialised properly\n"); bus->alloc_failed = 1; /* failure */ } #if USB_HAVE_BUSDMA if (cb) { cb(bus, &usb_bus_mem_alloc_all_cb); } #endif if (bus->alloc_failed) { usb_bus_mem_free_all(bus, cb); } return (bus->alloc_failed); } /*------------------------------------------------------------------------* * usb_bus_mem_free_all_cb *------------------------------------------------------------------------*/ #if USB_HAVE_BUSDMA static void usb_bus_mem_free_all_cb(struct usb_bus *bus, struct usb_page_cache *pc, struct usb_page *pg, usb_size_t size, usb_size_t align) { usb_pc_free_mem(pc); } #endif /*------------------------------------------------------------------------* * usb_bus_mem_free_all - factored out code *------------------------------------------------------------------------*/ void usb_bus_mem_free_all(struct usb_bus *bus, usb_bus_mem_cb_t *cb) { #if USB_HAVE_BUSDMA if (cb) { cb(bus, &usb_bus_mem_free_all_cb); } usb_dma_tag_unsetup(bus->dma_parent_tag); #endif mtx_destroy(&bus->bus_mtx); mtx_destroy(&bus->bus_spin_lock); } /* convenience wrappers */ void usb_proc_explore_mwait(struct usb_device *udev, void *pm1, void *pm2) { usb_proc_mwait(USB_BUS_EXPLORE_PROC(udev->bus), pm1, pm2); } void * usb_proc_explore_msignal(struct usb_device *udev, void *pm1, void *pm2) { return (usb_proc_msignal(USB_BUS_EXPLORE_PROC(udev->bus), pm1, pm2)); } void usb_proc_explore_lock(struct usb_device *udev) { USB_BUS_LOCK(udev->bus); } void usb_proc_explore_unlock(struct usb_device *udev) { USB_BUS_UNLOCK(udev->bus); } Index: head/sys/dev/usb/controller/uss820dci.c =================================================================== --- head/sys/dev/usb/controller/uss820dci.c (revision 276700) +++ head/sys/dev/usb/controller/uss820dci.c (revision 276701) @@ -1,2446 +1,2446 @@ /* $FreeBSD$ */ /*- * Copyright (c) 2008 Hans Petter Selasky * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * This file contains the driver for the USS820 series USB Device * Controller * * NOTE: The datasheet does not document everything. */ #ifdef USB_GLOBAL_INCLUDE_FILE #include USB_GLOBAL_INCLUDE_FILE #else #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define USB_DEBUG_VAR uss820dcidebug #include #include #include #include #include #include #include #include #include #include #endif /* USB_GLOBAL_INCLUDE_FILE */ #include #define USS820_DCI_BUS2SC(bus) \ ((struct uss820dci_softc *)(((uint8_t *)(bus)) - \ ((uint8_t *)&(((struct uss820dci_softc *)0)->sc_bus)))) #define USS820_DCI_PC2SC(pc) \ USS820_DCI_BUS2SC(USB_DMATAG_TO_XROOT((pc)->tag_parent)->bus) #define USS820_DCI_THREAD_IRQ \ (USS820_SSR_SUSPEND | USS820_SSR_RESUME | USS820_SSR_RESET) #ifdef USB_DEBUG static int uss820dcidebug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, uss820dci, CTLFLAG_RW, 0, "USB uss820dci"); -SYSCTL_INT(_hw_usb_uss820dci, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_uss820dci, OID_AUTO, debug, CTLFLAG_RWTUN, &uss820dcidebug, 0, "uss820dci debug level"); #endif #define USS820_DCI_INTR_ENDPT 1 /* prototypes */ static const struct usb_bus_methods uss820dci_bus_methods; static const struct usb_pipe_methods uss820dci_device_bulk_methods; static const struct usb_pipe_methods uss820dci_device_ctrl_methods; static const struct usb_pipe_methods uss820dci_device_intr_methods; static const struct usb_pipe_methods uss820dci_device_isoc_fs_methods; static uss820dci_cmd_t uss820dci_setup_rx; static uss820dci_cmd_t uss820dci_data_rx; static uss820dci_cmd_t uss820dci_data_tx; static uss820dci_cmd_t uss820dci_data_tx_sync; static void uss820dci_device_done(struct usb_xfer *, usb_error_t); static void uss820dci_do_poll(struct usb_bus *); static void uss820dci_standard_done(struct usb_xfer *); static void uss820dci_intr_set(struct usb_xfer *, uint8_t); static void uss820dci_update_shared_1(struct uss820dci_softc *, uint8_t, uint8_t, uint8_t); static void uss820dci_root_intr(struct uss820dci_softc *); /* * Here is a list of what the USS820D chip can support. The main * limitation is that the sum of the buffer sizes must be less than * 1120 bytes. */ static const struct usb_hw_ep_profile uss820dci_ep_profile[] = { [0] = { .max_in_frame_size = 32, .max_out_frame_size = 32, .is_simplex = 0, .support_control = 1, }, [1] = { .max_in_frame_size = 64, .max_out_frame_size = 64, .is_simplex = 0, .support_multi_buffer = 1, .support_bulk = 1, .support_interrupt = 1, .support_in = 1, .support_out = 1, }, [2] = { .max_in_frame_size = 8, .max_out_frame_size = 8, .is_simplex = 0, .support_multi_buffer = 1, .support_bulk = 1, .support_interrupt = 1, .support_in = 1, .support_out = 1, }, [3] = { .max_in_frame_size = 256, .max_out_frame_size = 256, .is_simplex = 0, .support_multi_buffer = 1, .support_isochronous = 1, .support_in = 1, .support_out = 1, }, }; static void uss820dci_update_shared_1(struct uss820dci_softc *sc, uint8_t reg, uint8_t keep_mask, uint8_t set_mask) { uint8_t temp; USS820_WRITE_1(sc, USS820_PEND, 1); temp = USS820_READ_1(sc, reg); temp &= (keep_mask); temp |= (set_mask); USS820_WRITE_1(sc, reg, temp); USS820_WRITE_1(sc, USS820_PEND, 0); } static void uss820dci_get_hw_ep_profile(struct usb_device *udev, const struct usb_hw_ep_profile **ppf, uint8_t ep_addr) { if (ep_addr == 0) { *ppf = uss820dci_ep_profile + 0; } else if (ep_addr < 5) { *ppf = uss820dci_ep_profile + 1; } else if (ep_addr < 7) { *ppf = uss820dci_ep_profile + 2; } else if (ep_addr == 7) { *ppf = uss820dci_ep_profile + 3; } else { *ppf = NULL; } } static void uss820dci_pull_up(struct uss820dci_softc *sc) { uint8_t temp; /* pullup D+, if possible */ if (!sc->sc_flags.d_pulled_up && sc->sc_flags.port_powered) { sc->sc_flags.d_pulled_up = 1; DPRINTF("\n"); temp = USS820_READ_1(sc, USS820_MCSR); temp |= USS820_MCSR_DPEN; USS820_WRITE_1(sc, USS820_MCSR, temp); } } static void uss820dci_pull_down(struct uss820dci_softc *sc) { uint8_t temp; /* pulldown D+, if possible */ if (sc->sc_flags.d_pulled_up) { sc->sc_flags.d_pulled_up = 0; DPRINTF("\n"); temp = USS820_READ_1(sc, USS820_MCSR); temp &= ~USS820_MCSR_DPEN; USS820_WRITE_1(sc, USS820_MCSR, temp); } } static void uss820dci_wakeup_peer(struct uss820dci_softc *sc) { if (!(sc->sc_flags.status_suspend)) { return; } DPRINTFN(0, "not supported\n"); } static void uss820dci_set_address(struct uss820dci_softc *sc, uint8_t addr) { DPRINTFN(5, "addr=%d\n", addr); USS820_WRITE_1(sc, USS820_FADDR, addr); } static uint8_t uss820dci_setup_rx(struct uss820dci_softc *sc, struct uss820dci_td *td) { struct usb_device_request req; uint16_t count; uint8_t rx_stat; uint8_t temp; /* select the correct endpoint */ USS820_WRITE_1(sc, USS820_EPINDEX, td->ep_index); /* read out FIFO status */ rx_stat = USS820_READ_1(sc, USS820_RXSTAT); DPRINTFN(5, "rx_stat=0x%02x rem=%u\n", rx_stat, td->remainder); if (!(rx_stat & USS820_RXSTAT_RXSETUP)) { goto not_complete; } /* clear did stall */ td->did_stall = 0; /* clear stall and all I/O */ uss820dci_update_shared_1(sc, USS820_EPCON, 0xFF ^ (USS820_EPCON_TXSTL | USS820_EPCON_RXSTL | USS820_EPCON_RXIE | USS820_EPCON_TXOE), 0); /* clear end overwrite flag */ uss820dci_update_shared_1(sc, USS820_RXSTAT, 0xFF ^ USS820_RXSTAT_EDOVW, 0); /* get the packet byte count */ count = USS820_READ_1(sc, USS820_RXCNTL); count |= (USS820_READ_1(sc, USS820_RXCNTH) << 8); count &= 0x3FF; /* verify data length */ if (count != td->remainder) { DPRINTFN(0, "Invalid SETUP packet " "length, %d bytes\n", count); goto setup_not_complete; } if (count != sizeof(req)) { DPRINTFN(0, "Unsupported SETUP packet " "length, %d bytes\n", count); goto setup_not_complete; } /* receive data */ bus_space_read_multi_1(sc->sc_io_tag, sc->sc_io_hdl, USS820_RXDAT * USS820_REG_STRIDE, (void *)&req, sizeof(req)); /* read out FIFO status */ rx_stat = USS820_READ_1(sc, USS820_RXSTAT); if (rx_stat & (USS820_RXSTAT_EDOVW | USS820_RXSTAT_STOVW)) { DPRINTF("new SETUP packet received\n"); return (1); /* not complete */ } /* clear receive setup bit */ uss820dci_update_shared_1(sc, USS820_RXSTAT, 0xFF ^ (USS820_RXSTAT_RXSETUP | USS820_RXSTAT_EDOVW | USS820_RXSTAT_STOVW), 0); /* set RXFFRC bit */ temp = USS820_READ_1(sc, USS820_RXCON); temp |= USS820_RXCON_RXFFRC; USS820_WRITE_1(sc, USS820_RXCON, temp); /* copy data into real buffer */ usbd_copy_in(td->pc, 0, &req, sizeof(req)); td->offset = sizeof(req); td->remainder = 0; /* sneak peek the set address */ if ((req.bmRequestType == UT_WRITE_DEVICE) && (req.bRequest == UR_SET_ADDRESS)) { sc->sc_dv_addr = req.wValue[0] & 0x7F; } else { sc->sc_dv_addr = 0xFF; } /* reset TX FIFO */ temp = USS820_READ_1(sc, USS820_TXCON); temp |= USS820_TXCON_TXCLR; USS820_WRITE_1(sc, USS820_TXCON, temp); temp &= ~USS820_TXCON_TXCLR; USS820_WRITE_1(sc, USS820_TXCON, temp); return (0); /* complete */ setup_not_complete: /* set RXFFRC bit */ temp = USS820_READ_1(sc, USS820_RXCON); temp |= USS820_RXCON_RXFFRC; USS820_WRITE_1(sc, USS820_RXCON, temp); /* FALLTHROUGH */ not_complete: /* abort any ongoing transfer */ if (!td->did_stall) { DPRINTFN(5, "stalling\n"); /* set stall */ uss820dci_update_shared_1(sc, USS820_EPCON, 0xFF, (USS820_EPCON_TXSTL | USS820_EPCON_RXSTL)); td->did_stall = 1; } /* clear end overwrite flag, if any */ if (rx_stat & USS820_RXSTAT_RXSETUP) { uss820dci_update_shared_1(sc, USS820_RXSTAT, 0xFF ^ (USS820_RXSTAT_EDOVW | USS820_RXSTAT_STOVW | USS820_RXSTAT_RXSETUP), 0); } return (1); /* not complete */ } static uint8_t uss820dci_data_rx(struct uss820dci_softc *sc, struct uss820dci_td *td) { struct usb_page_search buf_res; uint16_t count; uint8_t rx_flag; uint8_t rx_stat; uint8_t rx_cntl; uint8_t to; uint8_t got_short; to = 2; /* don't loop forever! */ got_short = 0; /* select the correct endpoint */ USS820_WRITE_1(sc, USS820_EPINDEX, td->ep_index); /* check if any of the FIFO banks have data */ repeat: /* read out FIFO flag */ rx_flag = USS820_READ_1(sc, USS820_RXFLG); /* read out FIFO status */ rx_stat = USS820_READ_1(sc, USS820_RXSTAT); DPRINTFN(5, "rx_stat=0x%02x rx_flag=0x%02x rem=%u\n", rx_stat, rx_flag, td->remainder); if (rx_stat & (USS820_RXSTAT_RXSETUP | USS820_RXSTAT_RXSOVW | USS820_RXSTAT_EDOVW)) { if (td->remainder == 0 && td->ep_index == 0) { /* * We are actually complete and have * received the next SETUP */ DPRINTFN(5, "faking complete\n"); return (0); /* complete */ } /* * USB Host Aborted the transfer. */ td->error = 1; return (0); /* complete */ } /* check for errors */ if (rx_flag & (USS820_RXFLG_RXOVF | USS820_RXFLG_RXURF)) { DPRINTFN(5, "overflow or underflow\n"); /* should not happen */ td->error = 1; return (0); /* complete */ } /* check status */ if (!(rx_flag & (USS820_RXFLG_RXFIF0 | USS820_RXFLG_RXFIF1))) { /* read out EPCON register */ /* enable RX input */ if (!td->did_enable) { uss820dci_update_shared_1(USS820_DCI_PC2SC(td->pc), USS820_EPCON, 0xFF, USS820_EPCON_RXIE); td->did_enable = 1; } return (1); /* not complete */ } /* get the packet byte count */ count = USS820_READ_1(sc, USS820_RXCNTL); count |= (USS820_READ_1(sc, USS820_RXCNTH) << 8); count &= 0x3FF; DPRINTFN(5, "count=0x%04x\n", count); /* verify the packet byte count */ if (count != td->max_packet_size) { if (count < td->max_packet_size) { /* we have a short packet */ td->short_pkt = 1; got_short = 1; } else { /* invalid USB packet */ td->error = 1; return (0); /* we are complete */ } } /* verify the packet byte count */ if (count > td->remainder) { /* invalid USB packet */ td->error = 1; return (0); /* we are complete */ } while (count > 0) { usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* receive data */ bus_space_read_multi_1(sc->sc_io_tag, sc->sc_io_hdl, USS820_RXDAT * USS820_REG_STRIDE, buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* set RXFFRC bit */ rx_cntl = USS820_READ_1(sc, USS820_RXCON); rx_cntl |= USS820_RXCON_RXFFRC; USS820_WRITE_1(sc, USS820_RXCON, rx_cntl); /* check if we are complete */ if ((td->remainder == 0) || got_short) { if (td->short_pkt) { /* we are complete */ return (0); } /* else need to receive a zero length packet */ } if (--to) { goto repeat; } return (1); /* not complete */ } static uint8_t uss820dci_data_tx(struct uss820dci_softc *sc, struct uss820dci_td *td) { struct usb_page_search buf_res; uint16_t count; uint16_t count_copy; uint8_t rx_stat; uint8_t tx_flag; uint8_t to; /* select the correct endpoint */ USS820_WRITE_1(sc, USS820_EPINDEX, td->ep_index); to = 2; /* don't loop forever! */ repeat: /* read out TX FIFO flags */ tx_flag = USS820_READ_1(sc, USS820_TXFLG); DPRINTFN(5, "tx_flag=0x%02x rem=%u\n", tx_flag, td->remainder); if (td->ep_index == 0) { /* read out RX FIFO status last */ rx_stat = USS820_READ_1(sc, USS820_RXSTAT); DPRINTFN(5, "rx_stat=0x%02x\n", rx_stat); if (rx_stat & (USS820_RXSTAT_RXSETUP | USS820_RXSTAT_RXSOVW | USS820_RXSTAT_EDOVW)) { /* * The current transfer was aborted by the USB * Host: */ td->error = 1; return (0); /* complete */ } } if (tx_flag & (USS820_TXFLG_TXOVF | USS820_TXFLG_TXURF)) { td->error = 1; return (0); /* complete */ } if (tx_flag & USS820_TXFLG_TXFIF0) { if (tx_flag & USS820_TXFLG_TXFIF1) { return (1); /* not complete */ } } if ((!td->support_multi_buffer) && (tx_flag & (USS820_TXFLG_TXFIF0 | USS820_TXFLG_TXFIF1))) { return (1); /* not complete */ } count = td->max_packet_size; if (td->remainder < count) { /* we have a short packet */ td->short_pkt = 1; count = td->remainder; } count_copy = count; while (count > 0) { usbd_get_page(td->pc, td->offset, &buf_res); /* get correct length */ if (buf_res.length > count) { buf_res.length = count; } /* transmit data */ bus_space_write_multi_1(sc->sc_io_tag, sc->sc_io_hdl, USS820_TXDAT * USS820_REG_STRIDE, buf_res.buffer, buf_res.length); /* update counters */ count -= buf_res.length; td->offset += buf_res.length; td->remainder -= buf_res.length; } /* post-write high packet byte count first */ USS820_WRITE_1(sc, USS820_TXCNTH, count_copy >> 8); /* post-write low packet byte count last */ USS820_WRITE_1(sc, USS820_TXCNTL, count_copy); /* * Enable TX output, which must happen after that we have written * data into the FIFO. This is undocumented. */ if (!td->did_enable) { uss820dci_update_shared_1(USS820_DCI_PC2SC(td->pc), USS820_EPCON, 0xFF, USS820_EPCON_TXOE); td->did_enable = 1; } /* check remainder */ if (td->remainder == 0) { if (td->short_pkt) { return (0); /* complete */ } /* else we need to transmit a short packet */ } if (--to) { goto repeat; } return (1); /* not complete */ } static uint8_t uss820dci_data_tx_sync(struct uss820dci_softc *sc, struct uss820dci_td *td) { uint8_t rx_stat; uint8_t tx_flag; /* select the correct endpoint */ USS820_WRITE_1(sc, USS820_EPINDEX, td->ep_index); /* read out TX FIFO flag */ tx_flag = USS820_READ_1(sc, USS820_TXFLG); if (td->ep_index == 0) { /* read out RX FIFO status last */ rx_stat = USS820_READ_1(sc, USS820_RXSTAT); DPRINTFN(5, "rx_stat=0x%02x rem=%u\n", rx_stat, td->remainder); if (rx_stat & (USS820_RXSTAT_RXSETUP | USS820_RXSTAT_RXSOVW | USS820_RXSTAT_EDOVW)) { DPRINTFN(5, "faking complete\n"); /* Race condition */ return (0); /* complete */ } } DPRINTFN(5, "tx_flag=0x%02x rem=%u\n", tx_flag, td->remainder); if (tx_flag & (USS820_TXFLG_TXOVF | USS820_TXFLG_TXURF)) { td->error = 1; return (0); /* complete */ } if (tx_flag & (USS820_TXFLG_TXFIF0 | USS820_TXFLG_TXFIF1)) { return (1); /* not complete */ } if (td->ep_index == 0 && sc->sc_dv_addr != 0xFF) { /* write function address */ uss820dci_set_address(sc, sc->sc_dv_addr); } return (0); /* complete */ } static void uss820dci_xfer_do_fifo(struct usb_xfer *xfer) { struct uss820dci_softc *sc = USS820_DCI_BUS2SC(xfer->xroot->bus); struct uss820dci_td *td; DPRINTFN(9, "\n"); td = xfer->td_transfer_cache; if (td == NULL) return; while (1) { if ((td->func) (sc, td)) { /* operation in progress */ break; } if (((void *)td) == xfer->td_transfer_last) { goto done; } if (td->error) { goto done; } else if (td->remainder > 0) { /* * We had a short transfer. If there is no alternate * next, stop processing ! */ if (!td->alt_next) { goto done; } } /* * Fetch the next transfer descriptor. */ td = td->obj_next; xfer->td_transfer_cache = td; } return; done: /* compute all actual lengths */ xfer->td_transfer_cache = NULL; sc->sc_xfer_complete = 1; } static uint8_t uss820dci_xfer_do_complete(struct usb_xfer *xfer) { struct uss820dci_td *td; DPRINTFN(9, "\n"); td = xfer->td_transfer_cache; if (td == NULL) { /* compute all actual lengths */ uss820dci_standard_done(xfer); return(1); } return (0); } static void uss820dci_interrupt_poll_locked(struct uss820dci_softc *sc) { struct usb_xfer *xfer; TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) uss820dci_xfer_do_fifo(xfer); } static void uss820dci_interrupt_complete_locked(struct uss820dci_softc *sc) { struct usb_xfer *xfer; repeat: TAILQ_FOREACH(xfer, &sc->sc_bus.intr_q.head, wait_entry) { if (uss820dci_xfer_do_complete(xfer)) goto repeat; } } static void uss820dci_wait_suspend(struct uss820dci_softc *sc, uint8_t on) { uint8_t scr; uint8_t scratch; scr = USS820_READ_1(sc, USS820_SCR); scratch = USS820_READ_1(sc, USS820_SCRATCH); if (on) { scr |= USS820_SCR_IE_SUSP; scratch &= ~USS820_SCRATCH_IE_RESUME; } else { scr &= ~USS820_SCR_IE_SUSP; scratch |= USS820_SCRATCH_IE_RESUME; } USS820_WRITE_1(sc, USS820_SCR, scr); USS820_WRITE_1(sc, USS820_SCRATCH, scratch); } int uss820dci_filter_interrupt(void *arg) { struct uss820dci_softc *sc = arg; int retval = FILTER_HANDLED; uint8_t ssr; USB_BUS_SPIN_LOCK(&sc->sc_bus); ssr = USS820_READ_1(sc, USS820_SSR); uss820dci_update_shared_1(sc, USS820_SSR, USS820_DCI_THREAD_IRQ, 0); if (ssr & USS820_DCI_THREAD_IRQ) retval = FILTER_SCHEDULE_THREAD; /* poll FIFOs, if any */ uss820dci_interrupt_poll_locked(sc); if (sc->sc_xfer_complete != 0) retval = FILTER_SCHEDULE_THREAD; USB_BUS_SPIN_UNLOCK(&sc->sc_bus); return (retval); } void uss820dci_interrupt(void *arg) { struct uss820dci_softc *sc = arg; uint8_t ssr; uint8_t event; USB_BUS_LOCK(&sc->sc_bus); USB_BUS_SPIN_LOCK(&sc->sc_bus); ssr = USS820_READ_1(sc, USS820_SSR); /* acknowledge all interrupts */ uss820dci_update_shared_1(sc, USS820_SSR, ~USS820_DCI_THREAD_IRQ, 0); /* check for any bus state change interrupts */ if (ssr & USS820_DCI_THREAD_IRQ) { event = 0; if (ssr & USS820_SSR_RESET) { sc->sc_flags.status_bus_reset = 1; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; /* disable resume interrupt */ uss820dci_wait_suspend(sc, 1); event = 1; } /* * If "RESUME" and "SUSPEND" is set at the same time * we interpret that like "RESUME". Resume is set when * there is at least 3 milliseconds of inactivity on * the USB BUS. */ if (ssr & USS820_SSR_RESUME) { if (sc->sc_flags.status_suspend) { sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 1; /* disable resume interrupt */ uss820dci_wait_suspend(sc, 1); event = 1; } } else if (ssr & USS820_SSR_SUSPEND) { if (!sc->sc_flags.status_suspend) { sc->sc_flags.status_suspend = 1; sc->sc_flags.change_suspend = 1; /* enable resume interrupt */ uss820dci_wait_suspend(sc, 0); event = 1; } } if (event) { DPRINTF("real bus interrupt 0x%02x\n", ssr); /* complete root HUB interrupt endpoint */ uss820dci_root_intr(sc); } } /* acknowledge all SBI interrupts */ uss820dci_update_shared_1(sc, USS820_SBI, 0, 0); /* acknowledge all SBI1 interrupts */ uss820dci_update_shared_1(sc, USS820_SBI1, 0, 0); if (sc->sc_xfer_complete != 0) { sc->sc_xfer_complete = 0; /* complete FIFOs, if any */ uss820dci_interrupt_complete_locked(sc); } USB_BUS_SPIN_UNLOCK(&sc->sc_bus); USB_BUS_UNLOCK(&sc->sc_bus); } static void uss820dci_setup_standard_chain_sub(struct uss820_std_temp *temp) { struct uss820dci_td *td; /* get current Transfer Descriptor */ td = temp->td_next; temp->td = td; /* prepare for next TD */ temp->td_next = td->obj_next; /* fill out the Transfer Descriptor */ td->func = temp->func; td->pc = temp->pc; td->offset = temp->offset; td->remainder = temp->len; td->error = 0; td->did_enable = 0; td->did_stall = temp->did_stall; td->short_pkt = temp->short_pkt; td->alt_next = temp->setup_alt_next; } static void uss820dci_setup_standard_chain(struct usb_xfer *xfer) { struct uss820_std_temp temp; struct uss820dci_softc *sc; struct uss820dci_td *td; uint32_t x; uint8_t ep_no; DPRINTFN(9, "addr=%d endpt=%d sumlen=%d speed=%d\n", xfer->address, UE_GET_ADDR(xfer->endpointno), xfer->sumlen, usbd_get_speed(xfer->xroot->udev)); temp.max_frame_size = xfer->max_frame_size; td = xfer->td_start[0]; xfer->td_transfer_first = td; xfer->td_transfer_cache = td; /* setup temp */ temp.pc = NULL; temp.td = NULL; temp.td_next = xfer->td_start[0]; temp.offset = 0; temp.setup_alt_next = xfer->flags_int.short_frames_ok || xfer->flags_int.isochronous_xfr; temp.did_stall = !xfer->flags_int.control_stall; sc = USS820_DCI_BUS2SC(xfer->xroot->bus); ep_no = (xfer->endpointno & UE_ADDR); /* check if we should prepend a setup message */ if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_hdr) { temp.func = &uss820dci_setup_rx; temp.len = xfer->frlengths[0]; temp.pc = xfer->frbuffers + 0; temp.short_pkt = temp.len ? 1 : 0; /* check for last frame */ if (xfer->nframes == 1) { /* no STATUS stage yet, SETUP is last */ if (xfer->flags_int.control_act) temp.setup_alt_next = 0; } uss820dci_setup_standard_chain_sub(&temp); } x = 1; } else { x = 0; } if (x != xfer->nframes) { if (xfer->endpointno & UE_DIR_IN) { temp.func = &uss820dci_data_tx; } else { temp.func = &uss820dci_data_rx; } /* setup "pc" pointer */ temp.pc = xfer->frbuffers + x; } while (x != xfer->nframes) { /* DATA0 / DATA1 message */ temp.len = xfer->frlengths[x]; x++; if (x == xfer->nframes) { if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_act) { temp.setup_alt_next = 0; } } else { temp.setup_alt_next = 0; } } if (temp.len == 0) { /* make sure that we send an USB packet */ temp.short_pkt = 0; } else { /* regular data transfer */ temp.short_pkt = (xfer->flags.force_short_xfer) ? 0 : 1; } uss820dci_setup_standard_chain_sub(&temp); if (xfer->flags_int.isochronous_xfr) { temp.offset += temp.len; } else { /* get next Page Cache pointer */ temp.pc = xfer->frbuffers + x; } } /* check for control transfer */ if (xfer->flags_int.control_xfr) { uint8_t need_sync; /* always setup a valid "pc" pointer for status and sync */ temp.pc = xfer->frbuffers + 0; temp.len = 0; temp.short_pkt = 0; temp.setup_alt_next = 0; /* check if we should append a status stage */ if (!xfer->flags_int.control_act) { /* * Send a DATA1 message and invert the current * endpoint direction. */ if (xfer->endpointno & UE_DIR_IN) { temp.func = &uss820dci_data_rx; need_sync = 0; } else { temp.func = &uss820dci_data_tx; need_sync = 1; } temp.len = 0; temp.short_pkt = 0; uss820dci_setup_standard_chain_sub(&temp); if (need_sync) { /* we need a SYNC point after TX */ temp.func = &uss820dci_data_tx_sync; uss820dci_setup_standard_chain_sub(&temp); } } } /* must have at least one frame! */ td = temp.td; xfer->td_transfer_last = td; } static void uss820dci_timeout(void *arg) { struct usb_xfer *xfer = arg; DPRINTF("xfer=%p\n", xfer); USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED); /* transfer is transferred */ uss820dci_device_done(xfer, USB_ERR_TIMEOUT); } static void uss820dci_intr_set(struct usb_xfer *xfer, uint8_t set) { struct uss820dci_softc *sc = USS820_DCI_BUS2SC(xfer->xroot->bus); uint8_t ep_no = (xfer->endpointno & UE_ADDR); uint8_t ep_reg; uint8_t temp; DPRINTFN(15, "endpoint 0x%02x\n", xfer->endpointno); if (ep_no > 3) { ep_reg = USS820_SBIE1; } else { ep_reg = USS820_SBIE; } ep_no &= 3; ep_no = 1 << (2 * ep_no); if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_hdr) { ep_no <<= 1; /* RX interrupt only */ } else { ep_no |= (ep_no << 1); /* RX and TX interrupt */ } } else { if (!(xfer->endpointno & UE_DIR_IN)) { ep_no <<= 1; } } temp = USS820_READ_1(sc, ep_reg); if (set) { temp |= ep_no; } else { temp &= ~ep_no; } USS820_WRITE_1(sc, ep_reg, temp); } static void uss820dci_start_standard_chain(struct usb_xfer *xfer) { struct uss820dci_softc *sc = USS820_DCI_BUS2SC(xfer->xroot->bus); DPRINTFN(9, "\n"); USB_BUS_SPIN_LOCK(&sc->sc_bus); /* poll one time */ uss820dci_xfer_do_fifo(xfer); if (uss820dci_xfer_do_complete(xfer) == 0) { /* * Only enable the endpoint interrupt when we are * actually waiting for data, hence we are dealing * with level triggered interrupts ! */ uss820dci_intr_set(xfer, 1); /* put transfer on interrupt queue */ usbd_transfer_enqueue(&xfer->xroot->bus->intr_q, xfer); /* start timeout, if any */ if (xfer->timeout != 0) { usbd_transfer_timeout_ms(xfer, &uss820dci_timeout, xfer->timeout); } } USB_BUS_SPIN_UNLOCK(&sc->sc_bus); } static void uss820dci_root_intr(struct uss820dci_softc *sc) { DPRINTFN(9, "\n"); USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); /* set port bit */ sc->sc_hub_idata[0] = 0x02; /* we only have one port */ uhub_root_intr(&sc->sc_bus, sc->sc_hub_idata, sizeof(sc->sc_hub_idata)); } static usb_error_t uss820dci_standard_done_sub(struct usb_xfer *xfer) { struct uss820dci_td *td; uint32_t len; uint8_t error; DPRINTFN(9, "\n"); td = xfer->td_transfer_cache; do { len = td->remainder; if (xfer->aframes != xfer->nframes) { /* * Verify the length and subtract * the remainder from "frlengths[]": */ if (len > xfer->frlengths[xfer->aframes]) { td->error = 1; } else { xfer->frlengths[xfer->aframes] -= len; } } /* Check for transfer error */ if (td->error) { /* the transfer is finished */ error = 1; td = NULL; break; } /* Check for short transfer */ if (len > 0) { if (xfer->flags_int.short_frames_ok || xfer->flags_int.isochronous_xfr) { /* follow alt next */ if (td->alt_next) { td = td->obj_next; } else { td = NULL; } } else { /* the transfer is finished */ td = NULL; } error = 0; break; } td = td->obj_next; /* this USB frame is complete */ error = 0; break; } while (0); /* update transfer cache */ xfer->td_transfer_cache = td; return (error ? USB_ERR_STALLED : USB_ERR_NORMAL_COMPLETION); } static void uss820dci_standard_done(struct usb_xfer *xfer) { usb_error_t err = 0; DPRINTFN(13, "xfer=%p endpoint=%p transfer done\n", xfer, xfer->endpoint); /* reset scanner */ xfer->td_transfer_cache = xfer->td_transfer_first; if (xfer->flags_int.control_xfr) { if (xfer->flags_int.control_hdr) { err = uss820dci_standard_done_sub(xfer); } xfer->aframes = 1; if (xfer->td_transfer_cache == NULL) { goto done; } } while (xfer->aframes != xfer->nframes) { err = uss820dci_standard_done_sub(xfer); xfer->aframes++; if (xfer->td_transfer_cache == NULL) { goto done; } } if (xfer->flags_int.control_xfr && !xfer->flags_int.control_act) { err = uss820dci_standard_done_sub(xfer); } done: uss820dci_device_done(xfer, err); } /*------------------------------------------------------------------------* * uss820dci_device_done * * NOTE: this function can be called more than one time on the * same USB transfer! *------------------------------------------------------------------------*/ static void uss820dci_device_done(struct usb_xfer *xfer, usb_error_t error) { struct uss820dci_softc *sc = USS820_DCI_BUS2SC(xfer->xroot->bus); USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED); DPRINTFN(2, "xfer=%p, endpoint=%p, error=%d\n", xfer, xfer->endpoint, error); USB_BUS_SPIN_LOCK(&sc->sc_bus); if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) { uss820dci_intr_set(xfer, 0); } /* dequeue transfer and start next transfer */ usbd_transfer_done(xfer, error); USB_BUS_SPIN_UNLOCK(&sc->sc_bus); } static void uss820dci_xfer_stall(struct usb_xfer *xfer) { uss820dci_device_done(xfer, USB_ERR_STALLED); } static void uss820dci_set_stall(struct usb_device *udev, struct usb_endpoint *ep, uint8_t *did_stall) { struct uss820dci_softc *sc; uint8_t ep_no; uint8_t ep_type; uint8_t ep_dir; uint8_t temp; USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED); DPRINTFN(5, "endpoint=%p\n", ep); /* set FORCESTALL */ sc = USS820_DCI_BUS2SC(udev->bus); ep_no = (ep->edesc->bEndpointAddress & UE_ADDR); ep_dir = (ep->edesc->bEndpointAddress & (UE_DIR_IN | UE_DIR_OUT)); ep_type = (ep->edesc->bmAttributes & UE_XFERTYPE); if (ep_type == UE_CONTROL) { /* should not happen */ return; } USB_BUS_SPIN_LOCK(&sc->sc_bus); USS820_WRITE_1(sc, USS820_EPINDEX, ep_no); if (ep_dir == UE_DIR_IN) { temp = USS820_EPCON_TXSTL; } else { temp = USS820_EPCON_RXSTL; } uss820dci_update_shared_1(sc, USS820_EPCON, 0xFF, temp); USB_BUS_SPIN_UNLOCK(&sc->sc_bus); } static void uss820dci_clear_stall_sub(struct uss820dci_softc *sc, uint8_t ep_no, uint8_t ep_type, uint8_t ep_dir) { uint8_t temp; if (ep_type == UE_CONTROL) { /* clearing stall is not needed */ return; } USB_BUS_SPIN_LOCK(&sc->sc_bus); /* select endpoint index */ USS820_WRITE_1(sc, USS820_EPINDEX, ep_no); /* clear stall and disable I/O transfers */ if (ep_dir == UE_DIR_IN) { temp = 0xFF ^ (USS820_EPCON_TXOE | USS820_EPCON_TXSTL); } else { temp = 0xFF ^ (USS820_EPCON_RXIE | USS820_EPCON_RXSTL); } uss820dci_update_shared_1(sc, USS820_EPCON, temp, 0); if (ep_dir == UE_DIR_IN) { /* reset data toggle */ USS820_WRITE_1(sc, USS820_TXSTAT, USS820_TXSTAT_TXSOVW); /* reset FIFO */ temp = USS820_READ_1(sc, USS820_TXCON); temp |= USS820_TXCON_TXCLR; USS820_WRITE_1(sc, USS820_TXCON, temp); temp &= ~USS820_TXCON_TXCLR; USS820_WRITE_1(sc, USS820_TXCON, temp); } else { /* reset data toggle */ uss820dci_update_shared_1(sc, USS820_RXSTAT, 0, USS820_RXSTAT_RXSOVW); /* reset FIFO */ temp = USS820_READ_1(sc, USS820_RXCON); temp |= USS820_RXCON_RXCLR; temp &= ~USS820_RXCON_RXFFRC; USS820_WRITE_1(sc, USS820_RXCON, temp); temp &= ~USS820_RXCON_RXCLR; USS820_WRITE_1(sc, USS820_RXCON, temp); } USB_BUS_SPIN_UNLOCK(&sc->sc_bus); } static void uss820dci_clear_stall(struct usb_device *udev, struct usb_endpoint *ep) { struct uss820dci_softc *sc; struct usb_endpoint_descriptor *ed; USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED); DPRINTFN(5, "endpoint=%p\n", ep); /* check mode */ if (udev->flags.usb_mode != USB_MODE_DEVICE) { /* not supported */ return; } /* get softc */ sc = USS820_DCI_BUS2SC(udev->bus); /* get endpoint descriptor */ ed = ep->edesc; /* reset endpoint */ uss820dci_clear_stall_sub(sc, (ed->bEndpointAddress & UE_ADDR), (ed->bmAttributes & UE_XFERTYPE), (ed->bEndpointAddress & (UE_DIR_IN | UE_DIR_OUT))); } usb_error_t uss820dci_init(struct uss820dci_softc *sc) { const struct usb_hw_ep_profile *pf; uint8_t n; uint8_t temp; DPRINTF("start\n"); /* set up the bus structure */ sc->sc_bus.usbrev = USB_REV_1_1; sc->sc_bus.methods = &uss820dci_bus_methods; USB_BUS_LOCK(&sc->sc_bus); /* we always have VBUS */ sc->sc_flags.status_vbus = 1; /* reset the chip */ USS820_WRITE_1(sc, USS820_SCR, USS820_SCR_SRESET); DELAY(100); USS820_WRITE_1(sc, USS820_SCR, 0); /* wait for reset to complete */ for (n = 0;; n++) { temp = USS820_READ_1(sc, USS820_MCSR); if (temp & USS820_MCSR_INIT) { break; } if (n == 100) { USB_BUS_UNLOCK(&sc->sc_bus); return (USB_ERR_INVAL); } /* wait a little for things to stabilise */ DELAY(100); } /* do a pulldown */ uss820dci_pull_down(sc); /* wait 10ms for pulldown to stabilise */ usb_pause_mtx(&sc->sc_bus.bus_mtx, hz / 100); /* check hardware revision */ temp = USS820_READ_1(sc, USS820_REV); if (temp < 0x13) { USB_BUS_UNLOCK(&sc->sc_bus); return (USB_ERR_INVAL); } /* enable interrupts */ USS820_WRITE_1(sc, USS820_SCR, USS820_SCR_T_IRQ | USS820_SCR_IE_RESET | /* USS820_SCR_RWUPE | */ USS820_SCR_IE_SUSP | USS820_SCR_IRQPOL); /* enable interrupts */ USS820_WRITE_1(sc, USS820_SCRATCH, USS820_SCRATCH_IE_RESUME); /* enable features */ USS820_WRITE_1(sc, USS820_MCSR, USS820_MCSR_BDFEAT | USS820_MCSR_FEAT); sc->sc_flags.mcsr_feat = 1; /* disable interrupts */ USS820_WRITE_1(sc, USS820_SBIE, 0); /* disable interrupts */ USS820_WRITE_1(sc, USS820_SBIE1, 0); /* disable all endpoints */ for (n = 0; n != USS820_EP_MAX; n++) { /* select endpoint */ USS820_WRITE_1(sc, USS820_EPINDEX, n); /* disable endpoint */ uss820dci_update_shared_1(sc, USS820_EPCON, 0, 0); } /* * Initialise default values for some registers that cannot be * changed during operation! */ for (n = 0; n != USS820_EP_MAX; n++) { uss820dci_get_hw_ep_profile(NULL, &pf, n); /* the maximum frame sizes should be the same */ if (pf->max_in_frame_size != pf->max_out_frame_size) { DPRINTF("Max frame size mismatch %u != %u\n", pf->max_in_frame_size, pf->max_out_frame_size); } if (pf->support_isochronous) { if (pf->max_in_frame_size <= 64) { temp = (USS820_TXCON_FFSZ_16_64 | USS820_TXCON_TXISO | USS820_TXCON_ATM); } else if (pf->max_in_frame_size <= 256) { temp = (USS820_TXCON_FFSZ_64_256 | USS820_TXCON_TXISO | USS820_TXCON_ATM); } else if (pf->max_in_frame_size <= 512) { temp = (USS820_TXCON_FFSZ_8_512 | USS820_TXCON_TXISO | USS820_TXCON_ATM); } else { /* 1024 bytes */ temp = (USS820_TXCON_FFSZ_32_1024 | USS820_TXCON_TXISO | USS820_TXCON_ATM); } } else { if ((pf->max_in_frame_size <= 8) && (sc->sc_flags.mcsr_feat)) { temp = (USS820_TXCON_FFSZ_8_512 | USS820_TXCON_ATM); } else if (pf->max_in_frame_size <= 16) { temp = (USS820_TXCON_FFSZ_16_64 | USS820_TXCON_ATM); } else if ((pf->max_in_frame_size <= 32) && (sc->sc_flags.mcsr_feat)) { temp = (USS820_TXCON_FFSZ_32_1024 | USS820_TXCON_ATM); } else { /* 64 bytes */ temp = (USS820_TXCON_FFSZ_64_256 | USS820_TXCON_ATM); } } /* need to configure the chip early */ USS820_WRITE_1(sc, USS820_EPINDEX, n); USS820_WRITE_1(sc, USS820_TXCON, temp); USS820_WRITE_1(sc, USS820_RXCON, temp); if (pf->support_control) { temp = USS820_EPCON_CTLEP | USS820_EPCON_RXSPM | USS820_EPCON_RXIE | USS820_EPCON_RXEPEN | USS820_EPCON_TXOE | USS820_EPCON_TXEPEN; } else { temp = USS820_EPCON_RXEPEN | USS820_EPCON_TXEPEN; } uss820dci_update_shared_1(sc, USS820_EPCON, 0, temp); } USB_BUS_UNLOCK(&sc->sc_bus); /* catch any lost interrupts */ uss820dci_do_poll(&sc->sc_bus); return (0); /* success */ } void uss820dci_uninit(struct uss820dci_softc *sc) { uint8_t temp; USB_BUS_LOCK(&sc->sc_bus); /* disable all interrupts */ temp = USS820_READ_1(sc, USS820_SCR); temp &= ~USS820_SCR_T_IRQ; USS820_WRITE_1(sc, USS820_SCR, temp); sc->sc_flags.port_powered = 0; sc->sc_flags.status_vbus = 0; sc->sc_flags.status_bus_reset = 0; sc->sc_flags.status_suspend = 0; sc->sc_flags.change_suspend = 0; sc->sc_flags.change_connect = 1; uss820dci_pull_down(sc); USB_BUS_UNLOCK(&sc->sc_bus); } static void uss820dci_suspend(struct uss820dci_softc *sc) { /* TODO */ } static void uss820dci_resume(struct uss820dci_softc *sc) { /* TODO */ } static void uss820dci_do_poll(struct usb_bus *bus) { struct uss820dci_softc *sc = USS820_DCI_BUS2SC(bus); USB_BUS_LOCK(&sc->sc_bus); USB_BUS_SPIN_LOCK(&sc->sc_bus); uss820dci_interrupt_poll_locked(sc); uss820dci_interrupt_complete_locked(sc); USB_BUS_SPIN_UNLOCK(&sc->sc_bus); USB_BUS_UNLOCK(&sc->sc_bus); } /*------------------------------------------------------------------------* * uss820dci bulk support *------------------------------------------------------------------------*/ static void uss820dci_device_bulk_open(struct usb_xfer *xfer) { return; } static void uss820dci_device_bulk_close(struct usb_xfer *xfer) { uss820dci_device_done(xfer, USB_ERR_CANCELLED); } static void uss820dci_device_bulk_enter(struct usb_xfer *xfer) { return; } static void uss820dci_device_bulk_start(struct usb_xfer *xfer) { /* setup TDs */ uss820dci_setup_standard_chain(xfer); uss820dci_start_standard_chain(xfer); } static const struct usb_pipe_methods uss820dci_device_bulk_methods = { .open = uss820dci_device_bulk_open, .close = uss820dci_device_bulk_close, .enter = uss820dci_device_bulk_enter, .start = uss820dci_device_bulk_start, }; /*------------------------------------------------------------------------* * uss820dci control support *------------------------------------------------------------------------*/ static void uss820dci_device_ctrl_open(struct usb_xfer *xfer) { return; } static void uss820dci_device_ctrl_close(struct usb_xfer *xfer) { uss820dci_device_done(xfer, USB_ERR_CANCELLED); } static void uss820dci_device_ctrl_enter(struct usb_xfer *xfer) { return; } static void uss820dci_device_ctrl_start(struct usb_xfer *xfer) { /* setup TDs */ uss820dci_setup_standard_chain(xfer); uss820dci_start_standard_chain(xfer); } static const struct usb_pipe_methods uss820dci_device_ctrl_methods = { .open = uss820dci_device_ctrl_open, .close = uss820dci_device_ctrl_close, .enter = uss820dci_device_ctrl_enter, .start = uss820dci_device_ctrl_start, }; /*------------------------------------------------------------------------* * uss820dci interrupt support *------------------------------------------------------------------------*/ static void uss820dci_device_intr_open(struct usb_xfer *xfer) { return; } static void uss820dci_device_intr_close(struct usb_xfer *xfer) { uss820dci_device_done(xfer, USB_ERR_CANCELLED); } static void uss820dci_device_intr_enter(struct usb_xfer *xfer) { return; } static void uss820dci_device_intr_start(struct usb_xfer *xfer) { /* setup TDs */ uss820dci_setup_standard_chain(xfer); uss820dci_start_standard_chain(xfer); } static const struct usb_pipe_methods uss820dci_device_intr_methods = { .open = uss820dci_device_intr_open, .close = uss820dci_device_intr_close, .enter = uss820dci_device_intr_enter, .start = uss820dci_device_intr_start, }; /*------------------------------------------------------------------------* * uss820dci full speed isochronous support *------------------------------------------------------------------------*/ static void uss820dci_device_isoc_fs_open(struct usb_xfer *xfer) { return; } static void uss820dci_device_isoc_fs_close(struct usb_xfer *xfer) { uss820dci_device_done(xfer, USB_ERR_CANCELLED); } static void uss820dci_device_isoc_fs_enter(struct usb_xfer *xfer) { struct uss820dci_softc *sc = USS820_DCI_BUS2SC(xfer->xroot->bus); uint32_t temp; uint32_t nframes; DPRINTFN(6, "xfer=%p next=%d nframes=%d\n", xfer, xfer->endpoint->isoc_next, xfer->nframes); /* get the current frame index - we don't need the high bits */ nframes = USS820_READ_1(sc, USS820_SOFL); /* * check if the frame index is within the window where the * frames will be inserted */ temp = (nframes - xfer->endpoint->isoc_next) & USS820_SOFL_MASK; if ((xfer->endpoint->is_synced == 0) || (temp < xfer->nframes)) { /* * If there is data underflow or the pipe queue is * empty we schedule the transfer a few frames ahead * of the current frame position. Else two isochronous * transfers might overlap. */ xfer->endpoint->isoc_next = (nframes + 3) & USS820_SOFL_MASK; xfer->endpoint->is_synced = 1; DPRINTFN(3, "start next=%d\n", xfer->endpoint->isoc_next); } /* * compute how many milliseconds the insertion is ahead of the * current frame position: */ temp = (xfer->endpoint->isoc_next - nframes) & USS820_SOFL_MASK; /* * pre-compute when the isochronous transfer will be finished: */ xfer->isoc_time_complete = usb_isoc_time_expand(&sc->sc_bus, nframes) + temp + xfer->nframes; /* compute frame number for next insertion */ xfer->endpoint->isoc_next += xfer->nframes; /* setup TDs */ uss820dci_setup_standard_chain(xfer); } static void uss820dci_device_isoc_fs_start(struct usb_xfer *xfer) { /* start TD chain */ uss820dci_start_standard_chain(xfer); } static const struct usb_pipe_methods uss820dci_device_isoc_fs_methods = { .open = uss820dci_device_isoc_fs_open, .close = uss820dci_device_isoc_fs_close, .enter = uss820dci_device_isoc_fs_enter, .start = uss820dci_device_isoc_fs_start, }; /*------------------------------------------------------------------------* * uss820dci root control support *------------------------------------------------------------------------* * Simulate a hardware HUB by handling all the necessary requests. *------------------------------------------------------------------------*/ static const struct usb_device_descriptor uss820dci_devd = { .bLength = sizeof(struct usb_device_descriptor), .bDescriptorType = UDESC_DEVICE, .bcdUSB = {0x00, 0x02}, .bDeviceClass = UDCLASS_HUB, .bDeviceSubClass = UDSUBCLASS_HUB, .bDeviceProtocol = UDPROTO_FSHUB, .bMaxPacketSize = 64, .bcdDevice = {0x00, 0x01}, .iManufacturer = 1, .iProduct = 2, .bNumConfigurations = 1, }; static const struct usb_device_qualifier uss820dci_odevd = { .bLength = sizeof(struct usb_device_qualifier), .bDescriptorType = UDESC_DEVICE_QUALIFIER, .bcdUSB = {0x00, 0x02}, .bDeviceClass = UDCLASS_HUB, .bDeviceSubClass = UDSUBCLASS_HUB, .bDeviceProtocol = UDPROTO_FSHUB, .bMaxPacketSize0 = 0, .bNumConfigurations = 0, }; static const struct uss820dci_config_desc uss820dci_confd = { .confd = { .bLength = sizeof(struct usb_config_descriptor), .bDescriptorType = UDESC_CONFIG, .wTotalLength[0] = sizeof(uss820dci_confd), .bNumInterface = 1, .bConfigurationValue = 1, .iConfiguration = 0, .bmAttributes = UC_SELF_POWERED, .bMaxPower = 0, }, .ifcd = { .bLength = sizeof(struct usb_interface_descriptor), .bDescriptorType = UDESC_INTERFACE, .bNumEndpoints = 1, .bInterfaceClass = UICLASS_HUB, .bInterfaceSubClass = UISUBCLASS_HUB, .bInterfaceProtocol = 0, }, .endpd = { .bLength = sizeof(struct usb_endpoint_descriptor), .bDescriptorType = UDESC_ENDPOINT, .bEndpointAddress = (UE_DIR_IN | USS820_DCI_INTR_ENDPT), .bmAttributes = UE_INTERRUPT, .wMaxPacketSize[0] = 8, .bInterval = 255, }, }; #define HSETW(ptr, val) ptr = { (uint8_t)(val), (uint8_t)((val) >> 8) } static const struct usb_hub_descriptor_min uss820dci_hubd = { .bDescLength = sizeof(uss820dci_hubd), .bDescriptorType = UDESC_HUB, .bNbrPorts = 1, HSETW(.wHubCharacteristics, (UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL)), .bPwrOn2PwrGood = 50, .bHubContrCurrent = 0, .DeviceRemovable = {0}, /* port is removable */ }; #define STRING_VENDOR \ "A\0G\0E\0R\0E" #define STRING_PRODUCT \ "D\0C\0I\0 \0R\0o\0o\0t\0 \0H\0U\0B" USB_MAKE_STRING_DESC(STRING_VENDOR, uss820dci_vendor); USB_MAKE_STRING_DESC(STRING_PRODUCT, uss820dci_product); static usb_error_t uss820dci_roothub_exec(struct usb_device *udev, struct usb_device_request *req, const void **pptr, uint16_t *plength) { struct uss820dci_softc *sc = USS820_DCI_BUS2SC(udev->bus); const void *ptr; uint16_t len; uint16_t value; uint16_t index; usb_error_t err; USB_BUS_LOCK_ASSERT(&sc->sc_bus, MA_OWNED); /* buffer reset */ ptr = (const void *)&sc->sc_hub_temp; len = 0; err = 0; value = UGETW(req->wValue); index = UGETW(req->wIndex); /* demultiplex the control request */ switch (req->bmRequestType) { case UT_READ_DEVICE: switch (req->bRequest) { case UR_GET_DESCRIPTOR: goto tr_handle_get_descriptor; case UR_GET_CONFIG: goto tr_handle_get_config; case UR_GET_STATUS: goto tr_handle_get_status; default: goto tr_stalled; } break; case UT_WRITE_DEVICE: switch (req->bRequest) { case UR_SET_ADDRESS: goto tr_handle_set_address; case UR_SET_CONFIG: goto tr_handle_set_config; case UR_CLEAR_FEATURE: goto tr_valid; /* nop */ case UR_SET_DESCRIPTOR: goto tr_valid; /* nop */ case UR_SET_FEATURE: default: goto tr_stalled; } break; case UT_WRITE_ENDPOINT: switch (req->bRequest) { case UR_CLEAR_FEATURE: switch (UGETW(req->wValue)) { case UF_ENDPOINT_HALT: goto tr_handle_clear_halt; case UF_DEVICE_REMOTE_WAKEUP: goto tr_handle_clear_wakeup; default: goto tr_stalled; } break; case UR_SET_FEATURE: switch (UGETW(req->wValue)) { case UF_ENDPOINT_HALT: goto tr_handle_set_halt; case UF_DEVICE_REMOTE_WAKEUP: goto tr_handle_set_wakeup; default: goto tr_stalled; } break; case UR_SYNCH_FRAME: goto tr_valid; /* nop */ default: goto tr_stalled; } break; case UT_READ_ENDPOINT: switch (req->bRequest) { case UR_GET_STATUS: goto tr_handle_get_ep_status; default: goto tr_stalled; } break; case UT_WRITE_INTERFACE: switch (req->bRequest) { case UR_SET_INTERFACE: goto tr_handle_set_interface; case UR_CLEAR_FEATURE: goto tr_valid; /* nop */ case UR_SET_FEATURE: default: goto tr_stalled; } break; case UT_READ_INTERFACE: switch (req->bRequest) { case UR_GET_INTERFACE: goto tr_handle_get_interface; case UR_GET_STATUS: goto tr_handle_get_iface_status; default: goto tr_stalled; } break; case UT_WRITE_CLASS_INTERFACE: case UT_WRITE_VENDOR_INTERFACE: /* XXX forward */ break; case UT_READ_CLASS_INTERFACE: case UT_READ_VENDOR_INTERFACE: /* XXX forward */ break; case UT_WRITE_CLASS_DEVICE: switch (req->bRequest) { case UR_CLEAR_FEATURE: goto tr_valid; case UR_SET_DESCRIPTOR: case UR_SET_FEATURE: break; default: goto tr_stalled; } break; case UT_WRITE_CLASS_OTHER: switch (req->bRequest) { case UR_CLEAR_FEATURE: goto tr_handle_clear_port_feature; case UR_SET_FEATURE: goto tr_handle_set_port_feature; case UR_CLEAR_TT_BUFFER: case UR_RESET_TT: case UR_STOP_TT: goto tr_valid; default: goto tr_stalled; } break; case UT_READ_CLASS_OTHER: switch (req->bRequest) { case UR_GET_TT_STATE: goto tr_handle_get_tt_state; case UR_GET_STATUS: goto tr_handle_get_port_status; default: goto tr_stalled; } break; case UT_READ_CLASS_DEVICE: switch (req->bRequest) { case UR_GET_DESCRIPTOR: goto tr_handle_get_class_descriptor; case UR_GET_STATUS: goto tr_handle_get_class_status; default: goto tr_stalled; } break; default: goto tr_stalled; } goto tr_valid; tr_handle_get_descriptor: switch (value >> 8) { case UDESC_DEVICE: if (value & 0xff) { goto tr_stalled; } len = sizeof(uss820dci_devd); ptr = (const void *)&uss820dci_devd; goto tr_valid; case UDESC_DEVICE_QUALIFIER: if (value & 0xff) { goto tr_stalled; } len = sizeof(uss820dci_odevd); ptr = (const void *)&uss820dci_odevd; goto tr_valid; case UDESC_CONFIG: if (value & 0xff) { goto tr_stalled; } len = sizeof(uss820dci_confd); ptr = (const void *)&uss820dci_confd; goto tr_valid; case UDESC_STRING: switch (value & 0xff) { case 0: /* Language table */ len = sizeof(usb_string_lang_en); ptr = (const void *)&usb_string_lang_en; goto tr_valid; case 1: /* Vendor */ len = sizeof(uss820dci_vendor); ptr = (const void *)&uss820dci_vendor; goto tr_valid; case 2: /* Product */ len = sizeof(uss820dci_product); ptr = (const void *)&uss820dci_product; goto tr_valid; default: break; } break; default: goto tr_stalled; } goto tr_stalled; tr_handle_get_config: len = 1; sc->sc_hub_temp.wValue[0] = sc->sc_conf; goto tr_valid; tr_handle_get_status: len = 2; USETW(sc->sc_hub_temp.wValue, UDS_SELF_POWERED); goto tr_valid; tr_handle_set_address: if (value & 0xFF00) { goto tr_stalled; } sc->sc_rt_addr = value; goto tr_valid; tr_handle_set_config: if (value >= 2) { goto tr_stalled; } sc->sc_conf = value; goto tr_valid; tr_handle_get_interface: len = 1; sc->sc_hub_temp.wValue[0] = 0; goto tr_valid; tr_handle_get_tt_state: tr_handle_get_class_status: tr_handle_get_iface_status: tr_handle_get_ep_status: len = 2; USETW(sc->sc_hub_temp.wValue, 0); goto tr_valid; tr_handle_set_halt: tr_handle_set_interface: tr_handle_set_wakeup: tr_handle_clear_wakeup: tr_handle_clear_halt: goto tr_valid; tr_handle_clear_port_feature: if (index != 1) { goto tr_stalled; } DPRINTFN(9, "UR_CLEAR_PORT_FEATURE on port %d\n", index); switch (value) { case UHF_PORT_SUSPEND: uss820dci_wakeup_peer(sc); break; case UHF_PORT_ENABLE: sc->sc_flags.port_enabled = 0; break; case UHF_PORT_TEST: case UHF_PORT_INDICATOR: case UHF_C_PORT_ENABLE: case UHF_C_PORT_OVER_CURRENT: case UHF_C_PORT_RESET: /* nops */ break; case UHF_PORT_POWER: sc->sc_flags.port_powered = 0; uss820dci_pull_down(sc); break; case UHF_C_PORT_CONNECTION: sc->sc_flags.change_connect = 0; break; case UHF_C_PORT_SUSPEND: sc->sc_flags.change_suspend = 0; break; default: err = USB_ERR_IOERROR; goto done; } goto tr_valid; tr_handle_set_port_feature: if (index != 1) { goto tr_stalled; } DPRINTFN(9, "UR_SET_PORT_FEATURE\n"); switch (value) { case UHF_PORT_ENABLE: sc->sc_flags.port_enabled = 1; break; case UHF_PORT_SUSPEND: case UHF_PORT_RESET: case UHF_PORT_TEST: case UHF_PORT_INDICATOR: /* nops */ break; case UHF_PORT_POWER: sc->sc_flags.port_powered = 1; break; default: err = USB_ERR_IOERROR; goto done; } goto tr_valid; tr_handle_get_port_status: DPRINTFN(9, "UR_GET_PORT_STATUS\n"); if (index != 1) { goto tr_stalled; } if (sc->sc_flags.status_vbus) { uss820dci_pull_up(sc); } else { uss820dci_pull_down(sc); } /* Select FULL-speed and Device Side Mode */ value = UPS_PORT_MODE_DEVICE; if (sc->sc_flags.port_powered) { value |= UPS_PORT_POWER; } if (sc->sc_flags.port_enabled) { value |= UPS_PORT_ENABLED; } if (sc->sc_flags.status_vbus && sc->sc_flags.status_bus_reset) { value |= UPS_CURRENT_CONNECT_STATUS; } if (sc->sc_flags.status_suspend) { value |= UPS_SUSPEND; } USETW(sc->sc_hub_temp.ps.wPortStatus, value); value = 0; if (sc->sc_flags.change_connect) { value |= UPS_C_CONNECT_STATUS; } if (sc->sc_flags.change_suspend) { value |= UPS_C_SUSPEND; } USETW(sc->sc_hub_temp.ps.wPortChange, value); len = sizeof(sc->sc_hub_temp.ps); goto tr_valid; tr_handle_get_class_descriptor: if (value & 0xFF) { goto tr_stalled; } ptr = (const void *)&uss820dci_hubd; len = sizeof(uss820dci_hubd); goto tr_valid; tr_stalled: err = USB_ERR_STALLED; tr_valid: done: *plength = len; *pptr = ptr; return (err); } static void uss820dci_xfer_setup(struct usb_setup_params *parm) { const struct usb_hw_ep_profile *pf; struct uss820dci_softc *sc; struct usb_xfer *xfer; void *last_obj; uint32_t ntd; uint32_t n; uint8_t ep_no; sc = USS820_DCI_BUS2SC(parm->udev->bus); xfer = parm->curr_xfer; /* * NOTE: This driver does not use any of the parameters that * are computed from the following values. Just set some * reasonable dummies: */ parm->hc_max_packet_size = 0x500; parm->hc_max_packet_count = 1; parm->hc_max_frame_size = 0x500; usbd_transfer_setup_sub(parm); /* * compute maximum number of TDs */ if (parm->methods == &uss820dci_device_ctrl_methods) { ntd = xfer->nframes + 1 /* STATUS */ + 1 /* SYNC */ ; } else if (parm->methods == &uss820dci_device_bulk_methods) { ntd = xfer->nframes + 1 /* SYNC */ ; } else if (parm->methods == &uss820dci_device_intr_methods) { ntd = xfer->nframes + 1 /* SYNC */ ; } else if (parm->methods == &uss820dci_device_isoc_fs_methods) { ntd = xfer->nframes + 1 /* SYNC */ ; } else { ntd = 0; } /* * check if "usbd_transfer_setup_sub" set an error */ if (parm->err) { return; } /* * allocate transfer descriptors */ last_obj = NULL; /* * get profile stuff */ if (ntd) { ep_no = xfer->endpointno & UE_ADDR; uss820dci_get_hw_ep_profile(parm->udev, &pf, ep_no); if (pf == NULL) { /* should not happen */ parm->err = USB_ERR_INVAL; return; } } else { ep_no = 0; pf = NULL; } /* align data */ parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1)); for (n = 0; n != ntd; n++) { struct uss820dci_td *td; if (parm->buf) { td = USB_ADD_BYTES(parm->buf, parm->size[0]); /* init TD */ td->max_packet_size = xfer->max_packet_size; td->ep_index = ep_no; if (pf->support_multi_buffer && (parm->methods != &uss820dci_device_ctrl_methods)) { td->support_multi_buffer = 1; } td->obj_next = last_obj; last_obj = td; } parm->size[0] += sizeof(*td); } xfer->td_start[0] = last_obj; } static void uss820dci_xfer_unsetup(struct usb_xfer *xfer) { return; } static void uss820dci_ep_init(struct usb_device *udev, struct usb_endpoint_descriptor *edesc, struct usb_endpoint *ep) { struct uss820dci_softc *sc = USS820_DCI_BUS2SC(udev->bus); DPRINTFN(2, "endpoint=%p, addr=%d, endpt=%d, mode=%d (%d)\n", ep, udev->address, edesc->bEndpointAddress, udev->flags.usb_mode, sc->sc_rt_addr); if (udev->device_index != sc->sc_rt_addr) { if (udev->speed != USB_SPEED_FULL) { /* not supported */ return; } switch (edesc->bmAttributes & UE_XFERTYPE) { case UE_CONTROL: ep->methods = &uss820dci_device_ctrl_methods; break; case UE_INTERRUPT: ep->methods = &uss820dci_device_intr_methods; break; case UE_ISOCHRONOUS: ep->methods = &uss820dci_device_isoc_fs_methods; break; case UE_BULK: ep->methods = &uss820dci_device_bulk_methods; break; default: /* do nothing */ break; } } } static void uss820dci_set_hw_power_sleep(struct usb_bus *bus, uint32_t state) { struct uss820dci_softc *sc = USS820_DCI_BUS2SC(bus); switch (state) { case USB_HW_POWER_SUSPEND: uss820dci_suspend(sc); break; case USB_HW_POWER_SHUTDOWN: uss820dci_uninit(sc); break; case USB_HW_POWER_RESUME: uss820dci_resume(sc); break; default: break; } } static const struct usb_bus_methods uss820dci_bus_methods = { .endpoint_init = &uss820dci_ep_init, .xfer_setup = &uss820dci_xfer_setup, .xfer_unsetup = &uss820dci_xfer_unsetup, .get_hw_ep_profile = &uss820dci_get_hw_ep_profile, .xfer_stall = &uss820dci_xfer_stall, .set_stall = &uss820dci_set_stall, .clear_stall = &uss820dci_clear_stall, .roothub_exec = &uss820dci_roothub_exec, .xfer_poll = &uss820dci_do_poll, .set_hw_power_sleep = uss820dci_set_hw_power_sleep, }; Index: head/sys/dev/usb/gadget/g_audio.c =================================================================== --- head/sys/dev/usb/gadget/g_audio.c (revision 276700) +++ head/sys/dev/usb/gadget/g_audio.c (revision 276701) @@ -1,624 +1,624 @@ /*- * Copyright (c) 2010 Hans Petter Selasky. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * USB audio specs: http://www.usb.org/developers/devclass_docs/audio10.pdf * http://www.usb.org/developers/devclass_docs/frmts10.pdf * http://www.usb.org/developers/devclass_docs/termt10.pdf */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usb_if.h" #define USB_DEBUG_VAR g_audio_debug #include #include enum { G_AUDIO_ISOC0_RD, G_AUDIO_ISOC1_RD, G_AUDIO_ISOC0_WR, G_AUDIO_ISOC1_WR, G_AUDIO_N_TRANSFER, }; struct g_audio_softc { struct mtx sc_mtx; struct usb_callout sc_callout; struct usb_callout sc_watchdog; struct usb_xfer *sc_xfer[G_AUDIO_N_TRANSFER]; int sc_mode; int sc_pattern_len; int sc_throughput; int sc_tx_interval; int sc_state; int sc_noise_rem; int8_t sc_pattern[G_AUDIO_MAX_STRLEN]; uint16_t sc_data_len[2][G_AUDIO_FRAMES]; int16_t sc_data_buf[2][G_AUDIO_BUFSIZE / 2]; uint8_t sc_volume_setting[32]; uint8_t sc_volume_limit[32]; uint8_t sc_sample_rate[32]; }; static SYSCTL_NODE(_hw_usb, OID_AUTO, g_audio, CTLFLAG_RW, 0, "USB audio gadget"); #ifdef USB_DEBUG static int g_audio_debug = 0; -SYSCTL_INT(_hw_usb_g_audio, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_g_audio, OID_AUTO, debug, CTLFLAG_RWTUN, &g_audio_debug, 0, "Debug level"); #endif static int g_audio_mode = 0; -SYSCTL_INT(_hw_usb_g_audio, OID_AUTO, mode, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_g_audio, OID_AUTO, mode, CTLFLAG_RWTUN, &g_audio_mode, 0, "Mode selection"); static int g_audio_pattern_interval = 1000; -SYSCTL_INT(_hw_usb_g_audio, OID_AUTO, pattern_interval, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_g_audio, OID_AUTO, pattern_interval, CTLFLAG_RWTUN, &g_audio_pattern_interval, 0, "Pattern interval in milliseconds"); static char g_audio_pattern_data[G_AUDIO_MAX_STRLEN]; SYSCTL_STRING(_hw_usb_g_audio, OID_AUTO, pattern, CTLFLAG_RW, &g_audio_pattern_data, sizeof(g_audio_pattern_data), "Data pattern"); static int g_audio_throughput; SYSCTL_INT(_hw_usb_g_audio, OID_AUTO, throughput, CTLFLAG_RD, &g_audio_throughput, sizeof(g_audio_throughput), "Throughput in bytes per second"); static device_probe_t g_audio_probe; static device_attach_t g_audio_attach; static device_detach_t g_audio_detach; static usb_handle_request_t g_audio_handle_request; static usb_callback_t g_audio_isoc_read_callback; static usb_callback_t g_audio_isoc_write_callback; static devclass_t g_audio_devclass; static void g_audio_watchdog(void *arg); static void g_audio_timeout(void *arg); static device_method_t g_audio_methods[] = { /* USB interface */ DEVMETHOD(usb_handle_request, g_audio_handle_request), /* Device interface */ DEVMETHOD(device_probe, g_audio_probe), DEVMETHOD(device_attach, g_audio_attach), DEVMETHOD(device_detach, g_audio_detach), DEVMETHOD_END }; static driver_t g_audio_driver = { .name = "g_audio", .methods = g_audio_methods, .size = sizeof(struct g_audio_softc), }; DRIVER_MODULE(g_audio, uhub, g_audio_driver, g_audio_devclass, 0, 0); MODULE_DEPEND(g_audio, usb, 1, 1, 1); static const struct usb_config g_audio_config[G_AUDIO_N_TRANSFER] = { [G_AUDIO_ISOC0_RD] = { .type = UE_ISOCHRONOUS, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_RX, .flags = {.ext_buffer = 1,.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = G_AUDIO_BUFSIZE, .callback = &g_audio_isoc_read_callback, .frames = G_AUDIO_FRAMES, .usb_mode = USB_MODE_DEVICE, .if_index = 1, }, [G_AUDIO_ISOC1_RD] = { .type = UE_ISOCHRONOUS, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_RX, .flags = {.ext_buffer = 1,.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = G_AUDIO_BUFSIZE, .callback = &g_audio_isoc_read_callback, .frames = G_AUDIO_FRAMES, .usb_mode = USB_MODE_DEVICE, .if_index = 1, }, [G_AUDIO_ISOC0_WR] = { .type = UE_ISOCHRONOUS, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_TX, .flags = {.ext_buffer = 1,.pipe_bof = 1,}, .bufsize = G_AUDIO_BUFSIZE, .callback = &g_audio_isoc_write_callback, .frames = G_AUDIO_FRAMES, .usb_mode = USB_MODE_DEVICE, .if_index = 2, }, [G_AUDIO_ISOC1_WR] = { .type = UE_ISOCHRONOUS, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_TX, .flags = {.ext_buffer = 1,.pipe_bof = 1,}, .bufsize = G_AUDIO_BUFSIZE, .callback = &g_audio_isoc_write_callback, .frames = G_AUDIO_FRAMES, .usb_mode = USB_MODE_DEVICE, .if_index = 2, }, }; static void g_audio_timeout_reset(struct g_audio_softc *sc) { int i = g_audio_pattern_interval; sc->sc_tx_interval = i; if (i <= 0) i = 1; else if (i > 1023) i = 1023; i = USB_MS_TO_TICKS(i); usb_callout_reset(&sc->sc_callout, i, &g_audio_timeout, sc); } static void g_audio_timeout(void *arg) { struct g_audio_softc *sc = arg; sc->sc_mode = g_audio_mode; memcpy(sc->sc_pattern, g_audio_pattern_data, sizeof(sc->sc_pattern)); sc->sc_pattern[G_AUDIO_MAX_STRLEN - 1] = 0; sc->sc_pattern_len = strlen(sc->sc_pattern); if (sc->sc_mode != G_AUDIO_MODE_LOOP) { usbd_transfer_start(sc->sc_xfer[G_AUDIO_ISOC0_WR]); usbd_transfer_start(sc->sc_xfer[G_AUDIO_ISOC1_WR]); } g_audio_timeout_reset(sc); } static void g_audio_watchdog_reset(struct g_audio_softc *sc) { usb_callout_reset(&sc->sc_watchdog, hz, &g_audio_watchdog, sc); } static void g_audio_watchdog(void *arg) { struct g_audio_softc *sc = arg; int i; i = sc->sc_throughput; sc->sc_throughput = 0; g_audio_throughput = i; g_audio_watchdog_reset(sc); } static int g_audio_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); DPRINTFN(11, "\n"); if (uaa->usb_mode != USB_MODE_DEVICE) return (ENXIO); if ((uaa->info.bInterfaceClass == UICLASS_AUDIO) && (uaa->info.bInterfaceSubClass == UISUBCLASS_AUDIOCONTROL)) return (0); return (ENXIO); } static int g_audio_attach(device_t dev) { struct g_audio_softc *sc = device_get_softc(dev); struct usb_attach_arg *uaa = device_get_ivars(dev); int error; int i; uint8_t iface_index[3]; DPRINTFN(11, "\n"); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "g_audio", NULL, MTX_DEF); usb_callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); usb_callout_init_mtx(&sc->sc_watchdog, &sc->sc_mtx, 0); sc->sc_mode = G_AUDIO_MODE_SILENT; sc->sc_noise_rem = 1; for (i = 0; i != G_AUDIO_FRAMES; i++) { sc->sc_data_len[0][i] = G_AUDIO_BUFSIZE / G_AUDIO_FRAMES; sc->sc_data_len[1][i] = G_AUDIO_BUFSIZE / G_AUDIO_FRAMES; } iface_index[0] = uaa->info.bIfaceIndex; iface_index[1] = uaa->info.bIfaceIndex + 1; iface_index[2] = uaa->info.bIfaceIndex + 2; error = usbd_set_alt_interface_index(uaa->device, iface_index[1], 1); if (error) { DPRINTF("alt iface setting error=%s\n", usbd_errstr(error)); goto detach; } error = usbd_set_alt_interface_index(uaa->device, iface_index[2], 1); if (error) { DPRINTF("alt iface setting error=%s\n", usbd_errstr(error)); goto detach; } error = usbd_transfer_setup(uaa->device, iface_index, sc->sc_xfer, g_audio_config, G_AUDIO_N_TRANSFER, sc, &sc->sc_mtx); if (error) { DPRINTF("error=%s\n", usbd_errstr(error)); goto detach; } usbd_set_parent_iface(uaa->device, iface_index[1], iface_index[0]); usbd_set_parent_iface(uaa->device, iface_index[2], iface_index[0]); mtx_lock(&sc->sc_mtx); usbd_transfer_start(sc->sc_xfer[G_AUDIO_ISOC0_RD]); usbd_transfer_start(sc->sc_xfer[G_AUDIO_ISOC1_RD]); usbd_transfer_start(sc->sc_xfer[G_AUDIO_ISOC0_WR]); usbd_transfer_start(sc->sc_xfer[G_AUDIO_ISOC1_WR]); g_audio_timeout_reset(sc); g_audio_watchdog_reset(sc); mtx_unlock(&sc->sc_mtx); return (0); /* success */ detach: g_audio_detach(dev); return (ENXIO); /* error */ } static int g_audio_detach(device_t dev) { struct g_audio_softc *sc = device_get_softc(dev); DPRINTF("\n"); mtx_lock(&sc->sc_mtx); usb_callout_stop(&sc->sc_callout); usb_callout_stop(&sc->sc_watchdog); mtx_unlock(&sc->sc_mtx); usbd_transfer_unsetup(sc->sc_xfer, G_AUDIO_N_TRANSFER); usb_callout_drain(&sc->sc_callout); usb_callout_drain(&sc->sc_watchdog); mtx_destroy(&sc->sc_mtx); return (0); } static int32_t g_noise(struct g_audio_softc *sc) { uint32_t temp; const uint32_t prime = 0xFFFF1D; if (sc->sc_noise_rem & 1) { sc->sc_noise_rem += prime; } sc->sc_noise_rem /= 2; temp = sc->sc_noise_rem; /* unsigned to signed conversion */ temp ^= 0x800000; if (temp & 0x800000) { temp |= (-0x800000); } return temp; } static void g_audio_make_samples(struct g_audio_softc *sc, int16_t *ptr, int samples) { int i; int j; for (i = 0; i != samples; i++) { j = g_noise(sc); if ((sc->sc_state < 0) || (sc->sc_state >= sc->sc_pattern_len)) sc->sc_state = 0; if (sc->sc_pattern_len != 0) { j = (j * sc->sc_pattern[sc->sc_state]) >> 16; sc->sc_state++; } *ptr++ = j / 256; *ptr++ = j / 256; } } static void g_audio_isoc_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct g_audio_softc *sc = usbd_xfer_softc(xfer); int actlen; int aframes; int nr = (xfer == sc->sc_xfer[G_AUDIO_ISOC0_WR]) ? 0 : 1; int16_t *ptr; int i; usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL); DPRINTF("st=%d aframes=%d actlen=%d bytes\n", USB_GET_STATE(xfer), aframes, actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: sc->sc_throughput += actlen; if (sc->sc_mode == G_AUDIO_MODE_LOOP) break; /* sync with RX */ case USB_ST_SETUP: tr_setup: ptr = sc->sc_data_buf[nr]; if (sc->sc_mode == G_AUDIO_MODE_PATTERN) { for (i = 0; i != G_AUDIO_FRAMES; i++) { usbd_xfer_set_frame_data(xfer, i, ptr, sc->sc_data_len[nr][i]); g_audio_make_samples(sc, ptr, (G_AUDIO_BUFSIZE / G_AUDIO_FRAMES) / 2); ptr += (G_AUDIO_BUFSIZE / G_AUDIO_FRAMES) / 2; } } else if (sc->sc_mode == G_AUDIO_MODE_LOOP) { for (i = 0; i != G_AUDIO_FRAMES; i++) { usbd_xfer_set_frame_data(xfer, i, ptr, sc->sc_data_len[nr][i] & ~3); g_audio_make_samples(sc, ptr, sc->sc_data_len[nr][i] / 4); ptr += (G_AUDIO_BUFSIZE / G_AUDIO_FRAMES) / 2; } } break; default: /* Error */ DPRINTF("error=%s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void g_audio_isoc_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct g_audio_softc *sc = usbd_xfer_softc(xfer); int actlen; int aframes; int nr = (xfer == sc->sc_xfer[G_AUDIO_ISOC0_RD]) ? 0 : 1; int16_t *ptr; int i; usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL); DPRINTF("st=%d aframes=%d actlen=%d bytes\n", USB_GET_STATE(xfer), aframes, actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: sc->sc_throughput += actlen; for (i = 0; i != G_AUDIO_FRAMES; i++) { sc->sc_data_len[nr][i] = usbd_xfer_frame_len(xfer, i); } usbd_transfer_start(sc->sc_xfer[G_AUDIO_ISOC0_WR]); usbd_transfer_start(sc->sc_xfer[G_AUDIO_ISOC1_WR]); break; case USB_ST_SETUP: tr_setup: ptr = sc->sc_data_buf[nr]; for (i = 0; i != G_AUDIO_FRAMES; i++) { usbd_xfer_set_frame_data(xfer, i, ptr, G_AUDIO_BUFSIZE / G_AUDIO_FRAMES); ptr += (G_AUDIO_BUFSIZE / G_AUDIO_FRAMES) / 2; } usbd_transfer_submit(xfer); break; default: /* Error */ DPRINTF("error=%s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static int g_audio_handle_request(device_t dev, const void *preq, void **pptr, uint16_t *plen, uint16_t offset, uint8_t *pstate) { struct g_audio_softc *sc = device_get_softc(dev); const struct usb_device_request *req = preq; uint8_t is_complete = *pstate; if (!is_complete) { if ((req->bmRequestType == UT_READ_CLASS_INTERFACE) && (req->bRequest == 0x82 /* get min */ )) { if (offset == 0) { USETW(sc->sc_volume_limit, 0); *plen = 2; *pptr = &sc->sc_volume_limit; } else { *plen = 0; } return (0); } else if ((req->bmRequestType == UT_READ_CLASS_INTERFACE) && (req->bRequest == 0x83 /* get max */ )) { if (offset == 0) { USETW(sc->sc_volume_limit, 0x2000); *plen = 2; *pptr = &sc->sc_volume_limit; } else { *plen = 0; } return (0); } else if ((req->bmRequestType == UT_READ_CLASS_INTERFACE) && (req->bRequest == 0x84 /* get residue */ )) { if (offset == 0) { USETW(sc->sc_volume_limit, 1); *plen = 2; *pptr = &sc->sc_volume_limit; } else { *plen = 0; } return (0); } else if ((req->bmRequestType == UT_READ_CLASS_INTERFACE) && (req->bRequest == 0x81 /* get value */ )) { if (offset == 0) { USETW(sc->sc_volume_setting, 0x2000); *plen = sizeof(sc->sc_volume_setting); *pptr = &sc->sc_volume_setting; } else { *plen = 0; } return (0); } else if ((req->bmRequestType == UT_WRITE_CLASS_INTERFACE) && (req->bRequest == 0x01 /* set value */ )) { if (offset == 0) { *plen = sizeof(sc->sc_volume_setting); *pptr = &sc->sc_volume_setting; } else { *plen = 0; } return (0); } else if ((req->bmRequestType == UT_WRITE_CLASS_ENDPOINT) && (req->bRequest == 0x01 /* set value */ )) { if (offset == 0) { *plen = sizeof(sc->sc_sample_rate); *pptr = &sc->sc_sample_rate; } else { *plen = 0; } return (0); } } return (ENXIO); /* use builtin handler */ } Index: head/sys/dev/usb/gadget/g_keyboard.c =================================================================== --- head/sys/dev/usb/gadget/g_keyboard.c (revision 276700) +++ head/sys/dev/usb/gadget/g_keyboard.c (revision 276701) @@ -1,411 +1,411 @@ /*- * Copyright (c) 2010 Hans Petter Selasky. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * HID spec: http://www.usb.org/developers/devclass_docs/HID1_11.pdf */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usb_if.h" #define USB_DEBUG_VAR g_keyboard_debug #include #include static SYSCTL_NODE(_hw_usb, OID_AUTO, g_keyboard, CTLFLAG_RW, 0, "USB keyboard gadget"); #ifdef USB_DEBUG static int g_keyboard_debug = 0; -SYSCTL_INT(_hw_usb_g_keyboard, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_g_keyboard, OID_AUTO, debug, CTLFLAG_RWTUN, &g_keyboard_debug, 0, "Debug level"); #endif static int g_keyboard_mode = 0; -SYSCTL_INT(_hw_usb_g_keyboard, OID_AUTO, mode, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_g_keyboard, OID_AUTO, mode, CTLFLAG_RWTUN, &g_keyboard_mode, 0, "Mode selection"); static int g_keyboard_key_press_interval = 1000; -SYSCTL_INT(_hw_usb_g_keyboard, OID_AUTO, key_press_interval, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_g_keyboard, OID_AUTO, key_press_interval, CTLFLAG_RWTUN, &g_keyboard_key_press_interval, 0, "Key Press Interval in milliseconds"); static char g_keyboard_key_press_pattern[G_KEYBOARD_MAX_STRLEN]; SYSCTL_STRING(_hw_usb_g_keyboard, OID_AUTO, key_press_pattern, CTLFLAG_RW, g_keyboard_key_press_pattern, sizeof(g_keyboard_key_press_pattern), "Key Press Patterns"); #define UPROTO_BOOT_KEYBOARD 1 #define G_KEYBOARD_NMOD 8 /* units */ #define G_KEYBOARD_NKEYCODE 6 /* units */ struct g_keyboard_data { uint8_t modifiers; #define MOD_CONTROL_L 0x01 #define MOD_CONTROL_R 0x10 #define MOD_SHIFT_L 0x02 #define MOD_SHIFT_R 0x20 #define MOD_ALT_L 0x04 #define MOD_ALT_R 0x40 #define MOD_WIN_L 0x08 #define MOD_WIN_R 0x80 uint8_t reserved; uint8_t keycode[G_KEYBOARD_NKEYCODE]; }; enum { G_KEYBOARD_INTR_DT, G_KEYBOARD_N_TRANSFER, }; struct g_keyboard_softc { struct mtx sc_mtx; struct usb_callout sc_callout; struct g_keyboard_data sc_data[2]; struct usb_xfer *sc_xfer[G_KEYBOARD_N_TRANSFER]; int sc_mode; int sc_state; int sc_pattern_len; char sc_pattern[G_KEYBOARD_MAX_STRLEN]; uint8_t sc_led_state[4]; }; static device_probe_t g_keyboard_probe; static device_attach_t g_keyboard_attach; static device_detach_t g_keyboard_detach; static usb_handle_request_t g_keyboard_handle_request; static usb_callback_t g_keyboard_intr_callback; static devclass_t g_keyboard_devclass; static device_method_t g_keyboard_methods[] = { /* USB interface */ DEVMETHOD(usb_handle_request, g_keyboard_handle_request), /* Device interface */ DEVMETHOD(device_probe, g_keyboard_probe), DEVMETHOD(device_attach, g_keyboard_attach), DEVMETHOD(device_detach, g_keyboard_detach), DEVMETHOD_END }; static driver_t g_keyboard_driver = { .name = "g_keyboard", .methods = g_keyboard_methods, .size = sizeof(struct g_keyboard_softc), }; DRIVER_MODULE(g_keyboard, uhub, g_keyboard_driver, g_keyboard_devclass, 0, 0); MODULE_DEPEND(g_keyboard, usb, 1, 1, 1); static const struct usb_config g_keyboard_config[G_KEYBOARD_N_TRANSFER] = { [G_KEYBOARD_INTR_DT] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.ext_buffer = 1,.pipe_bof = 1,}, .bufsize = sizeof(struct g_keyboard_data), .callback = &g_keyboard_intr_callback, .frames = 2, .usb_mode = USB_MODE_DEVICE, }, }; static void g_keyboard_timeout(void *arg); static void g_keyboard_timeout_reset(struct g_keyboard_softc *sc) { int i = g_keyboard_key_press_interval; if (i <= 0) i = 1; else if (i > 1023) i = 1023; i = USB_MS_TO_TICKS(i); usb_callout_reset(&sc->sc_callout, i, &g_keyboard_timeout, sc); } static void g_keyboard_timeout(void *arg) { struct g_keyboard_softc *sc = arg; sc->sc_mode = g_keyboard_mode; memcpy(sc->sc_pattern, g_keyboard_key_press_pattern, sizeof(sc->sc_pattern)); sc->sc_pattern[G_KEYBOARD_MAX_STRLEN - 1] = 0; sc->sc_pattern_len = strlen(sc->sc_pattern); DPRINTFN(11, "Timeout %p\n", sc->sc_xfer[G_KEYBOARD_INTR_DT]); usbd_transfer_start(sc->sc_xfer[G_KEYBOARD_INTR_DT]); g_keyboard_timeout_reset(sc); } static int g_keyboard_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); DPRINTFN(11, "\n"); if (uaa->usb_mode != USB_MODE_DEVICE) return (ENXIO); if ((uaa->info.bInterfaceClass == UICLASS_HID) && (uaa->info.bInterfaceSubClass == UISUBCLASS_BOOT) && (uaa->info.bInterfaceProtocol == UPROTO_BOOT_KEYBOARD)) return (0); return (ENXIO); } static int g_keyboard_attach(device_t dev) { struct g_keyboard_softc *sc = device_get_softc(dev); struct usb_attach_arg *uaa = device_get_ivars(dev); int error; DPRINTFN(11, "\n"); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "g_keyboard", NULL, MTX_DEF); usb_callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); sc->sc_mode = G_KEYBOARD_MODE_SILENT; error = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex, sc->sc_xfer, g_keyboard_config, G_KEYBOARD_N_TRANSFER, sc, &sc->sc_mtx); if (error) { DPRINTF("error=%s\n", usbd_errstr(error)); goto detach; } mtx_lock(&sc->sc_mtx); g_keyboard_timeout_reset(sc); mtx_unlock(&sc->sc_mtx); return (0); /* success */ detach: g_keyboard_detach(dev); return (ENXIO); /* error */ } static int g_keyboard_detach(device_t dev) { struct g_keyboard_softc *sc = device_get_softc(dev); DPRINTF("\n"); mtx_lock(&sc->sc_mtx); usb_callout_stop(&sc->sc_callout); mtx_unlock(&sc->sc_mtx); usbd_transfer_unsetup(sc->sc_xfer, G_KEYBOARD_N_TRANSFER); usb_callout_drain(&sc->sc_callout); mtx_destroy(&sc->sc_mtx); return (0); } static uint8_t g_keyboard_get_keycode(struct g_keyboard_softc *sc, int index) { int key; int mod = sc->sc_pattern_len; if (mod == 0) index = 0; else index %= mod; if ((index >= 0) && (index < sc->sc_pattern_len)) key = sc->sc_pattern[index]; else key = 'a'; if (key >= 'a' && key <= 'z') return (key - 'a' + 0x04); else return (0x04); } static void g_keyboard_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct g_keyboard_softc *sc = usbd_xfer_softc(xfer); int actlen; int aframes; usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL); DPRINTF("st=%d aframes=%d actlen=%d bytes\n", USB_GET_STATE(xfer), aframes, actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: break; case USB_ST_SETUP: tr_setup: if (sc->sc_mode == G_KEYBOARD_MODE_SILENT) { memset(&sc->sc_data, 0, sizeof(sc->sc_data)); usbd_xfer_set_frame_data(xfer, 0, &sc->sc_data[0], sizeof(sc->sc_data[0])); usbd_xfer_set_frame_data(xfer, 1, &sc->sc_data[1], sizeof(sc->sc_data[1])); usbd_xfer_set_frames(xfer, 2); usbd_transfer_submit(xfer); } else if (sc->sc_mode == G_KEYBOARD_MODE_PATTERN) { memset(&sc->sc_data, 0, sizeof(sc->sc_data)); if ((sc->sc_state < 0) || (sc->sc_state >= G_KEYBOARD_MAX_STRLEN)) sc->sc_state = 0; switch (sc->sc_state % 6) { case 0: sc->sc_data[0].keycode[0] = g_keyboard_get_keycode(sc, sc->sc_state + 0); case 1: sc->sc_data[0].keycode[1] = g_keyboard_get_keycode(sc, sc->sc_state + 1); case 2: sc->sc_data[0].keycode[2] = g_keyboard_get_keycode(sc, sc->sc_state + 2); case 3: sc->sc_data[0].keycode[3] = g_keyboard_get_keycode(sc, sc->sc_state + 3); case 4: sc->sc_data[0].keycode[4] = g_keyboard_get_keycode(sc, sc->sc_state + 4); default: sc->sc_data[0].keycode[5] = g_keyboard_get_keycode(sc, sc->sc_state + 5); } sc->sc_state++; usbd_xfer_set_frame_data(xfer, 0, &sc->sc_data[0], sizeof(sc->sc_data[0])); usbd_xfer_set_frame_data(xfer, 1, &sc->sc_data[1], sizeof(sc->sc_data[1])); usbd_xfer_set_frames(xfer, 2); usbd_transfer_submit(xfer); } break; default: /* Error */ DPRINTF("error=%s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static int g_keyboard_handle_request(device_t dev, const void *preq, void **pptr, uint16_t *plen, uint16_t offset, uint8_t *pstate) { struct g_keyboard_softc *sc = device_get_softc(dev); const struct usb_device_request *req = preq; uint8_t is_complete = *pstate; if (!is_complete) { if ((req->bmRequestType == UT_WRITE_CLASS_INTERFACE) && (req->bRequest == UR_SET_REPORT) && (req->wValue[0] == 0x00) && (req->wValue[1] == 0x02)) { if (offset == 0) { *plen = sizeof(sc->sc_led_state); *pptr = &sc->sc_led_state; } else { *plen = 0; } return (0); } else if ((req->bmRequestType == UT_WRITE_CLASS_INTERFACE) && (req->bRequest == UR_SET_PROTOCOL) && (req->wValue[0] == 0x00) && (req->wValue[1] == 0x00)) { *plen = 0; return (0); } else if ((req->bmRequestType == UT_WRITE_CLASS_INTERFACE) && (req->bRequest == UR_SET_IDLE)) { *plen = 0; return (0); } } return (ENXIO); /* use builtin handler */ } Index: head/sys/dev/usb/gadget/g_modem.c =================================================================== --- head/sys/dev/usb/gadget/g_modem.c (revision 276700) +++ head/sys/dev/usb/gadget/g_modem.c (revision 276701) @@ -1,544 +1,544 @@ /*- * Copyright (c) 2010 Hans Petter Selasky. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Comm Class spec: http://www.usb.org/developers/devclass_docs/usbccs10.pdf * http://www.usb.org/developers/devclass_docs/usbcdc11.pdf * http://www.usb.org/developers/devclass_docs/cdc_wmc10.zip */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usb_if.h" #define USB_DEBUG_VAR g_modem_debug #include #include enum { G_MODEM_INTR_DT, G_MODEM_BULK_RD, G_MODEM_BULK_WR, G_MODEM_N_TRANSFER, }; struct g_modem_softc { struct mtx sc_mtx; struct usb_callout sc_callout; struct usb_callout sc_watchdog; struct usb_xfer *sc_xfer[G_MODEM_N_TRANSFER]; int sc_mode; int sc_tx_busy; int sc_pattern_len; int sc_throughput; int sc_tx_interval; char sc_pattern[G_MODEM_MAX_STRLEN]; uint16_t sc_data_len; uint8_t sc_data_buf[G_MODEM_BUFSIZE]; uint8_t sc_line_coding[32]; uint8_t sc_abstract_state[32]; }; static SYSCTL_NODE(_hw_usb, OID_AUTO, g_modem, CTLFLAG_RW, 0, "USB modem gadget"); #ifdef USB_DEBUG static int g_modem_debug = 0; -SYSCTL_INT(_hw_usb_g_modem, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_g_modem, OID_AUTO, debug, CTLFLAG_RWTUN, &g_modem_debug, 0, "Debug level"); #endif static int g_modem_mode = 0; -SYSCTL_INT(_hw_usb_g_modem, OID_AUTO, mode, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_g_modem, OID_AUTO, mode, CTLFLAG_RWTUN, &g_modem_mode, 0, "Mode selection"); static int g_modem_pattern_interval = 1000; -SYSCTL_INT(_hw_usb_g_modem, OID_AUTO, pattern_interval, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_g_modem, OID_AUTO, pattern_interval, CTLFLAG_RWTUN, &g_modem_pattern_interval, 0, "Pattern interval in milliseconds"); static char g_modem_pattern_data[G_MODEM_MAX_STRLEN]; SYSCTL_STRING(_hw_usb_g_modem, OID_AUTO, pattern, CTLFLAG_RW, &g_modem_pattern_data, sizeof(g_modem_pattern_data), "Data pattern"); static int g_modem_throughput; SYSCTL_INT(_hw_usb_g_modem, OID_AUTO, throughput, CTLFLAG_RD, &g_modem_throughput, sizeof(g_modem_throughput), "Throughput in bytes per second"); static device_probe_t g_modem_probe; static device_attach_t g_modem_attach; static device_detach_t g_modem_detach; static usb_handle_request_t g_modem_handle_request; static usb_callback_t g_modem_intr_callback; static usb_callback_t g_modem_bulk_read_callback; static usb_callback_t g_modem_bulk_write_callback; static void g_modem_timeout(void *arg); static devclass_t g_modem_devclass; static device_method_t g_modem_methods[] = { /* USB interface */ DEVMETHOD(usb_handle_request, g_modem_handle_request), /* Device interface */ DEVMETHOD(device_probe, g_modem_probe), DEVMETHOD(device_attach, g_modem_attach), DEVMETHOD(device_detach, g_modem_detach), DEVMETHOD_END }; static driver_t g_modem_driver = { .name = "g_modem", .methods = g_modem_methods, .size = sizeof(struct g_modem_softc), }; DRIVER_MODULE(g_modem, uhub, g_modem_driver, g_modem_devclass, 0, 0); MODULE_DEPEND(g_modem, usb, 1, 1, 1); static const struct usb_config g_modem_config[G_MODEM_N_TRANSFER] = { [G_MODEM_INTR_DT] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_TX, .flags = {.ext_buffer = 1,.pipe_bof = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = &g_modem_intr_callback, .frames = 1, .usb_mode = USB_MODE_DEVICE, .if_index = 0, }, [G_MODEM_BULK_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_RX, .flags = {.ext_buffer = 1,.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = G_MODEM_BUFSIZE, .callback = &g_modem_bulk_read_callback, .frames = 1, .usb_mode = USB_MODE_DEVICE, .if_index = 1, }, [G_MODEM_BULK_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_TX, .flags = {.ext_buffer = 1,.pipe_bof = 1,}, .bufsize = G_MODEM_BUFSIZE, .callback = &g_modem_bulk_write_callback, .frames = 1, .usb_mode = USB_MODE_DEVICE, .if_index = 1, }, }; static void g_modem_timeout_reset(struct g_modem_softc *sc) { int i = g_modem_pattern_interval; sc->sc_tx_interval = i; if (i <= 0) i = 1; else if (i > 1023) i = 1023; i = USB_MS_TO_TICKS(i); usb_callout_reset(&sc->sc_callout, i, &g_modem_timeout, sc); } static void g_modem_timeout(void *arg) { struct g_modem_softc *sc = arg; sc->sc_mode = g_modem_mode; memcpy(sc->sc_pattern, g_modem_pattern_data, sizeof(sc->sc_pattern)); sc->sc_pattern[G_MODEM_MAX_STRLEN - 1] = 0; sc->sc_pattern_len = strlen(sc->sc_pattern); DPRINTFN(11, "Timeout %p\n", sc->sc_xfer[G_MODEM_INTR_DT]); usbd_transfer_start(sc->sc_xfer[G_MODEM_BULK_WR]); usbd_transfer_start(sc->sc_xfer[G_MODEM_BULK_RD]); g_modem_timeout_reset(sc); } static void g_modem_watchdog(void *arg); static void g_modem_watchdog_reset(struct g_modem_softc *sc) { usb_callout_reset(&sc->sc_watchdog, hz, &g_modem_watchdog, sc); } static void g_modem_watchdog(void *arg) { struct g_modem_softc *sc = arg; int i; i = sc->sc_throughput; sc->sc_throughput = 0; g_modem_throughput = i; g_modem_watchdog_reset(sc); } static int g_modem_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); DPRINTFN(11, "\n"); if (uaa->usb_mode != USB_MODE_DEVICE) return (ENXIO); if ((uaa->info.bInterfaceClass == UICLASS_CDC) && (uaa->info.bInterfaceSubClass == UISUBCLASS_ABSTRACT_CONTROL_MODEL) && (uaa->info.bInterfaceProtocol == UIPROTO_CDC_AT)) return (0); return (ENXIO); } static int g_modem_attach(device_t dev) { struct g_modem_softc *sc = device_get_softc(dev); struct usb_attach_arg *uaa = device_get_ivars(dev); int error; uint8_t iface_index[2]; DPRINTFN(11, "\n"); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "g_modem", NULL, MTX_DEF); usb_callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); usb_callout_init_mtx(&sc->sc_watchdog, &sc->sc_mtx, 0); sc->sc_mode = G_MODEM_MODE_SILENT; iface_index[0] = uaa->info.bIfaceIndex; iface_index[1] = uaa->info.bIfaceIndex + 1; error = usbd_transfer_setup(uaa->device, iface_index, sc->sc_xfer, g_modem_config, G_MODEM_N_TRANSFER, sc, &sc->sc_mtx); if (error) { DPRINTF("error=%s\n", usbd_errstr(error)); goto detach; } usbd_set_parent_iface(uaa->device, iface_index[1], iface_index[0]); mtx_lock(&sc->sc_mtx); g_modem_timeout_reset(sc); g_modem_watchdog_reset(sc); mtx_unlock(&sc->sc_mtx); return (0); /* success */ detach: g_modem_detach(dev); return (ENXIO); /* error */ } static int g_modem_detach(device_t dev) { struct g_modem_softc *sc = device_get_softc(dev); DPRINTF("\n"); mtx_lock(&sc->sc_mtx); usb_callout_stop(&sc->sc_callout); usb_callout_stop(&sc->sc_watchdog); mtx_unlock(&sc->sc_mtx); usbd_transfer_unsetup(sc->sc_xfer, G_MODEM_N_TRANSFER); usb_callout_drain(&sc->sc_callout); usb_callout_drain(&sc->sc_watchdog); mtx_destroy(&sc->sc_mtx); return (0); } static void g_modem_intr_callback(struct usb_xfer *xfer, usb_error_t error) { int actlen; int aframes; usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL); DPRINTF("st=%d aframes=%d actlen=%d bytes\n", USB_GET_STATE(xfer), aframes, actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: break; case USB_ST_SETUP: tr_setup: break; default: /* Error */ DPRINTF("error=%s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void g_modem_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct g_modem_softc *sc = usbd_xfer_softc(xfer); int actlen; int aframes; int mod; int x; int max; usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL); DPRINTF("st=%d aframes=%d actlen=%d bytes\n", USB_GET_STATE(xfer), aframes, actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: sc->sc_tx_busy = 0; sc->sc_throughput += actlen; if (sc->sc_mode == G_MODEM_MODE_LOOP) { /* start loop */ usbd_transfer_start(sc->sc_xfer[G_MODEM_BULK_RD]); break; } else if ((sc->sc_mode == G_MODEM_MODE_PATTERN) && (sc->sc_tx_interval != 0)) { /* wait for next timeout */ break; } case USB_ST_SETUP: tr_setup: if (sc->sc_mode == G_MODEM_MODE_PATTERN) { mod = sc->sc_pattern_len; max = sc->sc_tx_interval ? mod : G_MODEM_BUFSIZE; if (mod == 0) { for (x = 0; x != max; x++) sc->sc_data_buf[x] = x % 255; } else { for (x = 0; x != max; x++) sc->sc_data_buf[x] = sc->sc_pattern[x % mod]; } usbd_xfer_set_frame_data(xfer, 0, sc->sc_data_buf, max); usbd_xfer_set_interval(xfer, 0); usbd_xfer_set_frames(xfer, 1); usbd_transfer_submit(xfer); } else if (sc->sc_mode == G_MODEM_MODE_LOOP) { if (sc->sc_tx_busy == 0) break; x = sc->sc_tx_interval; if (x < 0) x = 0; else if (x > 256) x = 256; usbd_xfer_set_frame_data(xfer, 0, sc->sc_data_buf, sc->sc_data_len); usbd_xfer_set_interval(xfer, x); usbd_xfer_set_frames(xfer, 1); usbd_transfer_submit(xfer); } else { sc->sc_tx_busy = 0; } break; default: /* Error */ DPRINTF("error=%s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void g_modem_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct g_modem_softc *sc = usbd_xfer_softc(xfer); int actlen; int aframes; usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL); DPRINTF("st=%d aframes=%d actlen=%d bytes\n", USB_GET_STATE(xfer), aframes, actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: sc->sc_throughput += actlen; if (sc->sc_mode == G_MODEM_MODE_LOOP) { sc->sc_tx_busy = 1; sc->sc_data_len = actlen; usbd_transfer_start(sc->sc_xfer[G_MODEM_BULK_WR]); break; } case USB_ST_SETUP: tr_setup: if ((sc->sc_mode == G_MODEM_MODE_SILENT) || (sc->sc_tx_busy != 0)) break; usbd_xfer_set_frame_data(xfer, 0, sc->sc_data_buf, G_MODEM_BUFSIZE); usbd_xfer_set_frames(xfer, 1); usbd_transfer_submit(xfer); break; default: /* Error */ DPRINTF("error=%s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static int g_modem_handle_request(device_t dev, const void *preq, void **pptr, uint16_t *plen, uint16_t offset, uint8_t *pstate) { struct g_modem_softc *sc = device_get_softc(dev); const struct usb_device_request *req = preq; uint8_t is_complete = *pstate; if (!is_complete) { if ((req->bmRequestType == UT_WRITE_CLASS_INTERFACE) && (req->bRequest == UCDC_SET_LINE_CODING) && (req->wValue[0] == 0x00) && (req->wValue[1] == 0x00)) { if (offset == 0) { *plen = sizeof(sc->sc_line_coding); *pptr = &sc->sc_line_coding; } else { *plen = 0; } return (0); } else if ((req->bmRequestType == UT_WRITE_CLASS_INTERFACE) && (req->bRequest == UCDC_SET_COMM_FEATURE)) { if (offset == 0) { *plen = sizeof(sc->sc_abstract_state); *pptr = &sc->sc_abstract_state; } else { *plen = 0; } return (0); } else if ((req->bmRequestType == UT_WRITE_CLASS_INTERFACE) && (req->bRequest == UCDC_SET_CONTROL_LINE_STATE)) { *plen = 0; return (0); } else if ((req->bmRequestType == UT_WRITE_CLASS_INTERFACE) && (req->bRequest == UCDC_SEND_BREAK)) { *plen = 0; return (0); } } return (ENXIO); /* use builtin handler */ } Index: head/sys/dev/usb/gadget/g_mouse.c =================================================================== --- head/sys/dev/usb/gadget/g_mouse.c (revision 276700) +++ head/sys/dev/usb/gadget/g_mouse.c (revision 276701) @@ -1,456 +1,456 @@ /*- * Copyright (c) 2010 Hans Petter Selasky. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * HID spec: http://www.usb.org/developers/devclass_docs/HID1_11.pdf */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usb_if.h" #define USB_DEBUG_VAR g_mouse_debug #include #include static SYSCTL_NODE(_hw_usb, OID_AUTO, g_mouse, CTLFLAG_RW, 0, "USB mouse gadget"); #ifdef USB_DEBUG static int g_mouse_debug = 0; -SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, debug, CTLFLAG_RWTUN, &g_mouse_debug, 0, "Debug level"); #endif static int g_mouse_mode = 0; -SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, mode, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, mode, CTLFLAG_RWTUN, &g_mouse_mode, 0, "Mode selection"); static int g_mouse_button_press_interval = 0; -SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, button_press_interval, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, button_press_interval, CTLFLAG_RWTUN, &g_mouse_button_press_interval, 0, "Mouse button update interval in milliseconds"); static int g_mouse_cursor_update_interval = 1023; -SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, cursor_update_interval, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, cursor_update_interval, CTLFLAG_RWTUN, &g_mouse_cursor_update_interval, 0, "Mouse cursor update interval in milliseconds"); static int g_mouse_cursor_radius = 128; -SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, cursor_radius, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_g_mouse, OID_AUTO, cursor_radius, CTLFLAG_RWTUN, &g_mouse_cursor_radius, 0, "Mouse cursor radius in pixels"); struct g_mouse_data { uint8_t buttons; #define BUT_0 0x01 #define BUT_1 0x02 #define BUT_2 0x04 int8_t dx; int8_t dy; int8_t dz; }; enum { G_MOUSE_INTR_DT, G_MOUSE_N_TRANSFER, }; struct g_mouse_softc { struct mtx sc_mtx; struct usb_callout sc_button_press_callout; struct usb_callout sc_cursor_update_callout; struct g_mouse_data sc_data; struct usb_xfer *sc_xfer[G_MOUSE_N_TRANSFER]; int sc_mode; int sc_radius; int sc_last_x_state; int sc_last_y_state; int sc_curr_x_state; int sc_curr_y_state; int sc_tick; uint8_t sc_do_cursor_update; uint8_t sc_do_button_update; }; static device_probe_t g_mouse_probe; static device_attach_t g_mouse_attach; static device_detach_t g_mouse_detach; static usb_handle_request_t g_mouse_handle_request; static usb_callback_t g_mouse_intr_callback; static devclass_t g_mouse_devclass; static device_method_t g_mouse_methods[] = { /* USB interface */ DEVMETHOD(usb_handle_request, g_mouse_handle_request), /* Device interface */ DEVMETHOD(device_probe, g_mouse_probe), DEVMETHOD(device_attach, g_mouse_attach), DEVMETHOD(device_detach, g_mouse_detach), DEVMETHOD_END }; static driver_t g_mouse_driver = { .name = "g_mouse", .methods = g_mouse_methods, .size = sizeof(struct g_mouse_softc), }; DRIVER_MODULE(g_mouse, uhub, g_mouse_driver, g_mouse_devclass, 0, 0); MODULE_DEPEND(g_mouse, usb, 1, 1, 1); static const struct usb_config g_mouse_config[G_MOUSE_N_TRANSFER] = { [G_MOUSE_INTR_DT] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.ext_buffer = 1,.pipe_bof = 1,}, .bufsize = sizeof(struct g_mouse_data), .callback = &g_mouse_intr_callback, .frames = 1, .usb_mode = USB_MODE_DEVICE, }, }; static void g_mouse_button_press_timeout(void *arg); static void g_mouse_cursor_update_timeout(void *arg); static void g_mouse_button_press_timeout_reset(struct g_mouse_softc *sc) { int i = g_mouse_button_press_interval; if (i <= 0) { sc->sc_data.buttons = 0; sc->sc_do_button_update = 0; } else { sc->sc_do_button_update = 1; } if ((i <= 0) || (i > 1023)) i = 1023; i = USB_MS_TO_TICKS(i); usb_callout_reset(&sc->sc_button_press_callout, i, &g_mouse_button_press_timeout, sc); } static void g_mouse_cursor_update_timeout_reset(struct g_mouse_softc *sc) { int i = g_mouse_cursor_update_interval; if (i <= 0) { sc->sc_data.dx = 0; sc->sc_data.dy = 0; sc->sc_do_cursor_update = 0; sc->sc_tick = 0; } else { sc->sc_do_cursor_update = 1; } if ((i <= 0) || (i > 1023)) i = 1023; i = USB_MS_TO_TICKS(i); usb_callout_reset(&sc->sc_cursor_update_callout, i, &g_mouse_cursor_update_timeout, sc); } static void g_mouse_update_mode_radius(struct g_mouse_softc *sc) { sc->sc_mode = g_mouse_mode; sc->sc_radius = g_mouse_cursor_radius; if (sc->sc_radius < 0) sc->sc_radius = 0; else if (sc->sc_radius > 1023) sc->sc_radius = 1023; } static void g_mouse_button_press_timeout(void *arg) { struct g_mouse_softc *sc = arg; g_mouse_update_mode_radius(sc); DPRINTFN(11, "Timeout %p (button press)\n", sc->sc_xfer[G_MOUSE_INTR_DT]); g_mouse_button_press_timeout_reset(sc); usbd_transfer_start(sc->sc_xfer[G_MOUSE_INTR_DT]); } static void g_mouse_cursor_update_timeout(void *arg) { struct g_mouse_softc *sc = arg; g_mouse_update_mode_radius(sc); DPRINTFN(11, "Timeout %p (cursor update)\n", sc->sc_xfer[G_MOUSE_INTR_DT]); g_mouse_cursor_update_timeout_reset(sc); usbd_transfer_start(sc->sc_xfer[G_MOUSE_INTR_DT]); } static int g_mouse_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); DPRINTFN(11, "\n"); if (uaa->usb_mode != USB_MODE_DEVICE) return (ENXIO); if ((uaa->info.bInterfaceClass == UICLASS_HID) && (uaa->info.bInterfaceSubClass == UISUBCLASS_BOOT) && (uaa->info.bInterfaceProtocol == UIPROTO_MOUSE)) return (0); return (ENXIO); } static int g_mouse_attach(device_t dev) { struct g_mouse_softc *sc = device_get_softc(dev); struct usb_attach_arg *uaa = device_get_ivars(dev); int error; DPRINTFN(11, "\n"); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "g_mouse", NULL, MTX_DEF); usb_callout_init_mtx(&sc->sc_button_press_callout, &sc->sc_mtx, 0); usb_callout_init_mtx(&sc->sc_cursor_update_callout, &sc->sc_mtx, 0); sc->sc_mode = G_MOUSE_MODE_SILENT; error = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex, sc->sc_xfer, g_mouse_config, G_MOUSE_N_TRANSFER, sc, &sc->sc_mtx); if (error) { DPRINTF("error=%s\n", usbd_errstr(error)); goto detach; } mtx_lock(&sc->sc_mtx); g_mouse_button_press_timeout_reset(sc); g_mouse_cursor_update_timeout_reset(sc); mtx_unlock(&sc->sc_mtx); return (0); /* success */ detach: g_mouse_detach(dev); return (ENXIO); /* error */ } static int g_mouse_detach(device_t dev) { struct g_mouse_softc *sc = device_get_softc(dev); DPRINTF("\n"); mtx_lock(&sc->sc_mtx); usb_callout_stop(&sc->sc_button_press_callout); usb_callout_stop(&sc->sc_cursor_update_callout); mtx_unlock(&sc->sc_mtx); usbd_transfer_unsetup(sc->sc_xfer, G_MOUSE_N_TRANSFER); usb_callout_drain(&sc->sc_button_press_callout); usb_callout_drain(&sc->sc_cursor_update_callout); mtx_destroy(&sc->sc_mtx); return (0); } static void g_mouse_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct g_mouse_softc *sc = usbd_xfer_softc(xfer); int actlen; int aframes; int dx; int dy; int radius; usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL); DPRINTF("st=%d aframes=%d actlen=%d bytes\n", USB_GET_STATE(xfer), aframes, actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (!(sc->sc_do_cursor_update || sc->sc_do_button_update)) break; case USB_ST_SETUP: tr_setup: if (sc->sc_do_cursor_update) { sc->sc_do_cursor_update = 0; sc->sc_tick += 80; if ((sc->sc_tick < 0) || (sc->sc_tick > 7999)) sc->sc_tick = 0; } if (sc->sc_do_button_update) { sc->sc_do_button_update = 0; sc->sc_data.buttons ^= BUT_0; } radius = sc->sc_radius; switch (sc->sc_mode) { case G_MOUSE_MODE_SILENT: sc->sc_data.buttons = 0; break; case G_MOUSE_MODE_SPIRAL: radius = (radius * (8000-sc->sc_tick)) / 8000; case G_MOUSE_MODE_CIRCLE: /* TODO */ sc->sc_curr_y_state = 0; sc->sc_curr_x_state = 0; break; case G_MOUSE_MODE_BOX: if (sc->sc_tick < 2000) { sc->sc_curr_x_state = (sc->sc_tick * radius) / 2000; sc->sc_curr_y_state = 0; } else if (sc->sc_tick < 4000) { sc->sc_curr_x_state = radius; sc->sc_curr_y_state = -(((sc->sc_tick - 2000) * radius) / 2000); } else if (sc->sc_tick < 6000) { sc->sc_curr_x_state = radius - (((sc->sc_tick - 4000) * radius) / 2000); sc->sc_curr_y_state = -radius; } else { sc->sc_curr_x_state = 0; sc->sc_curr_y_state = -radius + (((sc->sc_tick - 6000) * radius) / 2000); } break; default: break; } dx = sc->sc_curr_x_state - sc->sc_last_x_state; dy = sc->sc_curr_y_state - sc->sc_last_y_state; if (dx < -63) dx = -63; else if (dx > 63) dx = 63; if (dy < -63) dy = -63; else if (dy > 63) dy = 63; sc->sc_last_x_state += dx; sc->sc_last_y_state += dy; sc->sc_data.dx = dx; sc->sc_data.dy = dy; usbd_xfer_set_frame_data(xfer, 0, &sc->sc_data, sizeof(sc->sc_data)); usbd_xfer_set_frames(xfer, 1); usbd_transfer_submit(xfer); break; default: /* Error */ DPRINTF("error=%s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static int g_mouse_handle_request(device_t dev, const void *preq, void **pptr, uint16_t *plen, uint16_t offset, uint8_t *pstate) { const struct usb_device_request *req = preq; uint8_t is_complete = *pstate; if (!is_complete) { if ((req->bmRequestType == UT_WRITE_CLASS_INTERFACE) && (req->bRequest == UR_SET_PROTOCOL) && (req->wValue[0] == 0x00) && (req->wValue[1] == 0x00)) { *plen = 0; return (0); } } return (ENXIO); /* use builtin handler */ } Index: head/sys/dev/usb/input/atp.c =================================================================== --- head/sys/dev/usb/input/atp.c (revision 276700) +++ head/sys/dev/usb/input/atp.c (revision 276701) @@ -1,2632 +1,2632 @@ /*- * Copyright (c) 2014 Rohit Grover * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Some tables, structures, definitions and constant values for the * touchpad protocol has been copied from Linux's * "drivers/input/mouse/bcm5974.c" which has the following copyright * holders under GPLv2. All device specific code in this driver has * been written from scratch. The decoding algorithm is based on * output from FreeBSD's usbdump. * * Copyright (C) 2008 Henrik Rydberg (rydberg@euromail.se) * Copyright (C) 2008 Scott Shawcroft (scott.shawcroft@gmail.com) * Copyright (C) 2001-2004 Greg Kroah-Hartman (greg@kroah.com) * Copyright (C) 2005 Johannes Berg (johannes@sipsolutions.net) * Copyright (C) 2005 Stelian Pop (stelian@popies.net) * Copyright (C) 2005 Frank Arnold (frank@scirocco-5v-turbo.de) * Copyright (C) 2005 Peter Osterlund (petero2@telia.com) * Copyright (C) 2005 Michael Hanselmann (linux-kernel@hansmi.ch) * Copyright (C) 2006 Nicolas Boichat (nicolas@boichat.ch) */ /* * Author's note: 'atp' supports two distinct families of Apple trackpad * products: the older Fountain/Geyser and the latest Wellspring trackpads. * The first version made its appearance with FreeBSD 8 and worked only with * the Fountain/Geyser hardware. A fork of this driver for Wellspring was * contributed by Huang Wen Hui. This driver unifies the Wellspring effort * and also improves upon the original work. * * I'm grateful to Stephan Scheunig, Angela Naegele, and Nokia IT-support * for helping me with access to hardware. Thanks also go to Nokia for * giving me an opportunity to do this work. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR atp_debug #include #include #define ATP_DRIVER_NAME "atp" /* * Driver specific options: the following options may be set by * `options' statements in the kernel configuration file. */ /* The divisor used to translate sensor reported positions to mickeys. */ #ifndef ATP_SCALE_FACTOR #define ATP_SCALE_FACTOR 16 #endif /* Threshold for small movement noise (in mickeys) */ #ifndef ATP_SMALL_MOVEMENT_THRESHOLD #define ATP_SMALL_MOVEMENT_THRESHOLD 30 #endif /* Threshold of instantaneous deltas beyond which movement is considered fast.*/ #ifndef ATP_FAST_MOVEMENT_TRESHOLD #define ATP_FAST_MOVEMENT_TRESHOLD 150 #endif /* * This is the age in microseconds beyond which a touch is considered * to be a slide; and therefore a tap event isn't registered. */ #ifndef ATP_TOUCH_TIMEOUT #define ATP_TOUCH_TIMEOUT 125000 #endif #ifndef ATP_IDLENESS_THRESHOLD #define ATP_IDLENESS_THRESHOLD 10 #endif #ifndef FG_SENSOR_NOISE_THRESHOLD #define FG_SENSOR_NOISE_THRESHOLD 2 #endif /* * A double-tap followed by a single-finger slide is treated as a * special gesture. The driver responds to this gesture by assuming a * virtual button-press for the lifetime of the slide. The following * threshold is the maximum time gap (in microseconds) between the two * tap events preceding the slide for such a gesture. */ #ifndef ATP_DOUBLE_TAP_N_DRAG_THRESHOLD #define ATP_DOUBLE_TAP_N_DRAG_THRESHOLD 200000 #endif /* * The wait duration in ticks after losing a touch contact before * zombied strokes are reaped and turned into button events. */ #define ATP_ZOMBIE_STROKE_REAP_INTERVAL (hz / 20) /* 50 ms */ /* The multiplier used to translate sensor reported positions to mickeys. */ #define FG_SCALE_FACTOR 380 /* * The movement threshold for a stroke; this is the maximum difference * in position which will be resolved as a continuation of a stroke * component. */ #define FG_MAX_DELTA_MICKEYS ((3 * (FG_SCALE_FACTOR)) >> 1) /* Distance-squared threshold for matching a finger with a known stroke */ #ifndef WSP_MAX_ALLOWED_MATCH_DISTANCE_SQ #define WSP_MAX_ALLOWED_MATCH_DISTANCE_SQ 1000000 #endif /* Ignore pressure spans with cumulative press. below this value. */ #define FG_PSPAN_MIN_CUM_PRESSURE 10 /* Maximum allowed width for pressure-spans.*/ #define FG_PSPAN_MAX_WIDTH 4 /* end of driver specific options */ /* Tunables */ static SYSCTL_NODE(_hw_usb, OID_AUTO, atp, CTLFLAG_RW, 0, "USB ATP"); #ifdef USB_DEBUG enum atp_log_level { ATP_LLEVEL_DISABLED = 0, ATP_LLEVEL_ERROR, ATP_LLEVEL_DEBUG, /* for troubleshooting */ ATP_LLEVEL_INFO, /* for diagnostics */ }; static int atp_debug = ATP_LLEVEL_ERROR; /* the default is to only log errors */ -SYSCTL_INT(_hw_usb_atp, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_atp, OID_AUTO, debug, CTLFLAG_RWTUN, &atp_debug, ATP_LLEVEL_ERROR, "ATP debug level"); #endif /* USB_DEBUG */ static u_int atp_touch_timeout = ATP_TOUCH_TIMEOUT; -SYSCTL_UINT(_hw_usb_atp, OID_AUTO, touch_timeout, CTLFLAG_RW, +SYSCTL_UINT(_hw_usb_atp, OID_AUTO, touch_timeout, CTLFLAG_RWTUN, &atp_touch_timeout, 125000, "age threshold in microseconds for a touch"); static u_int atp_double_tap_threshold = ATP_DOUBLE_TAP_N_DRAG_THRESHOLD; -SYSCTL_UINT(_hw_usb_atp, OID_AUTO, double_tap_threshold, CTLFLAG_RW, +SYSCTL_UINT(_hw_usb_atp, OID_AUTO, double_tap_threshold, CTLFLAG_RWTUN, &atp_double_tap_threshold, ATP_DOUBLE_TAP_N_DRAG_THRESHOLD, "maximum time in microseconds to allow association between a double-tap and " "drag gesture"); static u_int atp_mickeys_scale_factor = ATP_SCALE_FACTOR; static int atp_sysctl_scale_factor_handler(SYSCTL_HANDLER_ARGS); -SYSCTL_PROC(_hw_usb_atp, OID_AUTO, scale_factor, CTLTYPE_UINT | CTLFLAG_RW, +SYSCTL_PROC(_hw_usb_atp, OID_AUTO, scale_factor, CTLTYPE_UINT | CTLFLAG_RWTUN, &atp_mickeys_scale_factor, sizeof(atp_mickeys_scale_factor), atp_sysctl_scale_factor_handler, "IU", "movement scale factor"); static u_int atp_small_movement_threshold = ATP_SMALL_MOVEMENT_THRESHOLD; -SYSCTL_UINT(_hw_usb_atp, OID_AUTO, small_movement, CTLFLAG_RW, +SYSCTL_UINT(_hw_usb_atp, OID_AUTO, small_movement, CTLFLAG_RWTUN, &atp_small_movement_threshold, ATP_SMALL_MOVEMENT_THRESHOLD, "the small movement black-hole for filtering noise"); static u_int atp_tap_minimum = 1; -SYSCTL_UINT(_hw_usb_atp, OID_AUTO, tap_minimum, CTLFLAG_RW, +SYSCTL_UINT(_hw_usb_atp, OID_AUTO, tap_minimum, CTLFLAG_RWTUN, &atp_tap_minimum, 1, "Minimum number of taps before detection"); /* * Strokes which accumulate at least this amount of absolute movement * from the aggregate of their components are considered as * slides. Unit: mickeys. */ static u_int atp_slide_min_movement = 2 * ATP_SMALL_MOVEMENT_THRESHOLD; -SYSCTL_UINT(_hw_usb_atp, OID_AUTO, slide_min_movement, CTLFLAG_RW, +SYSCTL_UINT(_hw_usb_atp, OID_AUTO, slide_min_movement, CTLFLAG_RWTUN, &atp_slide_min_movement, 2 * ATP_SMALL_MOVEMENT_THRESHOLD, "strokes with at least this amt. of movement are considered slides"); /* * The minimum age of a stroke for it to be considered mature; this * helps filter movements (noise) from immature strokes. Units: interrupts. */ static u_int atp_stroke_maturity_threshold = 4; -SYSCTL_UINT(_hw_usb_atp, OID_AUTO, stroke_maturity_threshold, CTLFLAG_RW, +SYSCTL_UINT(_hw_usb_atp, OID_AUTO, stroke_maturity_threshold, CTLFLAG_RWTUN, &atp_stroke_maturity_threshold, 4, "the minimum age of a stroke for it to be considered mature"); typedef enum atp_trackpad_family { TRACKPAD_FAMILY_FOUNTAIN_GEYSER, TRACKPAD_FAMILY_WELLSPRING, TRACKPAD_FAMILY_MAX /* keep this at the tail end of the enumeration */ } trackpad_family_t; enum fountain_geyser_product { FOUNTAIN, GEYSER1, GEYSER1_17inch, GEYSER2, GEYSER3, GEYSER4, FOUNTAIN_GEYSER_PRODUCT_MAX /* keep this at the end */ }; enum wellspring_product { WELLSPRING1, WELLSPRING2, WELLSPRING3, WELLSPRING4, WELLSPRING4A, WELLSPRING5, WELLSPRING6A, WELLSPRING6, WELLSPRING5A, WELLSPRING7, WELLSPRING7A, WELLSPRING8, WELLSPRING_PRODUCT_MAX /* keep this at the end of the enumeration */ }; /* trackpad header types */ enum fountain_geyser_trackpad_type { FG_TRACKPAD_TYPE_GEYSER1, FG_TRACKPAD_TYPE_GEYSER2, FG_TRACKPAD_TYPE_GEYSER3, FG_TRACKPAD_TYPE_GEYSER4, }; enum wellspring_trackpad_type { WSP_TRACKPAD_TYPE1, /* plain trackpad */ WSP_TRACKPAD_TYPE2, /* button integrated in trackpad */ WSP_TRACKPAD_TYPE3 /* additional header fields since June 2013 */ }; /* * Trackpad family and product and family are encoded together in the * driver_info value associated with a trackpad product. */ #define N_PROD_BITS 8 /* Number of bits used to encode product */ #define ENCODE_DRIVER_INFO(FAMILY, PROD) \ (((FAMILY) << N_PROD_BITS) | (PROD)) #define DECODE_FAMILY_FROM_DRIVER_INFO(INFO) ((INFO) >> N_PROD_BITS) #define DECODE_PRODUCT_FROM_DRIVER_INFO(INFO) \ ((INFO) & ((1 << N_PROD_BITS) - 1)) #define FG_DRIVER_INFO(PRODUCT) \ ENCODE_DRIVER_INFO(TRACKPAD_FAMILY_FOUNTAIN_GEYSER, PRODUCT) #define WELLSPRING_DRIVER_INFO(PRODUCT) \ ENCODE_DRIVER_INFO(TRACKPAD_FAMILY_WELLSPRING, PRODUCT) /* * The following structure captures the state of a pressure span along * an axis. Each contact with the touchpad results in separate * pressure spans along the two axes. */ typedef struct fg_pspan { u_int width; /* in units of sensors */ u_int cum; /* cumulative compression (from all sensors) */ u_int cog; /* center of gravity */ u_int loc; /* location (scaled using the mickeys factor) */ boolean_t matched; /* to track pspans as they match against strokes. */ } fg_pspan; #define FG_MAX_PSPANS_PER_AXIS 3 #define FG_MAX_STROKES (2 * FG_MAX_PSPANS_PER_AXIS) #define WELLSPRING_INTERFACE_INDEX 1 /* trackpad finger data offsets, le16-aligned */ #define WSP_TYPE1_FINGER_DATA_OFFSET (13 * 2) #define WSP_TYPE2_FINGER_DATA_OFFSET (15 * 2) #define WSP_TYPE3_FINGER_DATA_OFFSET (19 * 2) /* trackpad button data offsets */ #define WSP_TYPE2_BUTTON_DATA_OFFSET 15 #define WSP_TYPE3_BUTTON_DATA_OFFSET 23 /* list of device capability bits */ #define HAS_INTEGRATED_BUTTON 1 /* trackpad finger structure - little endian */ struct wsp_finger_sensor_data { int16_t origin; /* zero when switching track finger */ int16_t abs_x; /* absolute x coordinate */ int16_t abs_y; /* absolute y coordinate */ int16_t rel_x; /* relative x coordinate */ int16_t rel_y; /* relative y coordinate */ int16_t tool_major; /* tool area, major axis */ int16_t tool_minor; /* tool area, minor axis */ int16_t orientation; /* 16384 when point, else 15 bit angle */ int16_t touch_major; /* touch area, major axis */ int16_t touch_minor; /* touch area, minor axis */ int16_t unused[3]; /* zeros */ int16_t multi; /* one finger: varies, more fingers: constant */ } __packed; typedef struct wsp_finger { /* to track fingers as they match against strokes. */ boolean_t matched; /* location (scaled using the mickeys factor) */ int x; int y; } wsp_finger_t; #define WSP_MAX_FINGERS 16 #define WSP_SIZEOF_FINGER_SENSOR_DATA sizeof(struct wsp_finger_sensor_data) #define WSP_SIZEOF_ALL_FINGER_DATA (WSP_MAX_FINGERS * \ WSP_SIZEOF_FINGER_SENSOR_DATA) #define WSP_MAX_FINGER_ORIENTATION 16384 #define ATP_SENSOR_DATA_BUF_MAX 1024 #if (ATP_SENSOR_DATA_BUF_MAX < ((WSP_MAX_FINGERS * 14 * 2) + \ WSP_TYPE3_FINGER_DATA_OFFSET)) /* note: 14 * 2 in the above is based on sizeof(struct wsp_finger_sensor_data)*/ #error "ATP_SENSOR_DATA_BUF_MAX is too small" #endif #define ATP_MAX_STROKES MAX(WSP_MAX_FINGERS, FG_MAX_STROKES) #define FG_MAX_XSENSORS 26 #define FG_MAX_YSENSORS 16 /* device-specific configuration */ struct fg_dev_params { u_int data_len; /* for sensor data */ u_int n_xsensors; u_int n_ysensors; enum fountain_geyser_trackpad_type prot; }; struct wsp_dev_params { uint8_t caps; /* device capability bitmask */ uint8_t tp_type; /* type of trackpad interface */ uint8_t finger_data_offset; /* offset to trackpad finger data */ }; static const struct fg_dev_params fg_dev_params[FOUNTAIN_GEYSER_PRODUCT_MAX] = { [FOUNTAIN] = { .data_len = 81, .n_xsensors = 16, .n_ysensors = 16, .prot = FG_TRACKPAD_TYPE_GEYSER1 }, [GEYSER1] = { .data_len = 81, .n_xsensors = 16, .n_ysensors = 16, .prot = FG_TRACKPAD_TYPE_GEYSER1 }, [GEYSER1_17inch] = { .data_len = 81, .n_xsensors = 26, .n_ysensors = 16, .prot = FG_TRACKPAD_TYPE_GEYSER1 }, [GEYSER2] = { .data_len = 64, .n_xsensors = 15, .n_ysensors = 9, .prot = FG_TRACKPAD_TYPE_GEYSER2 }, [GEYSER3] = { .data_len = 64, .n_xsensors = 20, .n_ysensors = 10, .prot = FG_TRACKPAD_TYPE_GEYSER3 }, [GEYSER4] = { .data_len = 64, .n_xsensors = 20, .n_ysensors = 10, .prot = FG_TRACKPAD_TYPE_GEYSER4 } }; static const STRUCT_USB_HOST_ID fg_devs[] = { /* PowerBooks Feb 2005, iBooks G4 */ { USB_VPI(USB_VENDOR_APPLE, 0x020e, FG_DRIVER_INFO(FOUNTAIN)) }, { USB_VPI(USB_VENDOR_APPLE, 0x020f, FG_DRIVER_INFO(FOUNTAIN)) }, { USB_VPI(USB_VENDOR_APPLE, 0x0210, FG_DRIVER_INFO(FOUNTAIN)) }, { USB_VPI(USB_VENDOR_APPLE, 0x030a, FG_DRIVER_INFO(FOUNTAIN)) }, { USB_VPI(USB_VENDOR_APPLE, 0x030b, FG_DRIVER_INFO(GEYSER1)) }, /* PowerBooks Oct 2005 */ { USB_VPI(USB_VENDOR_APPLE, 0x0214, FG_DRIVER_INFO(GEYSER2)) }, { USB_VPI(USB_VENDOR_APPLE, 0x0215, FG_DRIVER_INFO(GEYSER2)) }, { USB_VPI(USB_VENDOR_APPLE, 0x0216, FG_DRIVER_INFO(GEYSER2)) }, /* Core Duo MacBook & MacBook Pro */ { USB_VPI(USB_VENDOR_APPLE, 0x0217, FG_DRIVER_INFO(GEYSER3)) }, { USB_VPI(USB_VENDOR_APPLE, 0x0218, FG_DRIVER_INFO(GEYSER3)) }, { USB_VPI(USB_VENDOR_APPLE, 0x0219, FG_DRIVER_INFO(GEYSER3)) }, /* Core2 Duo MacBook & MacBook Pro */ { USB_VPI(USB_VENDOR_APPLE, 0x021a, FG_DRIVER_INFO(GEYSER4)) }, { USB_VPI(USB_VENDOR_APPLE, 0x021b, FG_DRIVER_INFO(GEYSER4)) }, { USB_VPI(USB_VENDOR_APPLE, 0x021c, FG_DRIVER_INFO(GEYSER4)) }, /* Core2 Duo MacBook3,1 */ { USB_VPI(USB_VENDOR_APPLE, 0x0229, FG_DRIVER_INFO(GEYSER4)) }, { USB_VPI(USB_VENDOR_APPLE, 0x022a, FG_DRIVER_INFO(GEYSER4)) }, { USB_VPI(USB_VENDOR_APPLE, 0x022b, FG_DRIVER_INFO(GEYSER4)) }, /* 17 inch PowerBook */ { USB_VPI(USB_VENDOR_APPLE, 0x020d, FG_DRIVER_INFO(GEYSER1_17inch)) }, }; static const struct wsp_dev_params wsp_dev_params[WELLSPRING_PRODUCT_MAX] = { [WELLSPRING1] = { .caps = 0, .tp_type = WSP_TRACKPAD_TYPE1, .finger_data_offset = WSP_TYPE1_FINGER_DATA_OFFSET, }, [WELLSPRING2] = { .caps = 0, .tp_type = WSP_TRACKPAD_TYPE1, .finger_data_offset = WSP_TYPE1_FINGER_DATA_OFFSET, }, [WELLSPRING3] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = WSP_TRACKPAD_TYPE2, .finger_data_offset = WSP_TYPE2_FINGER_DATA_OFFSET, }, [WELLSPRING4] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = WSP_TRACKPAD_TYPE2, .finger_data_offset = WSP_TYPE2_FINGER_DATA_OFFSET, }, [WELLSPRING4A] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = WSP_TRACKPAD_TYPE2, .finger_data_offset = WSP_TYPE2_FINGER_DATA_OFFSET, }, [WELLSPRING5] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = WSP_TRACKPAD_TYPE2, .finger_data_offset = WSP_TYPE2_FINGER_DATA_OFFSET, }, [WELLSPRING6] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = WSP_TRACKPAD_TYPE2, .finger_data_offset = WSP_TYPE2_FINGER_DATA_OFFSET, }, [WELLSPRING5A] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = WSP_TRACKPAD_TYPE2, .finger_data_offset = WSP_TYPE2_FINGER_DATA_OFFSET, }, [WELLSPRING6A] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = WSP_TRACKPAD_TYPE2, .finger_data_offset = WSP_TYPE2_FINGER_DATA_OFFSET, }, [WELLSPRING7] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = WSP_TRACKPAD_TYPE2, .finger_data_offset = WSP_TYPE2_FINGER_DATA_OFFSET, }, [WELLSPRING7A] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = WSP_TRACKPAD_TYPE2, .finger_data_offset = WSP_TYPE2_FINGER_DATA_OFFSET, }, [WELLSPRING8] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = WSP_TRACKPAD_TYPE3, .finger_data_offset = WSP_TYPE3_FINGER_DATA_OFFSET, }, }; #define ATP_DEV(v,p,i) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, i) } /* TODO: STRUCT_USB_HOST_ID */ static const struct usb_device_id wsp_devs[] = { /* MacbookAir1.1 */ ATP_DEV(APPLE, WELLSPRING_ANSI, WELLSPRING_DRIVER_INFO(WELLSPRING1)), ATP_DEV(APPLE, WELLSPRING_ISO, WELLSPRING_DRIVER_INFO(WELLSPRING1)), ATP_DEV(APPLE, WELLSPRING_JIS, WELLSPRING_DRIVER_INFO(WELLSPRING1)), /* MacbookProPenryn, aka wellspring2 */ ATP_DEV(APPLE, WELLSPRING2_ANSI, WELLSPRING_DRIVER_INFO(WELLSPRING2)), ATP_DEV(APPLE, WELLSPRING2_ISO, WELLSPRING_DRIVER_INFO(WELLSPRING2)), ATP_DEV(APPLE, WELLSPRING2_JIS, WELLSPRING_DRIVER_INFO(WELLSPRING2)), /* Macbook5,1 (unibody), aka wellspring3 */ ATP_DEV(APPLE, WELLSPRING3_ANSI, WELLSPRING_DRIVER_INFO(WELLSPRING3)), ATP_DEV(APPLE, WELLSPRING3_ISO, WELLSPRING_DRIVER_INFO(WELLSPRING3)), ATP_DEV(APPLE, WELLSPRING3_JIS, WELLSPRING_DRIVER_INFO(WELLSPRING3)), /* MacbookAir3,2 (unibody), aka wellspring4 */ ATP_DEV(APPLE, WELLSPRING4_ANSI, WELLSPRING_DRIVER_INFO(WELLSPRING4)), ATP_DEV(APPLE, WELLSPRING4_ISO, WELLSPRING_DRIVER_INFO(WELLSPRING4)), ATP_DEV(APPLE, WELLSPRING4_JIS, WELLSPRING_DRIVER_INFO(WELLSPRING4)), /* MacbookAir3,1 (unibody), aka wellspring4 */ ATP_DEV(APPLE, WELLSPRING4A_ANSI, WELLSPRING_DRIVER_INFO(WELLSPRING4A)), ATP_DEV(APPLE, WELLSPRING4A_ISO, WELLSPRING_DRIVER_INFO(WELLSPRING4A)), ATP_DEV(APPLE, WELLSPRING4A_JIS, WELLSPRING_DRIVER_INFO(WELLSPRING4A)), /* Macbook8 (unibody, March 2011) */ ATP_DEV(APPLE, WELLSPRING5_ANSI, WELLSPRING_DRIVER_INFO(WELLSPRING5)), ATP_DEV(APPLE, WELLSPRING5_ISO, WELLSPRING_DRIVER_INFO(WELLSPRING5)), ATP_DEV(APPLE, WELLSPRING5_JIS, WELLSPRING_DRIVER_INFO(WELLSPRING5)), /* MacbookAir4,1 (unibody, July 2011) */ ATP_DEV(APPLE, WELLSPRING6A_ANSI, WELLSPRING_DRIVER_INFO(WELLSPRING6A)), ATP_DEV(APPLE, WELLSPRING6A_ISO, WELLSPRING_DRIVER_INFO(WELLSPRING6A)), ATP_DEV(APPLE, WELLSPRING6A_JIS, WELLSPRING_DRIVER_INFO(WELLSPRING6A)), /* MacbookAir4,2 (unibody, July 2011) */ ATP_DEV(APPLE, WELLSPRING6_ANSI, WELLSPRING_DRIVER_INFO(WELLSPRING6)), ATP_DEV(APPLE, WELLSPRING6_ISO, WELLSPRING_DRIVER_INFO(WELLSPRING6)), ATP_DEV(APPLE, WELLSPRING6_JIS, WELLSPRING_DRIVER_INFO(WELLSPRING6)), /* Macbook8,2 (unibody) */ ATP_DEV(APPLE, WELLSPRING5A_ANSI, WELLSPRING_DRIVER_INFO(WELLSPRING5A)), ATP_DEV(APPLE, WELLSPRING5A_ISO, WELLSPRING_DRIVER_INFO(WELLSPRING5A)), ATP_DEV(APPLE, WELLSPRING5A_JIS, WELLSPRING_DRIVER_INFO(WELLSPRING5A)), /* MacbookPro10,1 (unibody, June 2012) */ /* MacbookPro11,? (unibody, June 2013) */ ATP_DEV(APPLE, WELLSPRING7_ANSI, WELLSPRING_DRIVER_INFO(WELLSPRING7)), ATP_DEV(APPLE, WELLSPRING7_ISO, WELLSPRING_DRIVER_INFO(WELLSPRING7)), ATP_DEV(APPLE, WELLSPRING7_JIS, WELLSPRING_DRIVER_INFO(WELLSPRING7)), /* MacbookPro10,2 (unibody, October 2012) */ ATP_DEV(APPLE, WELLSPRING7A_ANSI, WELLSPRING_DRIVER_INFO(WELLSPRING7A)), ATP_DEV(APPLE, WELLSPRING7A_ISO, WELLSPRING_DRIVER_INFO(WELLSPRING7A)), ATP_DEV(APPLE, WELLSPRING7A_JIS, WELLSPRING_DRIVER_INFO(WELLSPRING7A)), /* MacbookAir6,2 (unibody, June 2013) */ ATP_DEV(APPLE, WELLSPRING8_ANSI, WELLSPRING_DRIVER_INFO(WELLSPRING8)), ATP_DEV(APPLE, WELLSPRING8_ISO, WELLSPRING_DRIVER_INFO(WELLSPRING8)), ATP_DEV(APPLE, WELLSPRING8_JIS, WELLSPRING_DRIVER_INFO(WELLSPRING8)), }; typedef enum atp_stroke_type { ATP_STROKE_TOUCH, ATP_STROKE_SLIDE, } atp_stroke_type; typedef enum atp_axis { X = 0, Y = 1, NUM_AXES } atp_axis; #define ATP_FIFO_BUF_SIZE 8 /* bytes */ #define ATP_FIFO_QUEUE_MAXLEN 50 /* units */ enum { ATP_INTR_DT, ATP_RESET, ATP_N_TRANSFER, }; typedef struct fg_stroke_component { /* Fields encapsulating the pressure-span. */ u_int loc; /* location (scaled) */ u_int cum_pressure; /* cumulative compression */ u_int max_cum_pressure; /* max cumulative compression */ boolean_t matched; /*to track components as they match against pspans.*/ int delta_mickeys; /* change in location (un-smoothened movement)*/ } fg_stroke_component_t; /* * The following structure captures a finger contact with the * touchpad. A stroke comprises two p-span components and some state. */ typedef struct atp_stroke { TAILQ_ENTRY(atp_stroke) entry; atp_stroke_type type; uint32_t flags; /* the state of this stroke */ #define ATSF_ZOMBIE 0x1 boolean_t matched; /* to track match against fingers.*/ struct timeval ctime; /* create time; for coincident siblings. */ /* * Unit: interrupts; we maintain this value in * addition to 'ctime' in order to avoid the * expensive call to microtime() at every * interrupt. */ uint32_t age; /* Location */ int x; int y; /* Fields containing information about movement. */ int instantaneous_dx; /* curr. change in X location (un-smoothened) */ int instantaneous_dy; /* curr. change in Y location (un-smoothened) */ int pending_dx; /* cum. of pending short movements */ int pending_dy; /* cum. of pending short movements */ int movement_dx; /* interpreted smoothened movement */ int movement_dy; /* interpreted smoothened movement */ int cum_movement_x; /* cum. horizontal movement */ int cum_movement_y; /* cum. vertical movement */ /* * The following member is relevant only for fountain-geyser trackpads. * For these, there is the need to track pressure-spans and cumulative * pressures for stroke components. */ fg_stroke_component_t components[NUM_AXES]; } atp_stroke_t; struct atp_softc; /* forward declaration */ typedef void (*sensor_data_interpreter_t)(struct atp_softc *sc, u_int len); struct atp_softc { device_t sc_dev; struct usb_device *sc_usb_device; struct mtx sc_mutex; /* for synchronization */ struct usb_fifo_sc sc_fifo; #define MODE_LENGTH 8 char sc_mode_bytes[MODE_LENGTH]; /* device mode */ trackpad_family_t sc_family; const void *sc_params; /* device configuration */ sensor_data_interpreter_t sensor_data_interpreter; mousehw_t sc_hw; mousemode_t sc_mode; mousestatus_t sc_status; u_int sc_state; #define ATP_ENABLED 0x01 #define ATP_ZOMBIES_EXIST 0x02 #define ATP_DOUBLE_TAP_DRAG 0x04 #define ATP_VALID 0x08 struct usb_xfer *sc_xfer[ATP_N_TRANSFER]; u_int sc_pollrate; int sc_fflags; atp_stroke_t sc_strokes_data[ATP_MAX_STROKES]; TAILQ_HEAD(,atp_stroke) sc_stroke_free; TAILQ_HEAD(,atp_stroke) sc_stroke_used; u_int sc_n_strokes; struct callout sc_callout; /* * button status. Set to non-zero if the mouse-button is physically * pressed. This state variable is exposed through softc to allow * reap_sibling_zombies to avoid registering taps while the trackpad * button is pressed. */ uint8_t sc_ibtn; /* * Time when touch zombies were last reaped; useful for detecting * double-touch-n-drag. */ struct timeval sc_touch_reap_time; u_int sc_idlecount; /* Regarding the data transferred from t-pad in USB INTR packets. */ u_int sc_expected_sensor_data_len; uint8_t sc_sensor_data[ATP_SENSOR_DATA_BUF_MAX] __aligned(4); int sc_cur_x[FG_MAX_XSENSORS]; /* current sensor readings */ int sc_cur_y[FG_MAX_YSENSORS]; int sc_base_x[FG_MAX_XSENSORS]; /* base sensor readings */ int sc_base_y[FG_MAX_YSENSORS]; int sc_pressure_x[FG_MAX_XSENSORS]; /* computed pressures */ int sc_pressure_y[FG_MAX_YSENSORS]; fg_pspan sc_pspans_x[FG_MAX_PSPANS_PER_AXIS]; fg_pspan sc_pspans_y[FG_MAX_PSPANS_PER_AXIS]; }; /* * The last byte of the fountain-geyser sensor data contains status bits; the * following values define the meanings of these bits. * (only Geyser 3/4) */ enum geyser34_status_bits { FG_STATUS_BUTTON = (uint8_t)0x01, /* The button was pressed */ FG_STATUS_BASE_UPDATE = (uint8_t)0x04, /* Data from an untouched pad.*/ }; typedef enum interface_mode { RAW_SENSOR_MODE = (uint8_t)0x01, HID_MODE = (uint8_t)0x08 } interface_mode; /* * function prototypes */ static usb_fifo_cmd_t atp_start_read; static usb_fifo_cmd_t atp_stop_read; static usb_fifo_open_t atp_open; static usb_fifo_close_t atp_close; static usb_fifo_ioctl_t atp_ioctl; static struct usb_fifo_methods atp_fifo_methods = { .f_open = &atp_open, .f_close = &atp_close, .f_ioctl = &atp_ioctl, .f_start_read = &atp_start_read, .f_stop_read = &atp_stop_read, .basename[0] = ATP_DRIVER_NAME, }; /* device initialization and shutdown */ static usb_error_t atp_set_device_mode(struct atp_softc *, interface_mode); static void atp_reset_callback(struct usb_xfer *, usb_error_t); static int atp_enable(struct atp_softc *); static void atp_disable(struct atp_softc *); /* sensor interpretation */ static void fg_interpret_sensor_data(struct atp_softc *, u_int); static void fg_extract_sensor_data(const int8_t *, u_int, atp_axis, int *, enum fountain_geyser_trackpad_type); static void fg_get_pressures(int *, const int *, const int *, int); static void fg_detect_pspans(int *, u_int, u_int, fg_pspan *, u_int *); static void wsp_interpret_sensor_data(struct atp_softc *, u_int); /* movement detection */ static boolean_t fg_match_stroke_component(fg_stroke_component_t *, const fg_pspan *, atp_stroke_type); static void fg_match_strokes_against_pspans(struct atp_softc *, atp_axis, fg_pspan *, u_int, u_int); static boolean_t wsp_match_strokes_against_fingers(struct atp_softc *, wsp_finger_t *, u_int); static boolean_t fg_update_strokes(struct atp_softc *, fg_pspan *, u_int, fg_pspan *, u_int); static boolean_t wsp_update_strokes(struct atp_softc *, wsp_finger_t [WSP_MAX_FINGERS], u_int); static void fg_add_stroke(struct atp_softc *, const fg_pspan *, const fg_pspan *); static void fg_add_new_strokes(struct atp_softc *, fg_pspan *, u_int, fg_pspan *, u_int); static void wsp_add_stroke(struct atp_softc *, const wsp_finger_t *); static void atp_advance_stroke_state(struct atp_softc *, atp_stroke_t *, boolean_t *); static boolean_t atp_stroke_has_small_movement(const atp_stroke_t *); static void atp_update_pending_mickeys(atp_stroke_t *); static boolean_t atp_compute_stroke_movement(atp_stroke_t *); static void atp_terminate_stroke(struct atp_softc *, atp_stroke_t *); /* tap detection */ static boolean_t atp_is_horizontal_scroll(const atp_stroke_t *); static boolean_t atp_is_vertical_scroll(const atp_stroke_t *); static void atp_reap_sibling_zombies(void *); static void atp_convert_to_slide(struct atp_softc *, atp_stroke_t *); /* updating fifo */ static void atp_reset_buf(struct atp_softc *); static void atp_add_to_queue(struct atp_softc *, int, int, int, uint32_t); /* Device methods. */ static device_probe_t atp_probe; static device_attach_t atp_attach; static device_detach_t atp_detach; static usb_callback_t atp_intr; static const struct usb_config atp_xfer_config[ATP_N_TRANSFER] = { [ATP_INTR_DT] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = { .pipe_bof = 1, /* block pipe on failure */ .short_xfer_ok = 1, }, .bufsize = ATP_SENSOR_DATA_BUF_MAX, .callback = &atp_intr, }, [ATP_RESET] = { .type = UE_CONTROL, .endpoint = 0, /* Control pipe */ .direction = UE_DIR_ANY, .bufsize = sizeof(struct usb_device_request) + MODE_LENGTH, .callback = &atp_reset_callback, .interval = 0, /* no pre-delay */ }, }; static atp_stroke_t * atp_alloc_stroke(struct atp_softc *sc) { atp_stroke_t *pstroke; pstroke = TAILQ_FIRST(&sc->sc_stroke_free); if (pstroke == NULL) goto done; TAILQ_REMOVE(&sc->sc_stroke_free, pstroke, entry); memset(pstroke, 0, sizeof(*pstroke)); TAILQ_INSERT_TAIL(&sc->sc_stroke_used, pstroke, entry); sc->sc_n_strokes++; done: return (pstroke); } static void atp_free_stroke(struct atp_softc *sc, atp_stroke_t *pstroke) { if (pstroke == NULL) return; sc->sc_n_strokes--; TAILQ_REMOVE(&sc->sc_stroke_used, pstroke, entry); TAILQ_INSERT_TAIL(&sc->sc_stroke_free, pstroke, entry); } static void atp_init_stroke_pool(struct atp_softc *sc) { u_int x; TAILQ_INIT(&sc->sc_stroke_free); TAILQ_INIT(&sc->sc_stroke_used); sc->sc_n_strokes = 0; memset(&sc->sc_strokes_data, 0, sizeof(sc->sc_strokes_data)); for (x = 0; x != ATP_MAX_STROKES; x++) { TAILQ_INSERT_TAIL(&sc->sc_stroke_free, &sc->sc_strokes_data[x], entry); } } static usb_error_t atp_set_device_mode(struct atp_softc *sc, interface_mode newMode) { uint8_t mode_value; usb_error_t err; if ((newMode != RAW_SENSOR_MODE) && (newMode != HID_MODE)) return (USB_ERR_INVAL); if ((newMode == RAW_SENSOR_MODE) && (sc->sc_family == TRACKPAD_FAMILY_FOUNTAIN_GEYSER)) mode_value = (uint8_t)0x04; else mode_value = newMode; err = usbd_req_get_report(sc->sc_usb_device, NULL /* mutex */, sc->sc_mode_bytes, sizeof(sc->sc_mode_bytes), 0 /* interface idx */, 0x03 /* type */, 0x00 /* id */); if (err != USB_ERR_NORMAL_COMPLETION) { DPRINTF("Failed to read device mode (%d)\n", err); return (err); } if (sc->sc_mode_bytes[0] == mode_value) return (err); /* * XXX Need to wait at least 250ms for hardware to get * ready. The device mode handling appears to be handled * asynchronously and we should not issue these commands too * quickly. */ pause("WHW", hz / 4); sc->sc_mode_bytes[0] = mode_value; return (usbd_req_set_report(sc->sc_usb_device, NULL /* mutex */, sc->sc_mode_bytes, sizeof(sc->sc_mode_bytes), 0 /* interface idx */, 0x03 /* type */, 0x00 /* id */)); } static void atp_reset_callback(struct usb_xfer *xfer, usb_error_t error) { usb_device_request_t req; struct usb_page_cache *pc; struct atp_softc *sc = usbd_xfer_softc(xfer); uint8_t mode_value; if (sc->sc_family == TRACKPAD_FAMILY_FOUNTAIN_GEYSER) mode_value = 0x04; else mode_value = RAW_SENSOR_MODE; switch (USB_GET_STATE(xfer)) { case USB_ST_SETUP: sc->sc_mode_bytes[0] = mode_value; req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UR_SET_REPORT; USETW2(req.wValue, (uint8_t)0x03 /* type */, (uint8_t)0x00 /* id */); USETW(req.wIndex, 0); USETW(req.wLength, MODE_LENGTH); pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, &req, sizeof(req)); pc = usbd_xfer_get_frame(xfer, 1); usbd_copy_in(pc, 0, sc->sc_mode_bytes, MODE_LENGTH); usbd_xfer_set_frame_len(xfer, 0, sizeof(req)); usbd_xfer_set_frame_len(xfer, 1, MODE_LENGTH); usbd_xfer_set_frames(xfer, 2); usbd_transfer_submit(xfer); break; case USB_ST_TRANSFERRED: default: break; } } static int atp_enable(struct atp_softc *sc) { if (sc->sc_state & ATP_ENABLED) return (0); /* reset status */ memset(&sc->sc_status, 0, sizeof(sc->sc_status)); atp_init_stroke_pool(sc); sc->sc_state |= ATP_ENABLED; DPRINTFN(ATP_LLEVEL_INFO, "enabled atp\n"); return (0); } static void atp_disable(struct atp_softc *sc) { sc->sc_state &= ~(ATP_ENABLED | ATP_VALID); DPRINTFN(ATP_LLEVEL_INFO, "disabled atp\n"); } static void fg_interpret_sensor_data(struct atp_softc *sc, u_int data_len) { u_int n_xpspans = 0; u_int n_ypspans = 0; uint8_t status_bits; const struct fg_dev_params *params = (const struct fg_dev_params *)sc->sc_params; fg_extract_sensor_data(sc->sc_sensor_data, params->n_xsensors, X, sc->sc_cur_x, params->prot); fg_extract_sensor_data(sc->sc_sensor_data, params->n_ysensors, Y, sc->sc_cur_y, params->prot); /* * If this is the initial update (from an untouched * pad), we should set the base values for the sensor * data; deltas with respect to these base values can * be used as pressure readings subsequently. */ status_bits = sc->sc_sensor_data[params->data_len - 1]; if (((params->prot == FG_TRACKPAD_TYPE_GEYSER3) || (params->prot == FG_TRACKPAD_TYPE_GEYSER4)) && ((sc->sc_state & ATP_VALID) == 0)) { if (status_bits & FG_STATUS_BASE_UPDATE) { memcpy(sc->sc_base_x, sc->sc_cur_x, params->n_xsensors * sizeof(*sc->sc_base_x)); memcpy(sc->sc_base_y, sc->sc_cur_y, params->n_ysensors * sizeof(*sc->sc_base_y)); sc->sc_state |= ATP_VALID; return; } } /* Get pressure readings and detect p-spans for both axes. */ fg_get_pressures(sc->sc_pressure_x, sc->sc_cur_x, sc->sc_base_x, params->n_xsensors); fg_detect_pspans(sc->sc_pressure_x, params->n_xsensors, FG_MAX_PSPANS_PER_AXIS, sc->sc_pspans_x, &n_xpspans); fg_get_pressures(sc->sc_pressure_y, sc->sc_cur_y, sc->sc_base_y, params->n_ysensors); fg_detect_pspans(sc->sc_pressure_y, params->n_ysensors, FG_MAX_PSPANS_PER_AXIS, sc->sc_pspans_y, &n_ypspans); /* Update strokes with new pspans to detect movements. */ if (fg_update_strokes(sc, sc->sc_pspans_x, n_xpspans, sc->sc_pspans_y, n_ypspans)) sc->sc_status.flags |= MOUSE_POSCHANGED; sc->sc_ibtn = (status_bits & FG_STATUS_BUTTON) ? MOUSE_BUTTON1DOWN : 0; sc->sc_status.button = sc->sc_ibtn; /* * The Fountain/Geyser device continues to trigger interrupts * at a fast rate even after touchpad activity has * stopped. Upon detecting that the device has remained idle * beyond a threshold, we reinitialize it to silence the * interrupts. */ if ((sc->sc_status.flags == 0) && (sc->sc_n_strokes == 0)) { sc->sc_idlecount++; if (sc->sc_idlecount >= ATP_IDLENESS_THRESHOLD) { /* * Use the last frame before we go idle for * calibration on pads which do not send * calibration frames. */ const struct fg_dev_params *params = (const struct fg_dev_params *)sc->sc_params; DPRINTFN(ATP_LLEVEL_INFO, "idle\n"); if (params->prot < FG_TRACKPAD_TYPE_GEYSER3) { memcpy(sc->sc_base_x, sc->sc_cur_x, params->n_xsensors * sizeof(*(sc->sc_base_x))); memcpy(sc->sc_base_y, sc->sc_cur_y, params->n_ysensors * sizeof(*(sc->sc_base_y))); } sc->sc_idlecount = 0; usbd_transfer_start(sc->sc_xfer[ATP_RESET]); } } else { sc->sc_idlecount = 0; } } /* * Interpret the data from the X and Y pressure sensors. This function * is called separately for the X and Y sensor arrays. The data in the * USB packet is laid out in the following manner: * * sensor_data: * --,--,Y1,Y2,--,Y3,Y4,--,Y5,...,Y10, ... X1,X2,--,X3,X4 * indices: 0 1 2 3 4 5 6 7 8 ... 15 ... 20 21 22 23 24 * * '--' (in the above) indicates that the value is unimportant. * * Information about the above layout was obtained from the * implementation of the AppleTouch driver in Linux. * * parameters: * sensor_data * raw sensor data from the USB packet. * num * The number of elements in the array 'arr'. * axis * Axis of data to fetch * arr * The array to be initialized with the readings. * prot * The protocol to use to interpret the data */ static void fg_extract_sensor_data(const int8_t *sensor_data, u_int num, atp_axis axis, int *arr, enum fountain_geyser_trackpad_type prot) { u_int i; u_int di; /* index into sensor data */ switch (prot) { case FG_TRACKPAD_TYPE_GEYSER1: /* * For Geyser 1, the sensors are laid out in pairs * every 5 bytes. */ for (i = 0, di = (axis == Y) ? 1 : 2; i < 8; di += 5, i++) { arr[i] = sensor_data[di]; arr[i+8] = sensor_data[di+2]; if ((axis == X) && (num > 16)) arr[i+16] = sensor_data[di+40]; } break; case FG_TRACKPAD_TYPE_GEYSER2: for (i = 0, di = (axis == Y) ? 1 : 19; i < num; /* empty */ ) { arr[i++] = sensor_data[di++]; arr[i++] = sensor_data[di++]; di++; } break; case FG_TRACKPAD_TYPE_GEYSER3: case FG_TRACKPAD_TYPE_GEYSER4: for (i = 0, di = (axis == Y) ? 2 : 20; i < num; /* empty */ ) { arr[i++] = sensor_data[di++]; arr[i++] = sensor_data[di++]; di++; } break; default: break; } } static void fg_get_pressures(int *p, const int *cur, const int *base, int n) { int i; for (i = 0; i < n; i++) { p[i] = cur[i] - base[i]; if (p[i] > 127) p[i] -= 256; if (p[i] < -127) p[i] += 256; if (p[i] < 0) p[i] = 0; /* * Shave off pressures below the noise-pressure * threshold; this will reduce the contribution from * lower pressure readings. */ if ((u_int)p[i] <= FG_SENSOR_NOISE_THRESHOLD) p[i] = 0; /* filter away noise */ else p[i] -= FG_SENSOR_NOISE_THRESHOLD; } } static void fg_detect_pspans(int *p, u_int num_sensors, u_int max_spans, /* max # of pspans permitted */ fg_pspan *spans, /* finger spans */ u_int *nspans_p) /* num spans detected */ { u_int i; int maxp; /* max pressure seen within a span */ u_int num_spans = 0; enum fg_pspan_state { ATP_PSPAN_INACTIVE, ATP_PSPAN_INCREASING, ATP_PSPAN_DECREASING, } state; /* state of the pressure span */ /* * The following is a simple state machine to track * the phase of the pressure span. */ memset(spans, 0, max_spans * sizeof(fg_pspan)); maxp = 0; state = ATP_PSPAN_INACTIVE; for (i = 0; i < num_sensors; i++) { if (num_spans >= max_spans) break; if (p[i] == 0) { if (state == ATP_PSPAN_INACTIVE) { /* * There is no pressure information for this * sensor, and we aren't tracking a finger. */ continue; } else { state = ATP_PSPAN_INACTIVE; maxp = 0; num_spans++; } } else { switch (state) { case ATP_PSPAN_INACTIVE: state = ATP_PSPAN_INCREASING; maxp = p[i]; break; case ATP_PSPAN_INCREASING: if (p[i] > maxp) maxp = p[i]; else if (p[i] <= (maxp >> 1)) state = ATP_PSPAN_DECREASING; break; case ATP_PSPAN_DECREASING: if (p[i] > p[i - 1]) { /* * This is the beginning of * another span; change state * to give the appearance that * we're starting from an * inactive span, and then * re-process this reading in * the next iteration. */ num_spans++; state = ATP_PSPAN_INACTIVE; maxp = 0; i--; continue; } break; } /* Update the finger span with this reading. */ spans[num_spans].width++; spans[num_spans].cum += p[i]; spans[num_spans].cog += p[i] * (i + 1); } } if (state != ATP_PSPAN_INACTIVE) num_spans++; /* close the last finger span */ /* post-process the spans */ for (i = 0; i < num_spans; i++) { /* filter away unwanted pressure spans */ if ((spans[i].cum < FG_PSPAN_MIN_CUM_PRESSURE) || (spans[i].width > FG_PSPAN_MAX_WIDTH)) { if ((i + 1) < num_spans) { memcpy(&spans[i], &spans[i + 1], (num_spans - i - 1) * sizeof(fg_pspan)); i--; } num_spans--; continue; } /* compute this span's representative location */ spans[i].loc = spans[i].cog * FG_SCALE_FACTOR / spans[i].cum; spans[i].matched = false; /* not yet matched against a stroke */ } *nspans_p = num_spans; } static void wsp_interpret_sensor_data(struct atp_softc *sc, u_int data_len) { const struct wsp_dev_params *params = sc->sc_params; wsp_finger_t fingers[WSP_MAX_FINGERS]; struct wsp_finger_sensor_data *source_fingerp; u_int n_source_fingers; u_int n_fingers; u_int i; /* validate sensor data length */ if ((data_len < params->finger_data_offset) || ((data_len - params->finger_data_offset) % WSP_SIZEOF_FINGER_SENSOR_DATA) != 0) return; /* compute number of source fingers */ n_source_fingers = (data_len - params->finger_data_offset) / WSP_SIZEOF_FINGER_SENSOR_DATA; if (n_source_fingers > WSP_MAX_FINGERS) n_source_fingers = WSP_MAX_FINGERS; /* iterate over the source data collecting useful fingers */ n_fingers = 0; source_fingerp = (struct wsp_finger_sensor_data *)(sc->sc_sensor_data + params->finger_data_offset); for (i = 0; i < n_source_fingers; i++, source_fingerp++) { /* swap endianness, if any */ if (le16toh(0x1234) != 0x1234) { source_fingerp->origin = le16toh((uint16_t)source_fingerp->origin); source_fingerp->abs_x = le16toh((uint16_t)source_fingerp->abs_x); source_fingerp->abs_y = le16toh((uint16_t)source_fingerp->abs_y); source_fingerp->rel_x = le16toh((uint16_t)source_fingerp->rel_x); source_fingerp->rel_y = le16toh((uint16_t)source_fingerp->rel_y); source_fingerp->tool_major = le16toh((uint16_t)source_fingerp->tool_major); source_fingerp->tool_minor = le16toh((uint16_t)source_fingerp->tool_minor); source_fingerp->orientation = le16toh((uint16_t)source_fingerp->orientation); source_fingerp->touch_major = le16toh((uint16_t)source_fingerp->touch_major); source_fingerp->touch_minor = le16toh((uint16_t)source_fingerp->touch_minor); source_fingerp->multi = le16toh((uint16_t)source_fingerp->multi); } /* check for minium threshold */ if (source_fingerp->touch_major == 0) continue; fingers[n_fingers].matched = false; fingers[n_fingers].x = source_fingerp->abs_x; fingers[n_fingers].y = -source_fingerp->abs_y; n_fingers++; } if ((sc->sc_n_strokes == 0) && (n_fingers == 0)) return; if (wsp_update_strokes(sc, fingers, n_fingers)) sc->sc_status.flags |= MOUSE_POSCHANGED; switch(params->tp_type) { case WSP_TRACKPAD_TYPE2: sc->sc_ibtn = sc->sc_sensor_data[WSP_TYPE2_BUTTON_DATA_OFFSET]; break; case WSP_TRACKPAD_TYPE3: sc->sc_ibtn = sc->sc_sensor_data[WSP_TYPE3_BUTTON_DATA_OFFSET]; break; default: break; } sc->sc_status.button = sc->sc_ibtn ? MOUSE_BUTTON1DOWN : 0; } /* * Match a pressure-span against a stroke-component. If there is a * match, update the component's state and return true. */ static boolean_t fg_match_stroke_component(fg_stroke_component_t *component, const fg_pspan *pspan, atp_stroke_type stroke_type) { int delta_mickeys; u_int min_pressure; delta_mickeys = pspan->loc - component->loc; if (abs(delta_mickeys) > (int)FG_MAX_DELTA_MICKEYS) return (false); /* the finger span is too far out; no match */ component->loc = pspan->loc; /* * A sudden and significant increase in a pspan's cumulative * pressure indicates the incidence of a new finger * contact. This usually revises the pspan's * centre-of-gravity, and hence the location of any/all * matching stroke component(s). But such a change should * *not* be interpreted as a movement. */ if (pspan->cum > ((3 * component->cum_pressure) >> 1)) delta_mickeys = 0; component->cum_pressure = pspan->cum; if (pspan->cum > component->max_cum_pressure) component->max_cum_pressure = pspan->cum; /* * Disregard the component's movement if its cumulative * pressure drops below a fraction of the maximum; this * fraction is determined based on the stroke's type. */ if (stroke_type == ATP_STROKE_TOUCH) min_pressure = (3 * component->max_cum_pressure) >> 2; else min_pressure = component->max_cum_pressure >> 2; if (component->cum_pressure < min_pressure) delta_mickeys = 0; component->delta_mickeys = delta_mickeys; return (true); } static void fg_match_strokes_against_pspans(struct atp_softc *sc, atp_axis axis, fg_pspan *pspans, u_int n_pspans, u_int repeat_count) { atp_stroke_t *strokep; u_int repeat_index = 0; u_int i; /* Determine the index of the multi-span. */ if (repeat_count) { for (i = 0; i < n_pspans; i++) { if (pspans[i].cum > pspans[repeat_index].cum) repeat_index = i; } } TAILQ_FOREACH(strokep, &sc->sc_stroke_used, entry) { if (strokep->components[axis].matched) continue; /* skip matched components */ for (i = 0; i < n_pspans; i++) { if (pspans[i].matched) continue; /* skip matched pspans */ if (fg_match_stroke_component( &strokep->components[axis], &pspans[i], strokep->type)) { /* There is a match. */ strokep->components[axis].matched = true; /* Take care to repeat at the multi-span. */ if ((repeat_count > 0) && (i == repeat_index)) repeat_count--; else pspans[i].matched = true; break; /* skip to the next strokep */ } } /* loop over pspans */ } /* loop over strokes */ } static boolean_t wsp_match_strokes_against_fingers(struct atp_softc *sc, wsp_finger_t *fingers, u_int n_fingers) { boolean_t movement = false; atp_stroke_t *strokep; u_int i; /* reset the matched status for all strokes */ TAILQ_FOREACH(strokep, &sc->sc_stroke_used, entry) strokep->matched = false; for (i = 0; i != n_fingers; i++) { u_int least_distance_sq = WSP_MAX_ALLOWED_MATCH_DISTANCE_SQ; atp_stroke_t *strokep_best = NULL; TAILQ_FOREACH(strokep, &sc->sc_stroke_used, entry) { int instantaneous_dx; int instantaneous_dy; u_int d_squared; if (strokep->matched) continue; instantaneous_dx = fingers[i].x - strokep->x; instantaneous_dy = fingers[i].y - strokep->y; /* skip strokes which are far away */ d_squared = (instantaneous_dx * instantaneous_dx) + (instantaneous_dy * instantaneous_dy); if (d_squared < least_distance_sq) { least_distance_sq = d_squared; strokep_best = strokep; } } strokep = strokep_best; if (strokep != NULL) { fingers[i].matched = true; strokep->matched = true; strokep->instantaneous_dx = fingers[i].x - strokep->x; strokep->instantaneous_dy = fingers[i].y - strokep->y; strokep->x = fingers[i].x; strokep->y = fingers[i].y; atp_advance_stroke_state(sc, strokep, &movement); } } return (movement); } /* * Update strokes by matching against current pressure-spans. * Return true if any movement is detected. */ static boolean_t fg_update_strokes(struct atp_softc *sc, fg_pspan *pspans_x, u_int n_xpspans, fg_pspan *pspans_y, u_int n_ypspans) { atp_stroke_t *strokep; atp_stroke_t *strokep_next; boolean_t movement = false; u_int repeat_count = 0; u_int i; u_int j; /* Reset X and Y components of all strokes as unmatched. */ TAILQ_FOREACH(strokep, &sc->sc_stroke_used, entry) { strokep->components[X].matched = false; strokep->components[Y].matched = false; } /* * Usually, the X and Y pspans come in pairs (the common case * being a single pair). It is possible, however, that * multiple contacts resolve to a single pspan along an * axis, as illustrated in the following: * * F = finger-contact * * pspan pspan * +-----------------------+ * | . . | * | . . | * | . . | * | . . | * pspan |.........F......F | * | | * | | * | | * +-----------------------+ * * * The above case can be detected by a difference in the * number of X and Y pspans. When this happens, X and Y pspans * aren't easy to pair or match against strokes. * * When X and Y pspans differ in number, the axis with the * smaller number of pspans is regarded as having a repeating * pspan (or a multi-pspan)--in the above illustration, the * Y-axis has a repeating pspan. Our approach is to try to * match the multi-pspan repeatedly against strokes. The * difference between the number of X and Y pspans gives us a * crude repeat_count for matching multi-pspans--i.e. the * multi-pspan along the Y axis (above) has a repeat_count of 1. */ repeat_count = abs(n_xpspans - n_ypspans); fg_match_strokes_against_pspans(sc, X, pspans_x, n_xpspans, (((repeat_count != 0) && ((n_xpspans < n_ypspans))) ? repeat_count : 0)); fg_match_strokes_against_pspans(sc, Y, pspans_y, n_ypspans, (((repeat_count != 0) && (n_ypspans < n_xpspans)) ? repeat_count : 0)); /* Update the state of strokes based on the above pspan matches. */ TAILQ_FOREACH_SAFE(strokep, &sc->sc_stroke_used, entry, strokep_next) { if (strokep->components[X].matched && strokep->components[Y].matched) { strokep->matched = true; strokep->instantaneous_dx = strokep->components[X].delta_mickeys; strokep->instantaneous_dy = strokep->components[Y].delta_mickeys; atp_advance_stroke_state(sc, strokep, &movement); } else { /* * At least one component of this stroke * didn't match against current pspans; * terminate it. */ atp_terminate_stroke(sc, strokep); } } /* Add new strokes for pairs of unmatched pspans */ for (i = 0; i < n_xpspans; i++) { if (pspans_x[i].matched == false) break; } for (j = 0; j < n_ypspans; j++) { if (pspans_y[j].matched == false) break; } if ((i < n_xpspans) && (j < n_ypspans)) { #ifdef USB_DEBUG if (atp_debug >= ATP_LLEVEL_INFO) { printf("unmatched pspans:"); for (; i < n_xpspans; i++) { if (pspans_x[i].matched) continue; printf(" X:[loc:%u,cum:%u]", pspans_x[i].loc, pspans_x[i].cum); } for (; j < n_ypspans; j++) { if (pspans_y[j].matched) continue; printf(" Y:[loc:%u,cum:%u]", pspans_y[j].loc, pspans_y[j].cum); } printf("\n"); } #endif /* USB_DEBUG */ if ((n_xpspans == 1) && (n_ypspans == 1)) /* The common case of a single pair of new pspans. */ fg_add_stroke(sc, &pspans_x[0], &pspans_y[0]); else fg_add_new_strokes(sc, pspans_x, n_xpspans, pspans_y, n_ypspans); } #ifdef USB_DEBUG if (atp_debug >= ATP_LLEVEL_INFO) { TAILQ_FOREACH(strokep, &sc->sc_stroke_used, entry) { printf(" %s%clc:%u,dm:%d,cum:%d,max:%d,%c" ",%clc:%u,dm:%d,cum:%d,max:%d,%c", (strokep->flags & ATSF_ZOMBIE) ? "zomb:" : "", (strokep->type == ATP_STROKE_TOUCH) ? '[' : '<', strokep->components[X].loc, strokep->components[X].delta_mickeys, strokep->components[X].cum_pressure, strokep->components[X].max_cum_pressure, (strokep->type == ATP_STROKE_TOUCH) ? ']' : '>', (strokep->type == ATP_STROKE_TOUCH) ? '[' : '<', strokep->components[Y].loc, strokep->components[Y].delta_mickeys, strokep->components[Y].cum_pressure, strokep->components[Y].max_cum_pressure, (strokep->type == ATP_STROKE_TOUCH) ? ']' : '>'); } if (TAILQ_FIRST(&sc->sc_stroke_used) != NULL) printf("\n"); } #endif /* USB_DEBUG */ return (movement); } /* * Update strokes by matching against current pressure-spans. * Return true if any movement is detected. */ static boolean_t wsp_update_strokes(struct atp_softc *sc, wsp_finger_t *fingers, u_int n_fingers) { boolean_t movement = false; atp_stroke_t *strokep_next; atp_stroke_t *strokep; u_int i; if (sc->sc_n_strokes > 0) { movement = wsp_match_strokes_against_fingers( sc, fingers, n_fingers); /* handle zombie strokes */ TAILQ_FOREACH_SAFE(strokep, &sc->sc_stroke_used, entry, strokep_next) { if (strokep->matched) continue; atp_terminate_stroke(sc, strokep); } } /* initialize unmatched fingers as strokes */ for (i = 0; i != n_fingers; i++) { if (fingers[i].matched) continue; wsp_add_stroke(sc, fingers + i); } return (movement); } /* Initialize a stroke using a pressure-span. */ static void fg_add_stroke(struct atp_softc *sc, const fg_pspan *pspan_x, const fg_pspan *pspan_y) { atp_stroke_t *strokep; strokep = atp_alloc_stroke(sc); if (strokep == NULL) return; /* * Strokes begin as potential touches. If a stroke survives * longer than a threshold, or if it records significant * cumulative movement, then it is considered a 'slide'. */ strokep->type = ATP_STROKE_TOUCH; strokep->matched = false; microtime(&strokep->ctime); strokep->age = 1; /* number of interrupts */ strokep->x = pspan_x->loc; strokep->y = pspan_y->loc; strokep->components[X].loc = pspan_x->loc; strokep->components[X].cum_pressure = pspan_x->cum; strokep->components[X].max_cum_pressure = pspan_x->cum; strokep->components[X].matched = true; strokep->components[Y].loc = pspan_y->loc; strokep->components[Y].cum_pressure = pspan_y->cum; strokep->components[Y].max_cum_pressure = pspan_y->cum; strokep->components[Y].matched = true; if (sc->sc_n_strokes > 1) { /* Reset double-tap-n-drag if we have more than one strokes. */ sc->sc_state &= ~ATP_DOUBLE_TAP_DRAG; } DPRINTFN(ATP_LLEVEL_INFO, "[%u,%u], time: %u,%ld\n", strokep->components[X].loc, strokep->components[Y].loc, (u_int)strokep->ctime.tv_sec, (unsigned long int)strokep->ctime.tv_usec); } static void fg_add_new_strokes(struct atp_softc *sc, fg_pspan *pspans_x, u_int n_xpspans, fg_pspan *pspans_y, u_int n_ypspans) { fg_pspan spans[2][FG_MAX_PSPANS_PER_AXIS]; u_int nspans[2]; u_int i; u_int j; /* Copy unmatched pspans into the local arrays. */ for (i = 0, nspans[X] = 0; i < n_xpspans; i++) { if (pspans_x[i].matched == false) { spans[X][nspans[X]] = pspans_x[i]; nspans[X]++; } } for (j = 0, nspans[Y] = 0; j < n_ypspans; j++) { if (pspans_y[j].matched == false) { spans[Y][nspans[Y]] = pspans_y[j]; nspans[Y]++; } } if (nspans[X] == nspans[Y]) { /* Create new strokes from pairs of unmatched pspans */ for (i = 0, j = 0; (i < nspans[X]) && (j < nspans[Y]); i++, j++) fg_add_stroke(sc, &spans[X][i], &spans[Y][j]); } else { u_int cum = 0; atp_axis repeat_axis; /* axis with multi-pspans */ u_int repeat_count; /* repeat count for the multi-pspan*/ u_int repeat_index = 0; /* index of the multi-span */ repeat_axis = (nspans[X] > nspans[Y]) ? Y : X; repeat_count = abs(nspans[X] - nspans[Y]); for (i = 0; i < nspans[repeat_axis]; i++) { if (spans[repeat_axis][i].cum > cum) { repeat_index = i; cum = spans[repeat_axis][i].cum; } } /* Create new strokes from pairs of unmatched pspans */ i = 0, j = 0; for (; (i < nspans[X]) && (j < nspans[Y]); i++, j++) { fg_add_stroke(sc, &spans[X][i], &spans[Y][j]); /* Take care to repeat at the multi-pspan. */ if (repeat_count > 0) { if ((repeat_axis == X) && (repeat_index == i)) { i--; /* counter loop increment */ repeat_count--; } else if ((repeat_axis == Y) && (repeat_index == j)) { j--; /* counter loop increment */ repeat_count--; } } } } } /* Initialize a stroke from an unmatched finger. */ static void wsp_add_stroke(struct atp_softc *sc, const wsp_finger_t *fingerp) { atp_stroke_t *strokep; strokep = atp_alloc_stroke(sc); if (strokep == NULL) return; /* * Strokes begin as potential touches. If a stroke survives * longer than a threshold, or if it records significant * cumulative movement, then it is considered a 'slide'. */ strokep->type = ATP_STROKE_TOUCH; strokep->matched = true; microtime(&strokep->ctime); strokep->age = 1; /* number of interrupts */ strokep->x = fingerp->x; strokep->y = fingerp->y; /* Reset double-tap-n-drag if we have more than one strokes. */ if (sc->sc_n_strokes > 1) sc->sc_state &= ~ATP_DOUBLE_TAP_DRAG; DPRINTFN(ATP_LLEVEL_INFO, "[%d,%d]\n", strokep->x, strokep->y); } static void atp_advance_stroke_state(struct atp_softc *sc, atp_stroke_t *strokep, boolean_t *movementp) { /* Revitalize stroke if it had previously been marked as a zombie. */ if (strokep->flags & ATSF_ZOMBIE) strokep->flags &= ~ATSF_ZOMBIE; strokep->age++; if (strokep->age <= atp_stroke_maturity_threshold) { /* Avoid noise from immature strokes. */ strokep->instantaneous_dx = 0; strokep->instantaneous_dy = 0; } if (atp_compute_stroke_movement(strokep)) *movementp = true; if (strokep->type != ATP_STROKE_TOUCH) return; /* Convert touch strokes to slides upon detecting movement or age. */ if ((abs(strokep->cum_movement_x) > atp_slide_min_movement) || (abs(strokep->cum_movement_y) > atp_slide_min_movement)) atp_convert_to_slide(sc, strokep); else { /* Compute the stroke's age. */ struct timeval tdiff; getmicrotime(&tdiff); if (timevalcmp(&tdiff, &strokep->ctime, >)) { timevalsub(&tdiff, &strokep->ctime); if ((tdiff.tv_sec > (atp_touch_timeout / 1000000)) || ((tdiff.tv_sec == (atp_touch_timeout / 1000000)) && (tdiff.tv_usec >= (atp_touch_timeout % 1000000)))) atp_convert_to_slide(sc, strokep); } } } static boolean_t atp_stroke_has_small_movement(const atp_stroke_t *strokep) { return (((u_int)abs(strokep->instantaneous_dx) <= atp_small_movement_threshold) && ((u_int)abs(strokep->instantaneous_dy) <= atp_small_movement_threshold)); } /* * Accumulate instantaneous changes into the stroke's 'pending' bucket; if * the aggregate exceeds the small_movement_threshold, then retain * instantaneous changes for later. */ static void atp_update_pending_mickeys(atp_stroke_t *strokep) { /* accumulate instantaneous movement */ strokep->pending_dx += strokep->instantaneous_dx; strokep->pending_dy += strokep->instantaneous_dy; #define UPDATE_INSTANTANEOUS_AND_PENDING(I, P) \ if (abs((P)) <= atp_small_movement_threshold) \ (I) = 0; /* clobber small movement */ \ else { \ if ((I) > 0) { \ /* \ * Round up instantaneous movement to the nearest \ * ceiling. This helps preserve small mickey \ * movements from being lost in following scaling \ * operation. \ */ \ (I) = (((I) + (atp_mickeys_scale_factor - 1)) / \ atp_mickeys_scale_factor) * \ atp_mickeys_scale_factor; \ \ /* \ * Deduct the rounded mickeys from pending mickeys. \ * Note: we multiply by 2 to offset the previous \ * accumulation of instantaneous movement into \ * pending. \ */ \ (P) -= ((I) << 1); \ \ /* truncate pending to 0 if it becomes negative. */ \ (P) = imax((P), 0); \ } else { \ /* \ * Round down instantaneous movement to the nearest \ * ceiling. This helps preserve small mickey \ * movements from being lost in following scaling \ * operation. \ */ \ (I) = (((I) - (atp_mickeys_scale_factor - 1)) / \ atp_mickeys_scale_factor) * \ atp_mickeys_scale_factor; \ \ /* \ * Deduct the rounded mickeys from pending mickeys. \ * Note: we multiply by 2 to offset the previous \ * accumulation of instantaneous movement into \ * pending. \ */ \ (P) -= ((I) << 1); \ \ /* truncate pending to 0 if it becomes positive. */ \ (P) = imin((P), 0); \ } \ } UPDATE_INSTANTANEOUS_AND_PENDING(strokep->instantaneous_dx, strokep->pending_dx); UPDATE_INSTANTANEOUS_AND_PENDING(strokep->instantaneous_dy, strokep->pending_dy); } /* * Compute a smoothened value for the stroke's movement from * instantaneous changes in the X and Y components. */ static boolean_t atp_compute_stroke_movement(atp_stroke_t *strokep) { /* * Short movements are added first to the 'pending' bucket, * and then acted upon only when their aggregate exceeds a * threshold. This has the effect of filtering away movement * noise. */ if (atp_stroke_has_small_movement(strokep)) atp_update_pending_mickeys(strokep); else { /* large movement */ /* clear away any pending mickeys if there are large movements*/ strokep->pending_dx = 0; strokep->pending_dy = 0; } /* scale movement */ strokep->movement_dx = (strokep->instantaneous_dx) / (int)atp_mickeys_scale_factor; strokep->movement_dy = (strokep->instantaneous_dy) / (int)atp_mickeys_scale_factor; if ((abs(strokep->instantaneous_dx) >= ATP_FAST_MOVEMENT_TRESHOLD) || (abs(strokep->instantaneous_dy) >= ATP_FAST_MOVEMENT_TRESHOLD)) { strokep->movement_dx <<= 1; strokep->movement_dy <<= 1; } strokep->cum_movement_x += strokep->movement_dx; strokep->cum_movement_y += strokep->movement_dy; return ((strokep->movement_dx != 0) || (strokep->movement_dy != 0)); } /* * Terminate a stroke. Aside from immature strokes, a slide or touch is * retained as a zombies so as to reap all their termination siblings * together; this helps establish the number of fingers involved at the * end of a multi-touch gesture. */ static void atp_terminate_stroke(struct atp_softc *sc, atp_stroke_t *strokep) { if (strokep->flags & ATSF_ZOMBIE) return; /* Drop immature strokes rightaway. */ if (strokep->age <= atp_stroke_maturity_threshold) { atp_free_stroke(sc, strokep); return; } strokep->flags |= ATSF_ZOMBIE; sc->sc_state |= ATP_ZOMBIES_EXIST; callout_reset(&sc->sc_callout, ATP_ZOMBIE_STROKE_REAP_INTERVAL, atp_reap_sibling_zombies, sc); /* * Reset the double-click-n-drag at the termination of any * slide stroke. */ if (strokep->type == ATP_STROKE_SLIDE) sc->sc_state &= ~ATP_DOUBLE_TAP_DRAG; } static boolean_t atp_is_horizontal_scroll(const atp_stroke_t *strokep) { if (abs(strokep->cum_movement_x) < atp_slide_min_movement) return (false); if (strokep->cum_movement_y == 0) return (true); return (abs(strokep->cum_movement_x / strokep->cum_movement_y) >= 4); } static boolean_t atp_is_vertical_scroll(const atp_stroke_t *strokep) { if (abs(strokep->cum_movement_y) < atp_slide_min_movement) return (false); if (strokep->cum_movement_x == 0) return (true); return (abs(strokep->cum_movement_y / strokep->cum_movement_x) >= 4); } static void atp_reap_sibling_zombies(void *arg) { struct atp_softc *sc = (struct atp_softc *)arg; u_int8_t n_touches_reaped = 0; u_int8_t n_slides_reaped = 0; u_int8_t n_horizontal_scrolls = 0; u_int8_t n_vertical_scrolls = 0; int horizontal_scroll = 0; int vertical_scroll = 0; atp_stroke_t *strokep; atp_stroke_t *strokep_next; DPRINTFN(ATP_LLEVEL_INFO, "\n"); TAILQ_FOREACH_SAFE(strokep, &sc->sc_stroke_used, entry, strokep_next) { if ((strokep->flags & ATSF_ZOMBIE) == 0) continue; if (strokep->type == ATP_STROKE_TOUCH) { n_touches_reaped++; } else { n_slides_reaped++; if (atp_is_horizontal_scroll(strokep)) { n_horizontal_scrolls++; horizontal_scroll += strokep->cum_movement_x; } else if (atp_is_vertical_scroll(strokep)) { n_vertical_scrolls++; vertical_scroll += strokep->cum_movement_y; } } atp_free_stroke(sc, strokep); } DPRINTFN(ATP_LLEVEL_INFO, "reaped %u zombies\n", n_touches_reaped + n_slides_reaped); sc->sc_state &= ~ATP_ZOMBIES_EXIST; /* No further processing necessary if physical button is depressed. */ if (sc->sc_ibtn != 0) return; if ((n_touches_reaped == 0) && (n_slides_reaped == 0)) return; /* Add a pair of virtual button events (button-down and button-up) if * the physical button isn't pressed. */ if (n_touches_reaped != 0) { if (n_touches_reaped < atp_tap_minimum) return; switch (n_touches_reaped) { case 1: atp_add_to_queue(sc, 0, 0, 0, MOUSE_BUTTON1DOWN); microtime(&sc->sc_touch_reap_time); /* remember this time */ break; case 2: atp_add_to_queue(sc, 0, 0, 0, MOUSE_BUTTON3DOWN); break; case 3: atp_add_to_queue(sc, 0, 0, 0, MOUSE_BUTTON2DOWN); break; default: /* we handle taps of only up to 3 fingers */ return; } atp_add_to_queue(sc, 0, 0, 0, 0); /* button release */ } else if ((n_slides_reaped == 2) && (n_horizontal_scrolls == 2)) { if (horizontal_scroll < 0) atp_add_to_queue(sc, 0, 0, 0, MOUSE_BUTTON4DOWN); else atp_add_to_queue(sc, 0, 0, 0, MOUSE_BUTTON5DOWN); atp_add_to_queue(sc, 0, 0, 0, 0); /* button release */ } } /* Switch a given touch stroke to being a slide. */ static void atp_convert_to_slide(struct atp_softc *sc, atp_stroke_t *strokep) { strokep->type = ATP_STROKE_SLIDE; /* Are we at the beginning of a double-click-n-drag? */ if ((sc->sc_n_strokes == 1) && ((sc->sc_state & ATP_ZOMBIES_EXIST) == 0) && timevalcmp(&strokep->ctime, &sc->sc_touch_reap_time, >)) { struct timeval delta; struct timeval window = { atp_double_tap_threshold / 1000000, atp_double_tap_threshold % 1000000 }; delta = strokep->ctime; timevalsub(&delta, &sc->sc_touch_reap_time); if (timevalcmp(&delta, &window, <=)) sc->sc_state |= ATP_DOUBLE_TAP_DRAG; } } static void atp_reset_buf(struct atp_softc *sc) { /* reset read queue */ usb_fifo_reset(sc->sc_fifo.fp[USB_FIFO_RX]); } static void atp_add_to_queue(struct atp_softc *sc, int dx, int dy, int dz, uint32_t buttons_in) { uint32_t buttons_out; uint8_t buf[8]; dx = imin(dx, 254); dx = imax(dx, -256); dy = imin(dy, 254); dy = imax(dy, -256); dz = imin(dz, 126); dz = imax(dz, -128); buttons_out = MOUSE_MSC_BUTTONS; if (buttons_in & MOUSE_BUTTON1DOWN) buttons_out &= ~MOUSE_MSC_BUTTON1UP; else if (buttons_in & MOUSE_BUTTON2DOWN) buttons_out &= ~MOUSE_MSC_BUTTON2UP; else if (buttons_in & MOUSE_BUTTON3DOWN) buttons_out &= ~MOUSE_MSC_BUTTON3UP; DPRINTFN(ATP_LLEVEL_INFO, "dx=%d, dy=%d, buttons=%x\n", dx, dy, buttons_out); /* Encode the mouse data in standard format; refer to mouse(4) */ buf[0] = sc->sc_mode.syncmask[1]; buf[0] |= buttons_out; buf[1] = dx >> 1; buf[2] = dy >> 1; buf[3] = dx - (dx >> 1); buf[4] = dy - (dy >> 1); /* Encode extra bytes for level 1 */ if (sc->sc_mode.level == 1) { buf[5] = dz >> 1; buf[6] = dz - (dz >> 1); buf[7] = (((~buttons_in) >> 3) & MOUSE_SYS_EXTBUTTONS); } usb_fifo_put_data_linear(sc->sc_fifo.fp[USB_FIFO_RX], buf, sc->sc_mode.packetsize, 1); } static int atp_probe(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bInterfaceClass != UICLASS_HID) return (ENXIO); /* * Note: for some reason, the check * (uaa->info.bInterfaceProtocol == UIPROTO_MOUSE) doesn't hold true * for wellspring trackpads, so we've removed it from the common path. */ if ((usbd_lookup_id_by_uaa(fg_devs, sizeof(fg_devs), uaa)) == 0) return ((uaa->info.bInterfaceProtocol == UIPROTO_MOUSE) ? 0 : ENXIO); if ((usbd_lookup_id_by_uaa(wsp_devs, sizeof(wsp_devs), uaa)) == 0) if (uaa->info.bIfaceIndex == WELLSPRING_INTERFACE_INDEX) return (0); return (ENXIO); } static int atp_attach(device_t dev) { struct atp_softc *sc = device_get_softc(dev); struct usb_attach_arg *uaa = device_get_ivars(dev); usb_error_t err; void *descriptor_ptr = NULL; uint16_t descriptor_len; unsigned long di; DPRINTFN(ATP_LLEVEL_INFO, "sc=%p\n", sc); sc->sc_dev = dev; sc->sc_usb_device = uaa->device; /* Get HID descriptor */ if (usbd_req_get_hid_desc(uaa->device, NULL, &descriptor_ptr, &descriptor_len, M_TEMP, uaa->info.bIfaceIndex) != USB_ERR_NORMAL_COMPLETION) return (ENXIO); /* Get HID report descriptor length */ sc->sc_expected_sensor_data_len = hid_report_size(descriptor_ptr, descriptor_len, hid_input, NULL); free(descriptor_ptr, M_TEMP); if ((sc->sc_expected_sensor_data_len <= 0) || (sc->sc_expected_sensor_data_len > ATP_SENSOR_DATA_BUF_MAX)) { DPRINTF("atp_attach: datalength invalid or too large: %d\n", sc->sc_expected_sensor_data_len); return (ENXIO); } /* * By default the touchpad behaves like an HID device, sending * packets with reportID = 2. Such reports contain only * limited information--they encode movement deltas and button * events,--but do not include data from the pressure * sensors. The device input mode can be switched from HID * reports to raw sensor data using vendor-specific USB * control commands. */ if ((err = atp_set_device_mode(sc, RAW_SENSOR_MODE)) != 0) { DPRINTF("failed to set mode to 'RAW_SENSOR' (%d)\n", err); return (ENXIO); } mtx_init(&sc->sc_mutex, "atpmtx", NULL, MTX_DEF | MTX_RECURSE); di = USB_GET_DRIVER_INFO(uaa); sc->sc_family = DECODE_FAMILY_FROM_DRIVER_INFO(di); switch(sc->sc_family) { case TRACKPAD_FAMILY_FOUNTAIN_GEYSER: sc->sc_params = &fg_dev_params[DECODE_PRODUCT_FROM_DRIVER_INFO(di)]; sc->sensor_data_interpreter = fg_interpret_sensor_data; break; case TRACKPAD_FAMILY_WELLSPRING: sc->sc_params = &wsp_dev_params[DECODE_PRODUCT_FROM_DRIVER_INFO(di)]; sc->sensor_data_interpreter = wsp_interpret_sensor_data; break; default: goto detach; } err = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex, sc->sc_xfer, atp_xfer_config, ATP_N_TRANSFER, sc, &sc->sc_mutex); if (err) { DPRINTF("error=%s\n", usbd_errstr(err)); goto detach; } if (usb_fifo_attach(sc->sc_usb_device, sc, &sc->sc_mutex, &atp_fifo_methods, &sc->sc_fifo, device_get_unit(dev), -1, uaa->info.bIfaceIndex, UID_ROOT, GID_OPERATOR, 0644)) { goto detach; } device_set_usb_desc(dev); sc->sc_hw.buttons = 3; sc->sc_hw.iftype = MOUSE_IF_USB; sc->sc_hw.type = MOUSE_PAD; sc->sc_hw.model = MOUSE_MODEL_GENERIC; sc->sc_hw.hwid = 0; sc->sc_mode.protocol = MOUSE_PROTO_MSC; sc->sc_mode.rate = -1; sc->sc_mode.resolution = MOUSE_RES_UNKNOWN; sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC; sc->sc_mode.accelfactor = 0; sc->sc_mode.level = 0; sc->sc_state = 0; sc->sc_ibtn = 0; callout_init_mtx(&sc->sc_callout, &sc->sc_mutex, 0); return (0); detach: atp_detach(dev); return (ENOMEM); } static int atp_detach(device_t dev) { struct atp_softc *sc; sc = device_get_softc(dev); atp_set_device_mode(sc, HID_MODE); mtx_lock(&sc->sc_mutex); callout_drain(&sc->sc_callout); if (sc->sc_state & ATP_ENABLED) atp_disable(sc); mtx_unlock(&sc->sc_mutex); usb_fifo_detach(&sc->sc_fifo); usbd_transfer_unsetup(sc->sc_xfer, ATP_N_TRANSFER); mtx_destroy(&sc->sc_mutex); return (0); } static void atp_intr(struct usb_xfer *xfer, usb_error_t error) { struct atp_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int len; usbd_xfer_status(xfer, &len, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, sc->sc_sensor_data, len); if (len < sc->sc_expected_sensor_data_len) { /* make sure we don't process old data */ memset(sc->sc_sensor_data + len, 0, sc->sc_expected_sensor_data_len - len); } sc->sc_status.flags &= ~(MOUSE_STDBUTTONSCHANGED | MOUSE_POSCHANGED); sc->sc_status.obutton = sc->sc_status.button; (sc->sensor_data_interpreter)(sc, len); if (sc->sc_status.button != 0) { /* Reset DOUBLE_TAP_N_DRAG if the button is pressed. */ sc->sc_state &= ~ATP_DOUBLE_TAP_DRAG; } else if (sc->sc_state & ATP_DOUBLE_TAP_DRAG) { /* Assume a button-press with DOUBLE_TAP_N_DRAG. */ sc->sc_status.button = MOUSE_BUTTON1DOWN; } sc->sc_status.flags |= sc->sc_status.button ^ sc->sc_status.obutton; if (sc->sc_status.flags & MOUSE_STDBUTTONSCHANGED) { DPRINTFN(ATP_LLEVEL_INFO, "button %s\n", ((sc->sc_status.button & MOUSE_BUTTON1DOWN) ? "pressed" : "released")); } if (sc->sc_status.flags & (MOUSE_POSCHANGED | MOUSE_STDBUTTONSCHANGED)) { atp_stroke_t *strokep; u_int8_t n_movements = 0; int dx = 0; int dy = 0; int dz = 0; TAILQ_FOREACH(strokep, &sc->sc_stroke_used, entry) { if (strokep->flags & ATSF_ZOMBIE) continue; dx += strokep->movement_dx; dy += strokep->movement_dy; if (strokep->movement_dx || strokep->movement_dy) n_movements++; } /* average movement if multiple strokes record motion.*/ if (n_movements > 1) { dx /= (int)n_movements; dy /= (int)n_movements; } /* detect multi-finger vertical scrolls */ if (n_movements >= 2) { boolean_t all_vertical_scrolls = true; TAILQ_FOREACH(strokep, &sc->sc_stroke_used, entry) { if (strokep->flags & ATSF_ZOMBIE) continue; if (!atp_is_vertical_scroll(strokep)) all_vertical_scrolls = false; } if (all_vertical_scrolls) { dz = dy; dy = dx = 0; } } sc->sc_status.dx += dx; sc->sc_status.dy += dy; sc->sc_status.dz += dz; atp_add_to_queue(sc, dx, -dy, -dz, sc->sc_status.button); } case USB_ST_SETUP: tr_setup: /* check if we can put more data into the FIFO */ if (usb_fifo_put_bytes_max(sc->sc_fifo.fp[USB_FIFO_RX]) != 0) { usbd_xfer_set_frame_len(xfer, 0, sc->sc_expected_sensor_data_len); usbd_transfer_submit(xfer); } break; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void atp_start_read(struct usb_fifo *fifo) { struct atp_softc *sc = usb_fifo_softc(fifo); int rate; /* Check if we should override the default polling interval */ rate = sc->sc_pollrate; /* Range check rate */ if (rate > 1000) rate = 1000; /* Check for set rate */ if ((rate > 0) && (sc->sc_xfer[ATP_INTR_DT] != NULL)) { /* Stop current transfer, if any */ usbd_transfer_stop(sc->sc_xfer[ATP_INTR_DT]); /* Set new interval */ usbd_xfer_set_interval(sc->sc_xfer[ATP_INTR_DT], 1000 / rate); /* Only set pollrate once */ sc->sc_pollrate = 0; } usbd_transfer_start(sc->sc_xfer[ATP_INTR_DT]); } static void atp_stop_read(struct usb_fifo *fifo) { struct atp_softc *sc = usb_fifo_softc(fifo); usbd_transfer_stop(sc->sc_xfer[ATP_INTR_DT]); } static int atp_open(struct usb_fifo *fifo, int fflags) { struct atp_softc *sc = usb_fifo_softc(fifo); /* check for duplicate open, should not happen */ if (sc->sc_fflags & fflags) return (EBUSY); /* check for first open */ if (sc->sc_fflags == 0) { int rc; if ((rc = atp_enable(sc)) != 0) return (rc); } if (fflags & FREAD) { if (usb_fifo_alloc_buffer(fifo, ATP_FIFO_BUF_SIZE, ATP_FIFO_QUEUE_MAXLEN)) { return (ENOMEM); } } sc->sc_fflags |= (fflags & (FREAD | FWRITE)); return (0); } static void atp_close(struct usb_fifo *fifo, int fflags) { struct atp_softc *sc = usb_fifo_softc(fifo); if (fflags & FREAD) usb_fifo_free_buffer(fifo); sc->sc_fflags &= ~(fflags & (FREAD | FWRITE)); if (sc->sc_fflags == 0) { atp_disable(sc); } } static int atp_ioctl(struct usb_fifo *fifo, u_long cmd, void *addr, int fflags) { struct atp_softc *sc = usb_fifo_softc(fifo); mousemode_t mode; int error = 0; mtx_lock(&sc->sc_mutex); switch(cmd) { case MOUSE_GETHWINFO: *(mousehw_t *)addr = sc->sc_hw; break; case MOUSE_GETMODE: *(mousemode_t *)addr = sc->sc_mode; break; case MOUSE_SETMODE: mode = *(mousemode_t *)addr; if (mode.level == -1) /* Don't change the current setting */ ; else if ((mode.level < 0) || (mode.level > 1)) { error = EINVAL; break; } sc->sc_mode.level = mode.level; sc->sc_pollrate = mode.rate; sc->sc_hw.buttons = 3; if (sc->sc_mode.level == 0) { sc->sc_mode.protocol = MOUSE_PROTO_MSC; sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC; } else if (sc->sc_mode.level == 1) { sc->sc_mode.protocol = MOUSE_PROTO_SYSMOUSE; sc->sc_mode.packetsize = MOUSE_SYS_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_SYS_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_SYS_SYNC; } atp_reset_buf(sc); break; case MOUSE_GETLEVEL: *(int *)addr = sc->sc_mode.level; break; case MOUSE_SETLEVEL: if ((*(int *)addr < 0) || (*(int *)addr > 1)) { error = EINVAL; break; } sc->sc_mode.level = *(int *)addr; sc->sc_hw.buttons = 3; if (sc->sc_mode.level == 0) { sc->sc_mode.protocol = MOUSE_PROTO_MSC; sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC; } else if (sc->sc_mode.level == 1) { sc->sc_mode.protocol = MOUSE_PROTO_SYSMOUSE; sc->sc_mode.packetsize = MOUSE_SYS_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_SYS_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_SYS_SYNC; } atp_reset_buf(sc); break; case MOUSE_GETSTATUS: { mousestatus_t *status = (mousestatus_t *)addr; *status = sc->sc_status; sc->sc_status.obutton = sc->sc_status.button; sc->sc_status.button = 0; sc->sc_status.dx = 0; sc->sc_status.dy = 0; sc->sc_status.dz = 0; if (status->dx || status->dy || status->dz) status->flags |= MOUSE_POSCHANGED; if (status->button != status->obutton) status->flags |= MOUSE_BUTTONSCHANGED; break; } default: error = ENOTTY; break; } mtx_unlock(&sc->sc_mutex); return (error); } static int atp_sysctl_scale_factor_handler(SYSCTL_HANDLER_ARGS) { int error; u_int tmp; tmp = atp_mickeys_scale_factor; error = sysctl_handle_int(oidp, &tmp, 0, req); if (error != 0 || req->newptr == NULL) return (error); if (tmp == atp_mickeys_scale_factor) return (0); /* no change */ if ((tmp == 0) || (tmp > (10 * ATP_SCALE_FACTOR))) return (EINVAL); atp_mickeys_scale_factor = tmp; DPRINTFN(ATP_LLEVEL_INFO, "%s: resetting mickeys_scale_factor to %u\n", ATP_DRIVER_NAME, tmp); return (0); } static devclass_t atp_devclass; static device_method_t atp_methods[] = { DEVMETHOD(device_probe, atp_probe), DEVMETHOD(device_attach, atp_attach), DEVMETHOD(device_detach, atp_detach), DEVMETHOD_END }; static driver_t atp_driver = { .name = ATP_DRIVER_NAME, .methods = atp_methods, .size = sizeof(struct atp_softc) }; DRIVER_MODULE(atp, uhub, atp_driver, atp_devclass, NULL, 0); MODULE_DEPEND(atp, usb, 1, 1, 1); MODULE_VERSION(atp, 1); Index: head/sys/dev/usb/input/uep.c =================================================================== --- head/sys/dev/usb/input/uep.c (revision 276700) +++ head/sys/dev/usb/input/uep.c (revision 276701) @@ -1,443 +1,443 @@ /*- * Copyright 2010, Gleb Smirnoff * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ /* * http://home.eeti.com.tw/web20/drivers/Software%20Programming%20Guide_v2.0.pdf */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #include #include #include #define USB_DEBUG_VAR uep_debug #include #ifdef USB_DEBUG static int uep_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, uep, CTLFLAG_RW, 0, "USB uep"); -SYSCTL_INT(_hw_usb_uep, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_uep, OID_AUTO, debug, CTLFLAG_RWTUN, &uep_debug, 0, "Debug level"); #endif #define UEP_MAX_X 2047 #define UEP_MAX_Y 2047 #define UEP_DOWN 0x01 #define UEP_PACKET_LEN_MAX 16 #define UEP_PACKET_LEN_REPORT 5 #define UEP_PACKET_LEN_REPORT2 6 #define UEP_PACKET_DIAG 0x0a #define UEP_PACKET_REPORT_MASK 0xe0 #define UEP_PACKET_REPORT 0x80 #define UEP_PACKET_REPORT_PRESSURE 0xc0 #define UEP_PACKET_REPORT_PLAYER 0xa0 #define UEP_PACKET_LEN_MASK #define UEP_FIFO_BUF_SIZE 8 /* bytes */ #define UEP_FIFO_QUEUE_MAXLEN 50 /* units */ enum { UEP_INTR_DT, UEP_N_TRANSFER, }; struct uep_softc { struct mtx mtx; struct usb_xfer *xfer[UEP_N_TRANSFER]; struct usb_fifo_sc fifo; u_int pollrate; u_int state; #define UEP_ENABLED 0x01 /* Reassembling buffer. */ u_char buf[UEP_PACKET_LEN_MAX]; uint8_t buf_len; }; static usb_callback_t uep_intr_callback; static device_probe_t uep_probe; static device_attach_t uep_attach; static device_detach_t uep_detach; static usb_fifo_cmd_t uep_start_read; static usb_fifo_cmd_t uep_stop_read; static usb_fifo_open_t uep_open; static usb_fifo_close_t uep_close; static void uep_put_queue(struct uep_softc *, u_char *); static struct usb_fifo_methods uep_fifo_methods = { .f_open = &uep_open, .f_close = &uep_close, .f_start_read = &uep_start_read, .f_stop_read = &uep_stop_read, .basename[0] = "uep", }; static int get_pkt_len(u_char *buf) { if (buf[0] == UEP_PACKET_DIAG) { int len; len = buf[1] + 2; if (len > UEP_PACKET_LEN_MAX) { DPRINTF("bad packet len %u\n", len); return (UEP_PACKET_LEN_MAX); } return (len); } switch (buf[0] & UEP_PACKET_REPORT_MASK) { case UEP_PACKET_REPORT: return (UEP_PACKET_LEN_REPORT); case UEP_PACKET_REPORT_PRESSURE: case UEP_PACKET_REPORT_PLAYER: case UEP_PACKET_REPORT_PRESSURE | UEP_PACKET_REPORT_PLAYER: return (UEP_PACKET_LEN_REPORT2); default: DPRINTF("bad packet len 0\n"); return (0); } } static void uep_process_pkt(struct uep_softc *sc, u_char *buf) { int32_t x, y; if ((buf[0] & 0xFE) != 0x80) { DPRINTF("bad input packet format 0x%.2x\n", buf[0]); return; } /* * Packet format is 5 bytes: * * 1000000T * 0000AAAA * 0AAAAAAA * 0000BBBB * 0BBBBBBB * * T: 1=touched 0=not touched * A: bits of axis A position, MSB to LSB * B: bits of axis B position, MSB to LSB * * For the unit I have, which is CTF1020-S from CarTFT.com, * A = X and B = Y. But in NetBSD uep(4) it is other way round :) * * The controller sends a stream of T=1 events while the * panel is touched, followed by a single T=0 event. * */ x = (buf[1] << 7) | buf[2]; y = (buf[3] << 7) | buf[4]; DPRINTFN(2, "x %u y %u\n", x, y); uep_put_queue(sc, buf); } static void uep_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct uep_softc *sc = usbd_xfer_softc(xfer); int len; usbd_xfer_status(xfer, &len, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: { struct usb_page_cache *pc; u_char buf[17], *p; int pkt_len; if (len > (int)sizeof(buf)) { DPRINTF("bad input length %d\n", len); goto tr_setup; } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, buf, len); /* * The below code mimics Linux a lot. I don't know * why NetBSD reads complete packets, but we need * to reassamble 'em like Linux does (tries?). */ if (sc->buf_len > 0) { int res; if (sc->buf_len == 1) sc->buf[1] = buf[0]; if ((pkt_len = get_pkt_len(sc->buf)) == 0) goto tr_setup; res = pkt_len - sc->buf_len; memcpy(sc->buf + sc->buf_len, buf, res); uep_process_pkt(sc, sc->buf); sc->buf_len = 0; p = buf + res; len -= res; } else p = buf; if (len == 1) { sc->buf[0] = buf[0]; sc->buf_len = 1; goto tr_setup; } while (len > 0) { if ((pkt_len = get_pkt_len(p)) == 0) goto tr_setup; /* full packet: process */ if (pkt_len <= len) { uep_process_pkt(sc, p); } else { /* incomplete packet: save in buffer */ memcpy(sc->buf, p, len); sc->buf_len = len; } p += pkt_len; len -= pkt_len; } } case USB_ST_SETUP: tr_setup: /* check if we can put more data into the FIFO */ if (usb_fifo_put_bytes_max(sc->fifo.fp[USB_FIFO_RX]) != 0) { usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); } break; default: if (error != USB_ERR_CANCELLED) { /* try clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static const struct usb_config uep_config[UEP_N_TRANSFER] = { [UEP_INTR_DT] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = &uep_intr_callback, }, }; static const STRUCT_USB_HOST_ID uep_devs[] = { {USB_VPI(USB_VENDOR_EGALAX, USB_PRODUCT_EGALAX_TPANEL, 0)}, {USB_VPI(USB_VENDOR_EGALAX, USB_PRODUCT_EGALAX_TPANEL2, 0)}, {USB_VPI(USB_VENDOR_EGALAX2, USB_PRODUCT_EGALAX2_TPANEL, 0)}, }; static int uep_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != 0) return (ENXIO); if (uaa->info.bIfaceIndex != 0) return (ENXIO); return (usbd_lookup_id_by_uaa(uep_devs, sizeof(uep_devs), uaa)); } static int uep_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct uep_softc *sc = device_get_softc(dev); int error; device_set_usb_desc(dev); mtx_init(&sc->mtx, "uep lock", NULL, MTX_DEF); error = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex, sc->xfer, uep_config, UEP_N_TRANSFER, sc, &sc->mtx); if (error) { DPRINTF("usbd_transfer_setup error=%s\n", usbd_errstr(error)); goto detach; } error = usb_fifo_attach(uaa->device, sc, &sc->mtx, &uep_fifo_methods, &sc->fifo, device_get_unit(dev), -1, uaa->info.bIfaceIndex, UID_ROOT, GID_OPERATOR, 0644); if (error) { DPRINTF("usb_fifo_attach error=%s\n", usbd_errstr(error)); goto detach; } sc->buf_len = 0; return (0); detach: uep_detach(dev); return (ENOMEM); /* XXX */ } static int uep_detach(device_t dev) { struct uep_softc *sc = device_get_softc(dev); usb_fifo_detach(&sc->fifo); usbd_transfer_unsetup(sc->xfer, UEP_N_TRANSFER); mtx_destroy(&sc->mtx); return (0); } static void uep_start_read(struct usb_fifo *fifo) { struct uep_softc *sc = usb_fifo_softc(fifo); u_int rate; if ((rate = sc->pollrate) > 1000) rate = 1000; if (rate > 0 && sc->xfer[UEP_INTR_DT] != NULL) { usbd_transfer_stop(sc->xfer[UEP_INTR_DT]); usbd_xfer_set_interval(sc->xfer[UEP_INTR_DT], 1000 / rate); sc->pollrate = 0; } usbd_transfer_start(sc->xfer[UEP_INTR_DT]); } static void uep_stop_read(struct usb_fifo *fifo) { struct uep_softc *sc = usb_fifo_softc(fifo); usbd_transfer_stop(sc->xfer[UEP_INTR_DT]); } static void uep_put_queue(struct uep_softc *sc, u_char *buf) { usb_fifo_put_data_linear(sc->fifo.fp[USB_FIFO_RX], buf, UEP_PACKET_LEN_REPORT, 1); } static int uep_open(struct usb_fifo *fifo, int fflags) { if (fflags & FREAD) { struct uep_softc *sc = usb_fifo_softc(fifo); if (sc->state & UEP_ENABLED) return (EBUSY); if (usb_fifo_alloc_buffer(fifo, UEP_FIFO_BUF_SIZE, UEP_FIFO_QUEUE_MAXLEN)) return (ENOMEM); sc->state |= UEP_ENABLED; } return (0); } static void uep_close(struct usb_fifo *fifo, int fflags) { if (fflags & FREAD) { struct uep_softc *sc = usb_fifo_softc(fifo); sc->state &= ~(UEP_ENABLED); usb_fifo_free_buffer(fifo); } } static devclass_t uep_devclass; static device_method_t uep_methods[] = { DEVMETHOD(device_probe, uep_probe), DEVMETHOD(device_attach, uep_attach), DEVMETHOD(device_detach, uep_detach), { 0, 0 }, }; static driver_t uep_driver = { .name = "uep", .methods = uep_methods, .size = sizeof(struct uep_softc), }; DRIVER_MODULE(uep, uhub, uep_driver, uep_devclass, NULL, NULL); MODULE_DEPEND(uep, usb, 1, 1, 1); MODULE_VERSION(uep, 1); Index: head/sys/dev/usb/input/uhid.c =================================================================== --- head/sys/dev/usb/input/uhid.c (revision 276700) +++ head/sys/dev/usb/input/uhid.c (revision 276701) @@ -1,878 +1,878 @@ /* $NetBSD: uhid.c,v 1.46 2001/11/13 06:24:55 lukem Exp $ */ /* Also already merged from NetBSD: * $NetBSD: uhid.c,v 1.54 2002/09/23 05:51:21 simonb Exp $ */ #include __FBSDID("$FreeBSD$"); /*- * Copyright (c) 1998 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Lennart Augustsson (lennart@augustsson.net) at * Carlstedt Research & Technology. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * HID spec: http://www.usb.org/developers/devclass_docs/HID1_11.pdf */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #include #include #include #include #include #define USB_DEBUG_VAR uhid_debug #include #include #include #ifdef USB_DEBUG static int uhid_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, uhid, CTLFLAG_RW, 0, "USB uhid"); -SYSCTL_INT(_hw_usb_uhid, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_uhid, OID_AUTO, debug, CTLFLAG_RWTUN, &uhid_debug, 0, "Debug level"); #endif #define UHID_BSIZE 1024 /* bytes, buffer size */ #define UHID_FRAME_NUM 50 /* bytes, frame number */ enum { UHID_INTR_DT_WR, UHID_INTR_DT_RD, UHID_CTRL_DT_WR, UHID_CTRL_DT_RD, UHID_N_TRANSFER, }; struct uhid_softc { struct usb_fifo_sc sc_fifo; struct mtx sc_mtx; struct usb_xfer *sc_xfer[UHID_N_TRANSFER]; struct usb_device *sc_udev; void *sc_repdesc_ptr; uint32_t sc_isize; uint32_t sc_osize; uint32_t sc_fsize; uint16_t sc_repdesc_size; uint8_t sc_iface_no; uint8_t sc_iface_index; uint8_t sc_iid; uint8_t sc_oid; uint8_t sc_fid; uint8_t sc_flags; #define UHID_FLAG_IMMED 0x01 /* set if read should be immediate */ #define UHID_FLAG_STATIC_DESC 0x04 /* set if report descriptors are * static */ }; static const uint8_t uhid_xb360gp_report_descr[] = {UHID_XB360GP_REPORT_DESCR()}; static const uint8_t uhid_graphire_report_descr[] = {UHID_GRAPHIRE_REPORT_DESCR()}; static const uint8_t uhid_graphire3_4x5_report_descr[] = {UHID_GRAPHIRE3_4X5_REPORT_DESCR()}; /* prototypes */ static device_probe_t uhid_probe; static device_attach_t uhid_attach; static device_detach_t uhid_detach; static usb_callback_t uhid_intr_write_callback; static usb_callback_t uhid_intr_read_callback; static usb_callback_t uhid_write_callback; static usb_callback_t uhid_read_callback; static usb_fifo_cmd_t uhid_start_read; static usb_fifo_cmd_t uhid_stop_read; static usb_fifo_cmd_t uhid_start_write; static usb_fifo_cmd_t uhid_stop_write; static usb_fifo_open_t uhid_open; static usb_fifo_close_t uhid_close; static usb_fifo_ioctl_t uhid_ioctl; static struct usb_fifo_methods uhid_fifo_methods = { .f_open = &uhid_open, .f_close = &uhid_close, .f_ioctl = &uhid_ioctl, .f_start_read = &uhid_start_read, .f_stop_read = &uhid_stop_read, .f_start_write = &uhid_start_write, .f_stop_write = &uhid_stop_write, .basename[0] = "uhid", }; static void uhid_intr_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhid_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: case USB_ST_SETUP: tr_setup: pc = usbd_xfer_get_frame(xfer, 0); if (usb_fifo_get_data(sc->sc_fifo.fp[USB_FIFO_TX], pc, 0, usbd_xfer_max_len(xfer), &actlen, 0)) { usbd_xfer_set_frame_len(xfer, 0, actlen); usbd_transfer_submit(xfer); } return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void uhid_intr_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhid_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTF("transferred!\n"); pc = usbd_xfer_get_frame(xfer, 0); /* * If the ID byte is non zero we allow descriptors * having multiple sizes: */ if ((actlen >= (int)sc->sc_isize) || ((actlen > 0) && (sc->sc_iid != 0))) { /* limit report length to the maximum */ if (actlen > (int)sc->sc_isize) actlen = sc->sc_isize; usb_fifo_put_data(sc->sc_fifo.fp[USB_FIFO_RX], pc, 0, actlen, 1); } else { /* ignore it */ DPRINTF("ignored transfer, %d bytes\n", actlen); } case USB_ST_SETUP: re_submit: if (usb_fifo_put_bytes_max( sc->sc_fifo.fp[USB_FIFO_RX]) != 0) { usbd_xfer_set_frame_len(xfer, 0, sc->sc_isize); usbd_transfer_submit(xfer); } return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto re_submit; } return; } } static void uhid_fill_set_report(struct usb_device_request *req, uint8_t iface_no, uint8_t type, uint8_t id, uint16_t size) { req->bmRequestType = UT_WRITE_CLASS_INTERFACE; req->bRequest = UR_SET_REPORT; USETW2(req->wValue, type, id); req->wIndex[0] = iface_no; req->wIndex[1] = 0; USETW(req->wLength, size); } static void uhid_fill_get_report(struct usb_device_request *req, uint8_t iface_no, uint8_t type, uint8_t id, uint16_t size) { req->bmRequestType = UT_READ_CLASS_INTERFACE; req->bRequest = UR_GET_REPORT; USETW2(req->wValue, type, id); req->wIndex[0] = iface_no; req->wIndex[1] = 0; USETW(req->wLength, size); } static void uhid_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhid_softc *sc = usbd_xfer_softc(xfer); struct usb_device_request req; struct usb_page_cache *pc; uint32_t size = sc->sc_osize; uint32_t actlen; uint8_t id; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: case USB_ST_SETUP: /* try to extract the ID byte */ if (sc->sc_oid) { pc = usbd_xfer_get_frame(xfer, 0); if (usb_fifo_get_data(sc->sc_fifo.fp[USB_FIFO_TX], pc, 0, 1, &actlen, 0)) { if (actlen != 1) { goto tr_error; } usbd_copy_out(pc, 0, &id, 1); } else { return; } if (size) { size--; } } else { id = 0; } pc = usbd_xfer_get_frame(xfer, 1); if (usb_fifo_get_data(sc->sc_fifo.fp[USB_FIFO_TX], pc, 0, UHID_BSIZE, &actlen, 1)) { if (actlen != size) { goto tr_error; } uhid_fill_set_report (&req, sc->sc_iface_no, UHID_OUTPUT_REPORT, id, size); pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, &req, sizeof(req)); usbd_xfer_set_frame_len(xfer, 0, sizeof(req)); usbd_xfer_set_frame_len(xfer, 1, size); usbd_xfer_set_frames(xfer, size ? 2 : 1); usbd_transfer_submit(xfer); } return; default: tr_error: /* bomb out */ usb_fifo_get_data_error(sc->sc_fifo.fp[USB_FIFO_TX]); return; } } static void uhid_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhid_softc *sc = usbd_xfer_softc(xfer); struct usb_device_request req; struct usb_page_cache *pc; pc = usbd_xfer_get_frame(xfer, 0); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: usb_fifo_put_data(sc->sc_fifo.fp[USB_FIFO_RX], pc, sizeof(req), sc->sc_isize, 1); return; case USB_ST_SETUP: if (usb_fifo_put_bytes_max(sc->sc_fifo.fp[USB_FIFO_RX]) > 0) { uhid_fill_get_report (&req, sc->sc_iface_no, UHID_INPUT_REPORT, sc->sc_iid, sc->sc_isize); usbd_copy_in(pc, 0, &req, sizeof(req)); usbd_xfer_set_frame_len(xfer, 0, sizeof(req)); usbd_xfer_set_frame_len(xfer, 1, sc->sc_isize); usbd_xfer_set_frames(xfer, sc->sc_isize ? 2 : 1); usbd_transfer_submit(xfer); } return; default: /* Error */ /* bomb out */ usb_fifo_put_data_error(sc->sc_fifo.fp[USB_FIFO_RX]); return; } } static const struct usb_config uhid_config[UHID_N_TRANSFER] = { [UHID_INTR_DT_WR] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .flags = {.pipe_bof = 1,.no_pipe_ok = 1, }, .bufsize = UHID_BSIZE, .callback = &uhid_intr_write_callback, }, [UHID_INTR_DT_RD] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = UHID_BSIZE, .callback = &uhid_intr_read_callback, }, [UHID_CTRL_DT_WR] = { .type = UE_CONTROL, .endpoint = 0x00, /* Control pipe */ .direction = UE_DIR_ANY, .bufsize = sizeof(struct usb_device_request) + UHID_BSIZE, .callback = &uhid_write_callback, .timeout = 1000, /* 1 second */ }, [UHID_CTRL_DT_RD] = { .type = UE_CONTROL, .endpoint = 0x00, /* Control pipe */ .direction = UE_DIR_ANY, .bufsize = sizeof(struct usb_device_request) + UHID_BSIZE, .callback = &uhid_read_callback, .timeout = 1000, /* 1 second */ }, }; static void uhid_start_read(struct usb_fifo *fifo) { struct uhid_softc *sc = usb_fifo_softc(fifo); if (sc->sc_flags & UHID_FLAG_IMMED) { usbd_transfer_start(sc->sc_xfer[UHID_CTRL_DT_RD]); } else { usbd_transfer_start(sc->sc_xfer[UHID_INTR_DT_RD]); } } static void uhid_stop_read(struct usb_fifo *fifo) { struct uhid_softc *sc = usb_fifo_softc(fifo); usbd_transfer_stop(sc->sc_xfer[UHID_CTRL_DT_RD]); usbd_transfer_stop(sc->sc_xfer[UHID_INTR_DT_RD]); } static void uhid_start_write(struct usb_fifo *fifo) { struct uhid_softc *sc = usb_fifo_softc(fifo); if ((sc->sc_flags & UHID_FLAG_IMMED) || sc->sc_xfer[UHID_INTR_DT_WR] == NULL) { usbd_transfer_start(sc->sc_xfer[UHID_CTRL_DT_WR]); } else { usbd_transfer_start(sc->sc_xfer[UHID_INTR_DT_WR]); } } static void uhid_stop_write(struct usb_fifo *fifo) { struct uhid_softc *sc = usb_fifo_softc(fifo); usbd_transfer_stop(sc->sc_xfer[UHID_CTRL_DT_WR]); usbd_transfer_stop(sc->sc_xfer[UHID_INTR_DT_WR]); } static int uhid_get_report(struct uhid_softc *sc, uint8_t type, uint8_t id, void *kern_data, void *user_data, uint16_t len) { int err; uint8_t free_data = 0; if (kern_data == NULL) { kern_data = malloc(len, M_USBDEV, M_WAITOK); if (kern_data == NULL) { err = ENOMEM; goto done; } free_data = 1; } err = usbd_req_get_report(sc->sc_udev, NULL, kern_data, len, sc->sc_iface_index, type, id); if (err) { err = ENXIO; goto done; } if (user_data) { /* dummy buffer */ err = copyout(kern_data, user_data, len); if (err) { goto done; } } done: if (free_data) { free(kern_data, M_USBDEV); } return (err); } static int uhid_set_report(struct uhid_softc *sc, uint8_t type, uint8_t id, void *kern_data, void *user_data, uint16_t len) { int err; uint8_t free_data = 0; if (kern_data == NULL) { kern_data = malloc(len, M_USBDEV, M_WAITOK); if (kern_data == NULL) { err = ENOMEM; goto done; } free_data = 1; err = copyin(user_data, kern_data, len); if (err) { goto done; } } err = usbd_req_set_report(sc->sc_udev, NULL, kern_data, len, sc->sc_iface_index, type, id); if (err) { err = ENXIO; goto done; } done: if (free_data) { free(kern_data, M_USBDEV); } return (err); } static int uhid_open(struct usb_fifo *fifo, int fflags) { struct uhid_softc *sc = usb_fifo_softc(fifo); /* * The buffers are one byte larger than maximum so that one * can detect too large read/writes and short transfers: */ if (fflags & FREAD) { /* reset flags */ sc->sc_flags &= ~UHID_FLAG_IMMED; if (usb_fifo_alloc_buffer(fifo, sc->sc_isize + 1, UHID_FRAME_NUM)) { return (ENOMEM); } } if (fflags & FWRITE) { if (usb_fifo_alloc_buffer(fifo, sc->sc_osize + 1, UHID_FRAME_NUM)) { return (ENOMEM); } } return (0); } static void uhid_close(struct usb_fifo *fifo, int fflags) { if (fflags & (FREAD | FWRITE)) { usb_fifo_free_buffer(fifo); } } static int uhid_ioctl(struct usb_fifo *fifo, u_long cmd, void *addr, int fflags) { struct uhid_softc *sc = usb_fifo_softc(fifo); struct usb_gen_descriptor *ugd; uint32_t size; int error = 0; uint8_t id; switch (cmd) { case USB_GET_REPORT_DESC: ugd = addr; if (sc->sc_repdesc_size > ugd->ugd_maxlen) { size = ugd->ugd_maxlen; } else { size = sc->sc_repdesc_size; } ugd->ugd_actlen = size; if (ugd->ugd_data == NULL) break; /* descriptor length only */ error = copyout(sc->sc_repdesc_ptr, ugd->ugd_data, size); break; case USB_SET_IMMED: if (!(fflags & FREAD)) { error = EPERM; break; } if (*(int *)addr) { /* do a test read */ error = uhid_get_report(sc, UHID_INPUT_REPORT, sc->sc_iid, NULL, NULL, sc->sc_isize); if (error) { break; } mtx_lock(&sc->sc_mtx); sc->sc_flags |= UHID_FLAG_IMMED; mtx_unlock(&sc->sc_mtx); } else { mtx_lock(&sc->sc_mtx); sc->sc_flags &= ~UHID_FLAG_IMMED; mtx_unlock(&sc->sc_mtx); } break; case USB_GET_REPORT: if (!(fflags & FREAD)) { error = EPERM; break; } ugd = addr; switch (ugd->ugd_report_type) { case UHID_INPUT_REPORT: size = sc->sc_isize; id = sc->sc_iid; break; case UHID_OUTPUT_REPORT: size = sc->sc_osize; id = sc->sc_oid; break; case UHID_FEATURE_REPORT: size = sc->sc_fsize; id = sc->sc_fid; break; default: return (EINVAL); } if (id != 0) copyin(ugd->ugd_data, &id, 1); error = uhid_get_report(sc, ugd->ugd_report_type, id, NULL, ugd->ugd_data, imin(ugd->ugd_maxlen, size)); break; case USB_SET_REPORT: if (!(fflags & FWRITE)) { error = EPERM; break; } ugd = addr; switch (ugd->ugd_report_type) { case UHID_INPUT_REPORT: size = sc->sc_isize; id = sc->sc_iid; break; case UHID_OUTPUT_REPORT: size = sc->sc_osize; id = sc->sc_oid; break; case UHID_FEATURE_REPORT: size = sc->sc_fsize; id = sc->sc_fid; break; default: return (EINVAL); } if (id != 0) copyin(ugd->ugd_data, &id, 1); error = uhid_set_report(sc, ugd->ugd_report_type, id, NULL, ugd->ugd_data, imin(ugd->ugd_maxlen, size)); break; case USB_GET_REPORT_ID: *(int *)addr = 0; /* XXX: we only support reportid 0? */ break; default: error = EINVAL; break; } return (error); } static const STRUCT_USB_HOST_ID uhid_devs[] = { /* generic HID class */ {USB_IFACE_CLASS(UICLASS_HID),}, /* the Xbox 360 gamepad doesn't use the HID class */ {USB_IFACE_CLASS(UICLASS_VENDOR), USB_IFACE_SUBCLASS(UISUBCLASS_XBOX360_CONTROLLER), USB_IFACE_PROTOCOL(UIPROTO_XBOX360_GAMEPAD),}, }; static int uhid_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); int error; DPRINTFN(11, "\n"); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); error = usbd_lookup_id_by_uaa(uhid_devs, sizeof(uhid_devs), uaa); if (error) return (error); if (usb_test_quirk(uaa, UQ_HID_IGNORE)) return (ENXIO); /* * Don't attach to mouse and keyboard devices, hence then no * "nomatch" event is generated and then ums and ukbd won't * attach properly when loaded. */ if ((uaa->info.bInterfaceClass == UICLASS_HID) && (uaa->info.bInterfaceSubClass == UISUBCLASS_BOOT) && (((uaa->info.bInterfaceProtocol == UIPROTO_BOOT_KEYBOARD) && !usb_test_quirk(uaa, UQ_KBD_IGNORE)) || ((uaa->info.bInterfaceProtocol == UIPROTO_MOUSE) && !usb_test_quirk(uaa, UQ_UMS_IGNORE)))) return (ENXIO); return (BUS_PROBE_GENERIC); } static int uhid_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct uhid_softc *sc = device_get_softc(dev); int unit = device_get_unit(dev); int error = 0; DPRINTFN(10, "sc=%p\n", sc); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "uhid lock", NULL, MTX_DEF | MTX_RECURSE); sc->sc_udev = uaa->device; sc->sc_iface_no = uaa->info.bIfaceNum; sc->sc_iface_index = uaa->info.bIfaceIndex; error = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex, sc->sc_xfer, uhid_config, UHID_N_TRANSFER, sc, &sc->sc_mtx); if (error) { DPRINTF("error=%s\n", usbd_errstr(error)); goto detach; } if (uaa->info.idVendor == USB_VENDOR_WACOM) { /* the report descriptor for the Wacom Graphire is broken */ if (uaa->info.idProduct == USB_PRODUCT_WACOM_GRAPHIRE) { sc->sc_repdesc_size = sizeof(uhid_graphire_report_descr); sc->sc_repdesc_ptr = (void *)&uhid_graphire_report_descr; sc->sc_flags |= UHID_FLAG_STATIC_DESC; } else if (uaa->info.idProduct == USB_PRODUCT_WACOM_GRAPHIRE3_4X5) { static uint8_t reportbuf[] = {2, 2, 2}; /* * The Graphire3 needs 0x0202 to be written to * feature report ID 2 before it'll start * returning digitizer data. */ error = usbd_req_set_report(uaa->device, NULL, reportbuf, sizeof(reportbuf), uaa->info.bIfaceIndex, UHID_FEATURE_REPORT, 2); if (error) { DPRINTF("set report failed, error=%s (ignored)\n", usbd_errstr(error)); } sc->sc_repdesc_size = sizeof(uhid_graphire3_4x5_report_descr); sc->sc_repdesc_ptr = (void *)&uhid_graphire3_4x5_report_descr; sc->sc_flags |= UHID_FLAG_STATIC_DESC; } } else if ((uaa->info.bInterfaceClass == UICLASS_VENDOR) && (uaa->info.bInterfaceSubClass == UISUBCLASS_XBOX360_CONTROLLER) && (uaa->info.bInterfaceProtocol == UIPROTO_XBOX360_GAMEPAD)) { static const uint8_t reportbuf[3] = {1, 3, 0}; /* * Turn off the four LEDs on the gamepad which * are blinking by default: */ error = usbd_req_set_report(uaa->device, NULL, __DECONST(void *, reportbuf), sizeof(reportbuf), uaa->info.bIfaceIndex, UHID_OUTPUT_REPORT, 0); if (error) { DPRINTF("set output report failed, error=%s (ignored)\n", usbd_errstr(error)); } /* the Xbox 360 gamepad has no report descriptor */ sc->sc_repdesc_size = sizeof(uhid_xb360gp_report_descr); sc->sc_repdesc_ptr = (void *)&uhid_xb360gp_report_descr; sc->sc_flags |= UHID_FLAG_STATIC_DESC; } if (sc->sc_repdesc_ptr == NULL) { error = usbd_req_get_hid_desc(uaa->device, NULL, &sc->sc_repdesc_ptr, &sc->sc_repdesc_size, M_USBDEV, uaa->info.bIfaceIndex); if (error) { device_printf(dev, "no report descriptor\n"); goto detach; } } error = usbd_req_set_idle(uaa->device, NULL, uaa->info.bIfaceIndex, 0, 0); if (error) { DPRINTF("set idle failed, error=%s (ignored)\n", usbd_errstr(error)); } sc->sc_isize = hid_report_size (sc->sc_repdesc_ptr, sc->sc_repdesc_size, hid_input, &sc->sc_iid); sc->sc_osize = hid_report_size (sc->sc_repdesc_ptr, sc->sc_repdesc_size, hid_output, &sc->sc_oid); sc->sc_fsize = hid_report_size (sc->sc_repdesc_ptr, sc->sc_repdesc_size, hid_feature, &sc->sc_fid); if (sc->sc_isize > UHID_BSIZE) { DPRINTF("input size is too large, " "%d bytes (truncating)\n", sc->sc_isize); sc->sc_isize = UHID_BSIZE; } if (sc->sc_osize > UHID_BSIZE) { DPRINTF("output size is too large, " "%d bytes (truncating)\n", sc->sc_osize); sc->sc_osize = UHID_BSIZE; } if (sc->sc_fsize > UHID_BSIZE) { DPRINTF("feature size is too large, " "%d bytes (truncating)\n", sc->sc_fsize); sc->sc_fsize = UHID_BSIZE; } error = usb_fifo_attach(uaa->device, sc, &sc->sc_mtx, &uhid_fifo_methods, &sc->sc_fifo, unit, -1, uaa->info.bIfaceIndex, UID_ROOT, GID_OPERATOR, 0644); if (error) { goto detach; } return (0); /* success */ detach: uhid_detach(dev); return (ENOMEM); } static int uhid_detach(device_t dev) { struct uhid_softc *sc = device_get_softc(dev); usb_fifo_detach(&sc->sc_fifo); usbd_transfer_unsetup(sc->sc_xfer, UHID_N_TRANSFER); if (sc->sc_repdesc_ptr) { if (!(sc->sc_flags & UHID_FLAG_STATIC_DESC)) { free(sc->sc_repdesc_ptr, M_USBDEV); } } mtx_destroy(&sc->sc_mtx); return (0); } static devclass_t uhid_devclass; static device_method_t uhid_methods[] = { DEVMETHOD(device_probe, uhid_probe), DEVMETHOD(device_attach, uhid_attach), DEVMETHOD(device_detach, uhid_detach), DEVMETHOD_END }; static driver_t uhid_driver = { .name = "uhid", .methods = uhid_methods, .size = sizeof(struct uhid_softc), }; DRIVER_MODULE(uhid, uhub, uhid_driver, uhid_devclass, NULL, 0); MODULE_DEPEND(uhid, usb, 1, 1, 1); MODULE_VERSION(uhid, 1); Index: head/sys/dev/usb/input/ums.c =================================================================== --- head/sys/dev/usb/input/ums.c (revision 276700) +++ head/sys/dev/usb/input/ums.c (revision 276701) @@ -1,1054 +1,1054 @@ /*- * Copyright (c) 1998 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Lennart Augustsson (lennart@augustsson.net) at * Carlstedt Research & Technology. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * HID spec: http://www.usb.org/developers/devclass_docs/HID1_11.pdf */ #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 "usbdevs.h" #define USB_DEBUG_VAR ums_debug #include #include #include #include #include #include #ifdef USB_DEBUG static int ums_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, ums, CTLFLAG_RW, 0, "USB ums"); -SYSCTL_INT(_hw_usb_ums, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_ums, OID_AUTO, debug, CTLFLAG_RWTUN, &ums_debug, 0, "Debug level"); #endif #define MOUSE_FLAGS_MASK (HIO_CONST|HIO_RELATIVE) #define MOUSE_FLAGS (HIO_RELATIVE) #define UMS_BUF_SIZE 8 /* bytes */ #define UMS_IFQ_MAXLEN 50 /* units */ #define UMS_BUTTON_MAX 31 /* exclusive, must be less than 32 */ #define UMS_BUT(i) ((i) < 3 ? (((i) + 2) % 3) : (i)) #define UMS_INFO_MAX 2 /* maximum number of HID sets */ enum { UMS_INTR_DT, UMS_N_TRANSFER, }; struct ums_info { struct hid_location sc_loc_w; struct hid_location sc_loc_x; struct hid_location sc_loc_y; struct hid_location sc_loc_z; struct hid_location sc_loc_t; struct hid_location sc_loc_btn[UMS_BUTTON_MAX]; uint32_t sc_flags; #define UMS_FLAG_X_AXIS 0x0001 #define UMS_FLAG_Y_AXIS 0x0002 #define UMS_FLAG_Z_AXIS 0x0004 #define UMS_FLAG_T_AXIS 0x0008 #define UMS_FLAG_SBU 0x0010 /* spurious button up events */ #define UMS_FLAG_REVZ 0x0020 /* Z-axis is reversed */ #define UMS_FLAG_W_AXIS 0x0040 uint8_t sc_iid_w; uint8_t sc_iid_x; uint8_t sc_iid_y; uint8_t sc_iid_z; uint8_t sc_iid_t; uint8_t sc_iid_btn[UMS_BUTTON_MAX]; uint8_t sc_buttons; }; struct ums_softc { struct usb_fifo_sc sc_fifo; struct mtx sc_mtx; struct usb_callout sc_callout; struct ums_info sc_info[UMS_INFO_MAX]; mousehw_t sc_hw; mousemode_t sc_mode; mousestatus_t sc_status; struct usb_xfer *sc_xfer[UMS_N_TRANSFER]; int sc_pollrate; int sc_fflags; uint8_t sc_buttons; uint8_t sc_iid; uint8_t sc_temp[64]; }; static void ums_put_queue_timeout(void *__sc); static usb_callback_t ums_intr_callback; static device_probe_t ums_probe; static device_attach_t ums_attach; static device_detach_t ums_detach; static usb_fifo_cmd_t ums_start_read; static usb_fifo_cmd_t ums_stop_read; static usb_fifo_open_t ums_open; static usb_fifo_close_t ums_close; static usb_fifo_ioctl_t ums_ioctl; static void ums_put_queue(struct ums_softc *, int32_t, int32_t, int32_t, int32_t, int32_t); static int ums_sysctl_handler_parseinfo(SYSCTL_HANDLER_ARGS); static struct usb_fifo_methods ums_fifo_methods = { .f_open = &ums_open, .f_close = &ums_close, .f_ioctl = &ums_ioctl, .f_start_read = &ums_start_read, .f_stop_read = &ums_stop_read, .basename[0] = "ums", }; static void ums_put_queue_timeout(void *__sc) { struct ums_softc *sc = __sc; mtx_assert(&sc->sc_mtx, MA_OWNED); ums_put_queue(sc, 0, 0, 0, 0, 0); } static void ums_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct ums_softc *sc = usbd_xfer_softc(xfer); struct ums_info *info = &sc->sc_info[0]; struct usb_page_cache *pc; uint8_t *buf = sc->sc_temp; int32_t buttons = 0; int32_t buttons_found = 0; int32_t dw = 0; int32_t dx = 0; int32_t dy = 0; int32_t dz = 0; int32_t dt = 0; uint8_t i; uint8_t id; int len; usbd_xfer_status(xfer, &len, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(6, "sc=%p actlen=%d\n", sc, len); if (len > (int)sizeof(sc->sc_temp)) { DPRINTFN(6, "truncating large packet to %zu bytes\n", sizeof(sc->sc_temp)); len = sizeof(sc->sc_temp); } if (len == 0) goto tr_setup; pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, buf, len); DPRINTFN(6, "data = %02x %02x %02x %02x " "%02x %02x %02x %02x\n", (len > 0) ? buf[0] : 0, (len > 1) ? buf[1] : 0, (len > 2) ? buf[2] : 0, (len > 3) ? buf[3] : 0, (len > 4) ? buf[4] : 0, (len > 5) ? buf[5] : 0, (len > 6) ? buf[6] : 0, (len > 7) ? buf[7] : 0); if (sc->sc_iid) { id = *buf; len--; buf++; } else { id = 0; if (sc->sc_info[0].sc_flags & UMS_FLAG_SBU) { if ((*buf == 0x14) || (*buf == 0x15)) { goto tr_setup; } } } repeat: if ((info->sc_flags & UMS_FLAG_W_AXIS) && (id == info->sc_iid_w)) dw += hid_get_data(buf, len, &info->sc_loc_w); if ((info->sc_flags & UMS_FLAG_X_AXIS) && (id == info->sc_iid_x)) dx += hid_get_data(buf, len, &info->sc_loc_x); if ((info->sc_flags & UMS_FLAG_Y_AXIS) && (id == info->sc_iid_y)) dy = -hid_get_data(buf, len, &info->sc_loc_y); if ((info->sc_flags & UMS_FLAG_Z_AXIS) && (id == info->sc_iid_z)) { int32_t temp; temp = hid_get_data(buf, len, &info->sc_loc_z); if (info->sc_flags & UMS_FLAG_REVZ) temp = -temp; dz -= temp; } if ((info->sc_flags & UMS_FLAG_T_AXIS) && (id == info->sc_iid_t)) dt -= hid_get_data(buf, len, &info->sc_loc_t); for (i = 0; i < info->sc_buttons; i++) { uint32_t mask; mask = 1UL << UMS_BUT(i); /* check for correct button ID */ if (id != info->sc_iid_btn[i]) continue; /* check for button pressed */ if (hid_get_data(buf, len, &info->sc_loc_btn[i])) buttons |= mask; /* register button mask */ buttons_found |= mask; } if (++info != &sc->sc_info[UMS_INFO_MAX]) goto repeat; /* keep old button value(s) for non-detected buttons */ buttons |= sc->sc_status.button & ~buttons_found; if (dx || dy || dz || dt || dw || (buttons != sc->sc_status.button)) { DPRINTFN(6, "x:%d y:%d z:%d t:%d w:%d buttons:0x%08x\n", dx, dy, dz, dt, dw, buttons); /* translate T-axis into button presses until further */ if (dt > 0) buttons |= 1UL << 3; else if (dt < 0) buttons |= 1UL << 4; sc->sc_status.button = buttons; sc->sc_status.dx += dx; sc->sc_status.dy += dy; sc->sc_status.dz += dz; /* * sc->sc_status.dt += dt; * no way to export this yet */ /* * The Qtronix keyboard has a built in PS/2 * port for a mouse. The firmware once in a * while posts a spurious button up * event. This event we ignore by doing a * timeout for 50 msecs. If we receive * dx=dy=dz=buttons=0 before we add the event * to the queue. In any other case we delete * the timeout event. */ if ((sc->sc_info[0].sc_flags & UMS_FLAG_SBU) && (dx == 0) && (dy == 0) && (dz == 0) && (dt == 0) && (dw == 0) && (buttons == 0)) { usb_callout_reset(&sc->sc_callout, hz / 20, &ums_put_queue_timeout, sc); } else { usb_callout_stop(&sc->sc_callout); ums_put_queue(sc, dx, dy, dz, dt, buttons); } } case USB_ST_SETUP: tr_setup: /* check if we can put more data into the FIFO */ if (usb_fifo_put_bytes_max( sc->sc_fifo.fp[USB_FIFO_RX]) != 0) { usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); } break; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static const struct usb_config ums_config[UMS_N_TRANSFER] = { [UMS_INTR_DT] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = &ums_intr_callback, }, }; /* A match on these entries will load ums */ static const STRUCT_USB_HOST_ID __used ums_devs[] = { {USB_IFACE_CLASS(UICLASS_HID), USB_IFACE_SUBCLASS(UISUBCLASS_BOOT), USB_IFACE_PROTOCOL(UIPROTO_MOUSE),}, }; static int ums_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); void *d_ptr; int error; uint16_t d_len; DPRINTFN(11, "\n"); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bInterfaceClass != UICLASS_HID) return (ENXIO); if (usb_test_quirk(uaa, UQ_UMS_IGNORE)) return (ENXIO); if ((uaa->info.bInterfaceSubClass == UISUBCLASS_BOOT) && (uaa->info.bInterfaceProtocol == UIPROTO_MOUSE)) return (BUS_PROBE_DEFAULT); error = usbd_req_get_hid_desc(uaa->device, NULL, &d_ptr, &d_len, M_TEMP, uaa->info.bIfaceIndex); if (error) return (ENXIO); if (hid_is_mouse(d_ptr, d_len)) error = BUS_PROBE_DEFAULT; else error = ENXIO; free(d_ptr, M_TEMP); return (error); } static void ums_hid_parse(struct ums_softc *sc, device_t dev, const uint8_t *buf, uint16_t len, uint8_t index) { struct ums_info *info = &sc->sc_info[index]; uint32_t flags; uint8_t i; uint8_t j; if (hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_X), hid_input, index, &info->sc_loc_x, &flags, &info->sc_iid_x)) { if ((flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS) { info->sc_flags |= UMS_FLAG_X_AXIS; } } if (hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Y), hid_input, index, &info->sc_loc_y, &flags, &info->sc_iid_y)) { if ((flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS) { info->sc_flags |= UMS_FLAG_Y_AXIS; } } /* Try the wheel first as the Z activator since it's tradition. */ if (hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_WHEEL), hid_input, index, &info->sc_loc_z, &flags, &info->sc_iid_z) || hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_TWHEEL), hid_input, index, &info->sc_loc_z, &flags, &info->sc_iid_z)) { if ((flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS) { info->sc_flags |= UMS_FLAG_Z_AXIS; } /* * We might have both a wheel and Z direction, if so put * put the Z on the W coordinate. */ if (hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Z), hid_input, index, &info->sc_loc_w, &flags, &info->sc_iid_w)) { if ((flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS) { info->sc_flags |= UMS_FLAG_W_AXIS; } } } else if (hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_Z), hid_input, index, &info->sc_loc_z, &flags, &info->sc_iid_z)) { if ((flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS) { info->sc_flags |= UMS_FLAG_Z_AXIS; } } /* * The Microsoft Wireless Intellimouse 2.0 reports it's wheel * using 0x0048, which is HUG_TWHEEL, and seems to expect you * to know that the byte after the wheel is the tilt axis. * There are no other HID axis descriptors other than X,Y and * TWHEEL */ if (hid_locate(buf, len, HID_USAGE2(HUP_GENERIC_DESKTOP, HUG_TWHEEL), hid_input, index, &info->sc_loc_t, &flags, &info->sc_iid_t)) { info->sc_loc_t.pos += 8; if ((flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS) { info->sc_flags |= UMS_FLAG_T_AXIS; } } else if (hid_locate(buf, len, HID_USAGE2(HUP_CONSUMER, HUC_AC_PAN), hid_input, index, &info->sc_loc_t, &flags, &info->sc_iid_t)) { if ((flags & MOUSE_FLAGS_MASK) == MOUSE_FLAGS) info->sc_flags |= UMS_FLAG_T_AXIS; } /* figure out the number of buttons */ for (i = 0; i < UMS_BUTTON_MAX; i++) { if (!hid_locate(buf, len, HID_USAGE2(HUP_BUTTON, (i + 1)), hid_input, index, &info->sc_loc_btn[i], NULL, &info->sc_iid_btn[i])) { break; } } /* detect other buttons */ for (j = 0; (i < UMS_BUTTON_MAX) && (j < 2); i++, j++) { if (!hid_locate(buf, len, HID_USAGE2(HUP_MICROSOFT, (j + 1)), hid_input, index, &info->sc_loc_btn[i], NULL, &info->sc_iid_btn[i])) { break; } } info->sc_buttons = i; if (i > sc->sc_buttons) sc->sc_buttons = i; if (info->sc_flags == 0) return; /* announce information about the mouse */ device_printf(dev, "%d buttons and [%s%s%s%s%s] coordinates ID=%u\n", (info->sc_buttons), (info->sc_flags & UMS_FLAG_X_AXIS) ? "X" : "", (info->sc_flags & UMS_FLAG_Y_AXIS) ? "Y" : "", (info->sc_flags & UMS_FLAG_Z_AXIS) ? "Z" : "", (info->sc_flags & UMS_FLAG_T_AXIS) ? "T" : "", (info->sc_flags & UMS_FLAG_W_AXIS) ? "W" : "", info->sc_iid_x); } static int ums_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct ums_softc *sc = device_get_softc(dev); struct ums_info *info; void *d_ptr = NULL; int isize; int err; uint16_t d_len; uint8_t i; #ifdef USB_DEBUG uint8_t j; #endif DPRINTFN(11, "sc=%p\n", sc); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "ums lock", NULL, MTX_DEF | MTX_RECURSE); usb_callout_init_mtx(&sc->sc_callout, &sc->sc_mtx, 0); /* * Force the report (non-boot) protocol. * * Mice without boot protocol support may choose not to implement * Set_Protocol at all; Ignore any error. */ err = usbd_req_set_protocol(uaa->device, NULL, uaa->info.bIfaceIndex, 1); err = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex, sc->sc_xfer, ums_config, UMS_N_TRANSFER, sc, &sc->sc_mtx); if (err) { DPRINTF("error=%s\n", usbd_errstr(err)); goto detach; } /* Get HID descriptor */ err = usbd_req_get_hid_desc(uaa->device, NULL, &d_ptr, &d_len, M_TEMP, uaa->info.bIfaceIndex); if (err) { device_printf(dev, "error reading report description\n"); goto detach; } isize = hid_report_size(d_ptr, d_len, hid_input, &sc->sc_iid); /* * The Microsoft Wireless Notebook Optical Mouse seems to be in worse * shape than the Wireless Intellimouse 2.0, as its X, Y, wheel, and * all of its other button positions are all off. It also reports that * it has two addional buttons and a tilt wheel. */ if (usb_test_quirk(uaa, UQ_MS_BAD_CLASS)) { sc->sc_iid = 0; info = &sc->sc_info[0]; info->sc_flags = (UMS_FLAG_X_AXIS | UMS_FLAG_Y_AXIS | UMS_FLAG_Z_AXIS | UMS_FLAG_SBU); info->sc_buttons = 3; isize = 5; /* 1st byte of descriptor report contains garbage */ info->sc_loc_x.pos = 16; info->sc_loc_x.size = 8; info->sc_loc_y.pos = 24; info->sc_loc_y.size = 8; info->sc_loc_z.pos = 32; info->sc_loc_z.size = 8; info->sc_loc_btn[0].pos = 8; info->sc_loc_btn[0].size = 1; info->sc_loc_btn[1].pos = 9; info->sc_loc_btn[1].size = 1; info->sc_loc_btn[2].pos = 10; info->sc_loc_btn[2].size = 1; /* Announce device */ device_printf(dev, "3 buttons and [XYZ] " "coordinates ID=0\n"); } else { /* Search the HID descriptor and announce device */ for (i = 0; i < UMS_INFO_MAX; i++) { ums_hid_parse(sc, dev, d_ptr, d_len, i); } } if (usb_test_quirk(uaa, UQ_MS_REVZ)) { info = &sc->sc_info[0]; /* Some wheels need the Z axis reversed. */ info->sc_flags |= UMS_FLAG_REVZ; } if (isize > (int)usbd_xfer_max_framelen(sc->sc_xfer[UMS_INTR_DT])) { DPRINTF("WARNING: report size, %d bytes, is larger " "than interrupt size, %d bytes!\n", isize, usbd_xfer_max_framelen(sc->sc_xfer[UMS_INTR_DT])); } free(d_ptr, M_TEMP); d_ptr = NULL; #ifdef USB_DEBUG for (j = 0; j < UMS_INFO_MAX; j++) { info = &sc->sc_info[j]; DPRINTF("sc=%p, index=%d\n", sc, j); DPRINTF("X\t%d/%d id=%d\n", info->sc_loc_x.pos, info->sc_loc_x.size, info->sc_iid_x); DPRINTF("Y\t%d/%d id=%d\n", info->sc_loc_y.pos, info->sc_loc_y.size, info->sc_iid_y); DPRINTF("Z\t%d/%d id=%d\n", info->sc_loc_z.pos, info->sc_loc_z.size, info->sc_iid_z); DPRINTF("T\t%d/%d id=%d\n", info->sc_loc_t.pos, info->sc_loc_t.size, info->sc_iid_t); DPRINTF("W\t%d/%d id=%d\n", info->sc_loc_w.pos, info->sc_loc_w.size, info->sc_iid_w); for (i = 0; i < info->sc_buttons; i++) { DPRINTF("B%d\t%d/%d id=%d\n", i + 1, info->sc_loc_btn[i].pos, info->sc_loc_btn[i].size, info->sc_iid_btn[i]); } } DPRINTF("size=%d, id=%d\n", isize, sc->sc_iid); #endif err = usb_fifo_attach(uaa->device, sc, &sc->sc_mtx, &ums_fifo_methods, &sc->sc_fifo, device_get_unit(dev), -1, uaa->info.bIfaceIndex, UID_ROOT, GID_OPERATOR, 0644); if (err) goto detach; SYSCTL_ADD_PROC(device_get_sysctl_ctx(dev), SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "parseinfo", CTLTYPE_STRING|CTLFLAG_RD, sc, 0, ums_sysctl_handler_parseinfo, "", "Dump of parsed HID report descriptor"); return (0); detach: if (d_ptr) { free(d_ptr, M_TEMP); } ums_detach(dev); return (ENOMEM); } static int ums_detach(device_t self) { struct ums_softc *sc = device_get_softc(self); DPRINTF("sc=%p\n", sc); usb_fifo_detach(&sc->sc_fifo); usbd_transfer_unsetup(sc->sc_xfer, UMS_N_TRANSFER); usb_callout_drain(&sc->sc_callout); mtx_destroy(&sc->sc_mtx); return (0); } static void ums_start_read(struct usb_fifo *fifo) { struct ums_softc *sc = usb_fifo_softc(fifo); int rate; /* Check if we should override the default polling interval */ rate = sc->sc_pollrate; /* Range check rate */ if (rate > 1000) rate = 1000; /* Check for set rate */ if ((rate > 0) && (sc->sc_xfer[UMS_INTR_DT] != NULL)) { DPRINTF("Setting pollrate = %d\n", rate); /* Stop current transfer, if any */ usbd_transfer_stop(sc->sc_xfer[UMS_INTR_DT]); /* Set new interval */ usbd_xfer_set_interval(sc->sc_xfer[UMS_INTR_DT], 1000 / rate); /* Only set pollrate once */ sc->sc_pollrate = 0; } usbd_transfer_start(sc->sc_xfer[UMS_INTR_DT]); } static void ums_stop_read(struct usb_fifo *fifo) { struct ums_softc *sc = usb_fifo_softc(fifo); usbd_transfer_stop(sc->sc_xfer[UMS_INTR_DT]); usb_callout_stop(&sc->sc_callout); } #if ((MOUSE_SYS_PACKETSIZE != 8) || \ (MOUSE_MSC_PACKETSIZE != 5)) #error "Software assumptions are not met. Please update code." #endif static void ums_put_queue(struct ums_softc *sc, int32_t dx, int32_t dy, int32_t dz, int32_t dt, int32_t buttons) { uint8_t buf[8]; if (1) { if (dx > 254) dx = 254; if (dx < -256) dx = -256; if (dy > 254) dy = 254; if (dy < -256) dy = -256; if (dz > 126) dz = 126; if (dz < -128) dz = -128; if (dt > 126) dt = 126; if (dt < -128) dt = -128; buf[0] = sc->sc_mode.syncmask[1]; buf[0] |= (~buttons) & MOUSE_MSC_BUTTONS; buf[1] = dx >> 1; buf[2] = dy >> 1; buf[3] = dx - (dx >> 1); buf[4] = dy - (dy >> 1); if (sc->sc_mode.level == 1) { buf[5] = dz >> 1; buf[6] = dz - (dz >> 1); buf[7] = (((~buttons) >> 3) & MOUSE_SYS_EXTBUTTONS); } usb_fifo_put_data_linear(sc->sc_fifo.fp[USB_FIFO_RX], buf, sc->sc_mode.packetsize, 1); } else { DPRINTF("Buffer full, discarded packet\n"); } } static void ums_reset_buf(struct ums_softc *sc) { /* reset read queue, must be called locked */ usb_fifo_reset(sc->sc_fifo.fp[USB_FIFO_RX]); } static int ums_open(struct usb_fifo *fifo, int fflags) { struct ums_softc *sc = usb_fifo_softc(fifo); DPRINTFN(2, "\n"); /* check for duplicate open, should not happen */ if (sc->sc_fflags & fflags) return (EBUSY); /* check for first open */ if (sc->sc_fflags == 0) { /* reset all USB mouse parameters */ if (sc->sc_buttons > MOUSE_MSC_MAXBUTTON) sc->sc_hw.buttons = MOUSE_MSC_MAXBUTTON; else sc->sc_hw.buttons = sc->sc_buttons; sc->sc_hw.iftype = MOUSE_IF_USB; sc->sc_hw.type = MOUSE_MOUSE; sc->sc_hw.model = MOUSE_MODEL_GENERIC; sc->sc_hw.hwid = 0; sc->sc_mode.protocol = MOUSE_PROTO_MSC; sc->sc_mode.rate = -1; sc->sc_mode.resolution = MOUSE_RES_UNKNOWN; sc->sc_mode.accelfactor = 0; sc->sc_mode.level = 0; sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC; /* reset status */ sc->sc_status.flags = 0; sc->sc_status.button = 0; sc->sc_status.obutton = 0; sc->sc_status.dx = 0; sc->sc_status.dy = 0; sc->sc_status.dz = 0; /* sc->sc_status.dt = 0; */ } if (fflags & FREAD) { /* allocate RX buffer */ if (usb_fifo_alloc_buffer(fifo, UMS_BUF_SIZE, UMS_IFQ_MAXLEN)) { return (ENOMEM); } } sc->sc_fflags |= fflags & (FREAD | FWRITE); return (0); } static void ums_close(struct usb_fifo *fifo, int fflags) { struct ums_softc *sc = usb_fifo_softc(fifo); DPRINTFN(2, "\n"); if (fflags & FREAD) usb_fifo_free_buffer(fifo); sc->sc_fflags &= ~(fflags & (FREAD | FWRITE)); } static int ums_ioctl(struct usb_fifo *fifo, u_long cmd, void *addr, int fflags) { struct ums_softc *sc = usb_fifo_softc(fifo); mousemode_t mode; int error = 0; DPRINTFN(2, "\n"); mtx_lock(&sc->sc_mtx); switch (cmd) { case MOUSE_GETHWINFO: *(mousehw_t *)addr = sc->sc_hw; break; case MOUSE_GETMODE: *(mousemode_t *)addr = sc->sc_mode; break; case MOUSE_SETMODE: mode = *(mousemode_t *)addr; if (mode.level == -1) { /* don't change the current setting */ } else if ((mode.level < 0) || (mode.level > 1)) { error = EINVAL; break; } else { sc->sc_mode.level = mode.level; } /* store polling rate */ sc->sc_pollrate = mode.rate; if (sc->sc_mode.level == 0) { if (sc->sc_buttons > MOUSE_MSC_MAXBUTTON) sc->sc_hw.buttons = MOUSE_MSC_MAXBUTTON; else sc->sc_hw.buttons = sc->sc_buttons; sc->sc_mode.protocol = MOUSE_PROTO_MSC; sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC; } else if (sc->sc_mode.level == 1) { if (sc->sc_buttons > MOUSE_SYS_MAXBUTTON) sc->sc_hw.buttons = MOUSE_SYS_MAXBUTTON; else sc->sc_hw.buttons = sc->sc_buttons; sc->sc_mode.protocol = MOUSE_PROTO_SYSMOUSE; sc->sc_mode.packetsize = MOUSE_SYS_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_SYS_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_SYS_SYNC; } ums_reset_buf(sc); break; case MOUSE_GETLEVEL: *(int *)addr = sc->sc_mode.level; break; case MOUSE_SETLEVEL: if (*(int *)addr < 0 || *(int *)addr > 1) { error = EINVAL; break; } sc->sc_mode.level = *(int *)addr; if (sc->sc_mode.level == 0) { if (sc->sc_buttons > MOUSE_MSC_MAXBUTTON) sc->sc_hw.buttons = MOUSE_MSC_MAXBUTTON; else sc->sc_hw.buttons = sc->sc_buttons; sc->sc_mode.protocol = MOUSE_PROTO_MSC; sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC; } else if (sc->sc_mode.level == 1) { if (sc->sc_buttons > MOUSE_SYS_MAXBUTTON) sc->sc_hw.buttons = MOUSE_SYS_MAXBUTTON; else sc->sc_hw.buttons = sc->sc_buttons; sc->sc_mode.protocol = MOUSE_PROTO_SYSMOUSE; sc->sc_mode.packetsize = MOUSE_SYS_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_SYS_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_SYS_SYNC; } ums_reset_buf(sc); break; case MOUSE_GETSTATUS:{ mousestatus_t *status = (mousestatus_t *)addr; *status = sc->sc_status; sc->sc_status.obutton = sc->sc_status.button; sc->sc_status.button = 0; sc->sc_status.dx = 0; sc->sc_status.dy = 0; sc->sc_status.dz = 0; /* sc->sc_status.dt = 0; */ if (status->dx || status->dy || status->dz /* || status->dt */ ) { status->flags |= MOUSE_POSCHANGED; } if (status->button != status->obutton) { status->flags |= MOUSE_BUTTONSCHANGED; } break; } default: error = ENOTTY; break; } mtx_unlock(&sc->sc_mtx); return (error); } static int ums_sysctl_handler_parseinfo(SYSCTL_HANDLER_ARGS) { struct ums_softc *sc = arg1; struct ums_info *info; struct sbuf *sb; int i, j, err, had_output; sb = sbuf_new_auto(); for (i = 0, had_output = 0; i < UMS_INFO_MAX; i++) { info = &sc->sc_info[i]; /* Don't emit empty info */ if ((info->sc_flags & (UMS_FLAG_X_AXIS | UMS_FLAG_Y_AXIS | UMS_FLAG_Z_AXIS | UMS_FLAG_T_AXIS | UMS_FLAG_W_AXIS)) == 0 && info->sc_buttons == 0) continue; if (had_output) sbuf_printf(sb, "\n"); had_output = 1; sbuf_printf(sb, "i%d:", i + 1); if (info->sc_flags & UMS_FLAG_X_AXIS) sbuf_printf(sb, " X:r%d, p%d, s%d;", (int)info->sc_iid_x, (int)info->sc_loc_x.pos, (int)info->sc_loc_x.size); if (info->sc_flags & UMS_FLAG_Y_AXIS) sbuf_printf(sb, " Y:r%d, p%d, s%d;", (int)info->sc_iid_y, (int)info->sc_loc_y.pos, (int)info->sc_loc_y.size); if (info->sc_flags & UMS_FLAG_Z_AXIS) sbuf_printf(sb, " Z:r%d, p%d, s%d;", (int)info->sc_iid_z, (int)info->sc_loc_z.pos, (int)info->sc_loc_z.size); if (info->sc_flags & UMS_FLAG_T_AXIS) sbuf_printf(sb, " T:r%d, p%d, s%d;", (int)info->sc_iid_t, (int)info->sc_loc_t.pos, (int)info->sc_loc_t.size); if (info->sc_flags & UMS_FLAG_W_AXIS) sbuf_printf(sb, " W:r%d, p%d, s%d;", (int)info->sc_iid_w, (int)info->sc_loc_w.pos, (int)info->sc_loc_w.size); for (j = 0; j < info->sc_buttons; j++) { sbuf_printf(sb, " B%d:r%d, p%d, s%d;", j + 1, (int)info->sc_iid_btn[j], (int)info->sc_loc_btn[j].pos, (int)info->sc_loc_btn[j].size); } } sbuf_finish(sb); err = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1); sbuf_delete(sb); return (err); } static devclass_t ums_devclass; static device_method_t ums_methods[] = { DEVMETHOD(device_probe, ums_probe), DEVMETHOD(device_attach, ums_attach), DEVMETHOD(device_detach, ums_detach), DEVMETHOD_END }; static driver_t ums_driver = { .name = "ums", .methods = ums_methods, .size = sizeof(struct ums_softc), }; DRIVER_MODULE(ums, uhub, ums_driver, ums_devclass, NULL, 0); MODULE_DEPEND(ums, usb, 1, 1, 1); MODULE_VERSION(ums, 1); Index: head/sys/dev/usb/input/wsp.c =================================================================== --- head/sys/dev/usb/input/wsp.c (revision 276700) +++ head/sys/dev/usb/input/wsp.c (revision 276701) @@ -1,1226 +1,1226 @@ /*- * Copyright (c) 2012 Huang Wen Hui * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR wsp_debug #include #include #define WSP_DRIVER_NAME "wsp" #define WSP_BUFFER_MAX 1024 #define WSP_CLAMP(x,low,high) do { \ if ((x) < (low)) \ (x) = (low); \ else if ((x) > (high)) \ (x) = (high); \ } while (0) /* Tunables */ static SYSCTL_NODE(_hw_usb, OID_AUTO, wsp, CTLFLAG_RW, 0, "USB wsp"); #ifdef USB_DEBUG enum wsp_log_level { WSP_LLEVEL_DISABLED = 0, WSP_LLEVEL_ERROR, WSP_LLEVEL_DEBUG, /* for troubleshooting */ WSP_LLEVEL_INFO, /* for diagnostics */ }; static int wsp_debug = WSP_LLEVEL_ERROR;/* the default is to only log errors */ -SYSCTL_INT(_hw_usb_wsp, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_wsp, OID_AUTO, debug, CTLFLAG_RWTUN, &wsp_debug, WSP_LLEVEL_ERROR, "WSP debug level"); #endif /* USB_DEBUG */ static struct wsp_tuning { int scale_factor; int z_factor; int pressure_touch_threshold; int pressure_untouch_threshold; int pressure_tap_threshold; int scr_hor_threshold; } wsp_tuning = { .scale_factor = 12, .z_factor = 5, .pressure_touch_threshold = 50, .pressure_untouch_threshold = 10, .pressure_tap_threshold = 100, .scr_hor_threshold = 10, }; static void wsp_runing_rangecheck(struct wsp_tuning *ptun) { WSP_CLAMP(ptun->scale_factor, 1, 63); WSP_CLAMP(ptun->z_factor, 1, 63); WSP_CLAMP(ptun->pressure_touch_threshold, 1, 255); WSP_CLAMP(ptun->pressure_untouch_threshold, 1, 255); WSP_CLAMP(ptun->pressure_tap_threshold, 1, 255); WSP_CLAMP(ptun->scr_hor_threshold, 1, 255); } -SYSCTL_INT(_hw_usb_wsp, OID_AUTO, scale_factor, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_wsp, OID_AUTO, scale_factor, CTLFLAG_RWTUN, &wsp_tuning.scale_factor, 0, "movement scale factor"); -SYSCTL_INT(_hw_usb_wsp, OID_AUTO, z_factor, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_wsp, OID_AUTO, z_factor, CTLFLAG_RWTUN, &wsp_tuning.z_factor, 0, "Z-axis scale factor"); -SYSCTL_INT(_hw_usb_wsp, OID_AUTO, pressure_touch_threshold, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_wsp, OID_AUTO, pressure_touch_threshold, CTLFLAG_RWTUN, &wsp_tuning.pressure_touch_threshold, 0, "touch pressure threshold"); -SYSCTL_INT(_hw_usb_wsp, OID_AUTO, pressure_untouch_threshold, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_wsp, OID_AUTO, pressure_untouch_threshold, CTLFLAG_RWTUN, &wsp_tuning.pressure_untouch_threshold, 0, "untouch pressure threshold"); -SYSCTL_INT(_hw_usb_wsp, OID_AUTO, pressure_tap_threshold, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_wsp, OID_AUTO, pressure_tap_threshold, CTLFLAG_RWTUN, &wsp_tuning.pressure_tap_threshold, 0, "tap pressure threshold"); -SYSCTL_INT(_hw_usb_wsp, OID_AUTO, scr_hor_threshold, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_wsp, OID_AUTO, scr_hor_threshold, CTLFLAG_RWTUN, &wsp_tuning.scr_hor_threshold, 0, "horizontal scrolling threshold"); #define WSP_IFACE_INDEX 1 /* * Some tables, structures, definitions and constant values for the * touchpad protocol has been copied from Linux's * "drivers/input/mouse/bcm5974.c" which has the following copyright * holders under GPLv2. All device specific code in this driver has * been written from scratch. The decoding algorithm is based on * output from FreeBSD's usbdump. * * Copyright (C) 2008 Henrik Rydberg (rydberg@euromail.se) * Copyright (C) 2008 Scott Shawcroft (scott.shawcroft@gmail.com) * Copyright (C) 2001-2004 Greg Kroah-Hartman (greg@kroah.com) * Copyright (C) 2005 Johannes Berg (johannes@sipsolutions.net) * Copyright (C) 2005 Stelian Pop (stelian@popies.net) * Copyright (C) 2005 Frank Arnold (frank@scirocco-5v-turbo.de) * Copyright (C) 2005 Peter Osterlund (petero2@telia.com) * Copyright (C) 2005 Michael Hanselmann (linux-kernel@hansmi.ch) * Copyright (C) 2006 Nicolas Boichat (nicolas@boichat.ch) */ /* button data structure */ struct bt_data { uint8_t unknown1; /* constant */ uint8_t button; /* left button */ uint8_t rel_x; /* relative x coordinate */ uint8_t rel_y; /* relative y coordinate */ } __packed; /* trackpad header types */ enum tp_type { TYPE1, /* plain trackpad */ TYPE2, /* button integrated in trackpad */ TYPE3 /* additional header fields since June 2013 */ }; /* trackpad finger data offsets, le16-aligned */ #define FINGER_TYPE1 (13 * 2) #define FINGER_TYPE2 (15 * 2) #define FINGER_TYPE3 (19 * 2) /* trackpad button data offsets */ #define BUTTON_TYPE2 15 #define BUTTON_TYPE3 23 /* list of device capability bits */ #define HAS_INTEGRATED_BUTTON 1 /* trackpad finger header - little endian */ struct tp_header { uint8_t flag; uint8_t sn0; uint16_t wFixed0; uint32_t dwSn1; uint32_t dwFixed1; uint16_t wLength; uint8_t nfinger; uint8_t ibt; int16_t wUnknown[6]; uint8_t q1; uint8_t q2; } __packed; /* trackpad finger structure - little endian */ struct tp_finger { int16_t origin; /* zero when switching track finger */ int16_t abs_x; /* absolute x coodinate */ int16_t abs_y; /* absolute y coodinate */ int16_t rel_x; /* relative x coodinate */ int16_t rel_y; /* relative y coodinate */ int16_t tool_major; /* tool area, major axis */ int16_t tool_minor; /* tool area, minor axis */ int16_t orientation; /* 16384 when point, else 15 bit angle */ int16_t touch_major; /* touch area, major axis */ int16_t touch_minor; /* touch area, minor axis */ int16_t unused[3]; /* zeros */ int16_t multi; /* one finger: varies, more fingers: * constant */ } __packed; /* trackpad finger data size, empirically at least ten fingers */ #define MAX_FINGERS 16 #define SIZEOF_FINGER sizeof(struct tp_finger) #define SIZEOF_ALL_FINGERS (MAX_FINGERS * SIZEOF_FINGER) #if (WSP_BUFFER_MAX < ((MAX_FINGERS * 14 * 2) + FINGER_TYPE3)) #error "WSP_BUFFER_MAX is too small" #endif enum { WSP_FLAG_WELLSPRING1, WSP_FLAG_WELLSPRING2, WSP_FLAG_WELLSPRING3, WSP_FLAG_WELLSPRING4, WSP_FLAG_WELLSPRING4A, WSP_FLAG_WELLSPRING5, WSP_FLAG_WELLSPRING6A, WSP_FLAG_WELLSPRING6, WSP_FLAG_WELLSPRING5A, WSP_FLAG_WELLSPRING7, WSP_FLAG_WELLSPRING7A, WSP_FLAG_WELLSPRING8, WSP_FLAG_MAX, }; /* device-specific configuration */ struct wsp_dev_params { uint8_t caps; /* device capability bitmask */ uint8_t tp_type; /* type of trackpad interface */ uint8_t tp_offset; /* offset to trackpad finger data */ }; static const struct wsp_dev_params wsp_dev_params[WSP_FLAG_MAX] = { [WSP_FLAG_WELLSPRING1] = { .caps = 0, .tp_type = TYPE1, .tp_offset = FINGER_TYPE1, }, [WSP_FLAG_WELLSPRING2] = { .caps = 0, .tp_type = TYPE1, .tp_offset = FINGER_TYPE1, }, [WSP_FLAG_WELLSPRING3] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = TYPE2, .tp_offset = FINGER_TYPE2, }, [WSP_FLAG_WELLSPRING4] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = TYPE2, .tp_offset = FINGER_TYPE2, }, [WSP_FLAG_WELLSPRING4A] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = TYPE2, .tp_offset = FINGER_TYPE2, }, [WSP_FLAG_WELLSPRING5] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = TYPE2, .tp_offset = FINGER_TYPE2, }, [WSP_FLAG_WELLSPRING6] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = TYPE2, .tp_offset = FINGER_TYPE2, }, [WSP_FLAG_WELLSPRING5A] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = TYPE2, .tp_offset = FINGER_TYPE2, }, [WSP_FLAG_WELLSPRING6A] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = TYPE2, .tp_offset = FINGER_TYPE2, }, [WSP_FLAG_WELLSPRING7] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = TYPE2, .tp_offset = FINGER_TYPE2, }, [WSP_FLAG_WELLSPRING7A] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = TYPE2, .tp_offset = FINGER_TYPE2, }, [WSP_FLAG_WELLSPRING8] = { .caps = HAS_INTEGRATED_BUTTON, .tp_type = TYPE3, .tp_offset = FINGER_TYPE3, }, }; #define WSP_DEV(v,p,i) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, i) } static const STRUCT_USB_HOST_ID wsp_devs[] = { /* MacbookAir1.1 */ WSP_DEV(APPLE, WELLSPRING_ANSI, WSP_FLAG_WELLSPRING1), WSP_DEV(APPLE, WELLSPRING_ISO, WSP_FLAG_WELLSPRING1), WSP_DEV(APPLE, WELLSPRING_JIS, WSP_FLAG_WELLSPRING1), /* MacbookProPenryn, aka wellspring2 */ WSP_DEV(APPLE, WELLSPRING2_ANSI, WSP_FLAG_WELLSPRING2), WSP_DEV(APPLE, WELLSPRING2_ISO, WSP_FLAG_WELLSPRING2), WSP_DEV(APPLE, WELLSPRING2_JIS, WSP_FLAG_WELLSPRING2), /* Macbook5,1 (unibody), aka wellspring3 */ WSP_DEV(APPLE, WELLSPRING3_ANSI, WSP_FLAG_WELLSPRING3), WSP_DEV(APPLE, WELLSPRING3_ISO, WSP_FLAG_WELLSPRING3), WSP_DEV(APPLE, WELLSPRING3_JIS, WSP_FLAG_WELLSPRING3), /* MacbookAir3,2 (unibody), aka wellspring4 */ WSP_DEV(APPLE, WELLSPRING4_ANSI, WSP_FLAG_WELLSPRING4), WSP_DEV(APPLE, WELLSPRING4_ISO, WSP_FLAG_WELLSPRING4), WSP_DEV(APPLE, WELLSPRING4_JIS, WSP_FLAG_WELLSPRING4), /* MacbookAir3,1 (unibody), aka wellspring4 */ WSP_DEV(APPLE, WELLSPRING4A_ANSI, WSP_FLAG_WELLSPRING4A), WSP_DEV(APPLE, WELLSPRING4A_ISO, WSP_FLAG_WELLSPRING4A), WSP_DEV(APPLE, WELLSPRING4A_JIS, WSP_FLAG_WELLSPRING4A), /* Macbook8 (unibody, March 2011) */ WSP_DEV(APPLE, WELLSPRING5_ANSI, WSP_FLAG_WELLSPRING5), WSP_DEV(APPLE, WELLSPRING5_ISO, WSP_FLAG_WELLSPRING5), WSP_DEV(APPLE, WELLSPRING5_JIS, WSP_FLAG_WELLSPRING5), /* MacbookAir4,1 (unibody, July 2011) */ WSP_DEV(APPLE, WELLSPRING6A_ANSI, WSP_FLAG_WELLSPRING6A), WSP_DEV(APPLE, WELLSPRING6A_ISO, WSP_FLAG_WELLSPRING6A), WSP_DEV(APPLE, WELLSPRING6A_JIS, WSP_FLAG_WELLSPRING6A), /* MacbookAir4,2 (unibody, July 2011) */ WSP_DEV(APPLE, WELLSPRING6_ANSI, WSP_FLAG_WELLSPRING6), WSP_DEV(APPLE, WELLSPRING6_ISO, WSP_FLAG_WELLSPRING6), WSP_DEV(APPLE, WELLSPRING6_JIS, WSP_FLAG_WELLSPRING6), /* Macbook8,2 (unibody) */ WSP_DEV(APPLE, WELLSPRING5A_ANSI, WSP_FLAG_WELLSPRING5A), WSP_DEV(APPLE, WELLSPRING5A_ISO, WSP_FLAG_WELLSPRING5A), WSP_DEV(APPLE, WELLSPRING5A_JIS, WSP_FLAG_WELLSPRING5A), /* MacbookPro10,1 (unibody, June 2012) */ /* MacbookPro11,? (unibody, June 2013) */ WSP_DEV(APPLE, WELLSPRING7_ANSI, WSP_FLAG_WELLSPRING7), WSP_DEV(APPLE, WELLSPRING7_ISO, WSP_FLAG_WELLSPRING7), WSP_DEV(APPLE, WELLSPRING7_JIS, WSP_FLAG_WELLSPRING7), /* MacbookPro10,2 (unibody, October 2012) */ WSP_DEV(APPLE, WELLSPRING7A_ANSI, WSP_FLAG_WELLSPRING7A), WSP_DEV(APPLE, WELLSPRING7A_ISO, WSP_FLAG_WELLSPRING7A), WSP_DEV(APPLE, WELLSPRING7A_JIS, WSP_FLAG_WELLSPRING7A), /* MacbookAir6,2 (unibody, June 2013) */ WSP_DEV(APPLE, WELLSPRING8_ANSI, WSP_FLAG_WELLSPRING8), WSP_DEV(APPLE, WELLSPRING8_ISO, WSP_FLAG_WELLSPRING8), WSP_DEV(APPLE, WELLSPRING8_JIS, WSP_FLAG_WELLSPRING8), }; #define WSP_FIFO_BUF_SIZE 8 /* bytes */ #define WSP_FIFO_QUEUE_MAXLEN 50 /* units */ enum { WSP_INTR_DT, WSP_N_TRANSFER, }; struct wsp_softc { struct usb_device *sc_usb_device; struct mtx sc_mutex; /* for synchronization */ struct usb_xfer *sc_xfer[WSP_N_TRANSFER]; struct usb_fifo_sc sc_fifo; const struct wsp_dev_params *sc_params; /* device configuration */ mousehw_t sc_hw; mousemode_t sc_mode; u_int sc_pollrate; mousestatus_t sc_status; u_int sc_state; #define WSP_ENABLED 0x01 struct tp_finger *index[MAX_FINGERS]; /* finger index data */ int16_t pos_x[MAX_FINGERS]; /* position array */ int16_t pos_y[MAX_FINGERS]; /* position array */ u_int sc_touch; /* touch status */ #define WSP_UNTOUCH 0x00 #define WSP_FIRST_TOUCH 0x01 #define WSP_SECOND_TOUCH 0x02 #define WSP_TOUCHING 0x04 int16_t pre_pos_x; /* previous position array */ int16_t pre_pos_y; /* previous position array */ int dx_sum; /* x axis cumulative movement */ int dy_sum; /* y axis cumulative movement */ int dz_sum; /* z axis cumulative movement */ int dz_count; #define WSP_DZ_MAX_COUNT 32 int dt_sum; /* T-axis cumulative movement */ int rdx; /* x axis remainder of divide by scale_factor */ int rdy; /* y axis remainder of divide by scale_factor */ int rdz; /* z axis remainder of divide by scale_factor */ int tp_datalen; uint8_t o_ntouch; /* old touch finger status */ uint8_t finger; /* 0 or 1 *, check which finger moving */ uint16_t intr_count; #define WSP_TAP_THRESHOLD 3 #define WSP_TAP_MAX_COUNT 20 int distance; /* the distance of 2 fingers */ #define MAX_DISTANCE 2500 /* the max allowed distance */ uint8_t ibtn; /* button status in tapping */ uint8_t ntaps; /* finger status in tapping */ uint8_t scr_mode; /* scroll status in movement */ #define WSP_SCR_NONE 0 #define WSP_SCR_VER 1 #define WSP_SCR_HOR 2 uint8_t tp_data[WSP_BUFFER_MAX] __aligned(4); /* trackpad transferred data */ }; typedef enum interface_mode { RAW_SENSOR_MODE = 0x01, HID_MODE = 0x08 } interface_mode; /* * function prototypes */ static usb_fifo_cmd_t wsp_start_read; static usb_fifo_cmd_t wsp_stop_read; static usb_fifo_open_t wsp_open; static usb_fifo_close_t wsp_close; static usb_fifo_ioctl_t wsp_ioctl; static struct usb_fifo_methods wsp_fifo_methods = { .f_open = &wsp_open, .f_close = &wsp_close, .f_ioctl = &wsp_ioctl, .f_start_read = &wsp_start_read, .f_stop_read = &wsp_stop_read, .basename[0] = WSP_DRIVER_NAME, }; /* device initialization and shutdown */ static int wsp_enable(struct wsp_softc *sc); static void wsp_disable(struct wsp_softc *sc); /* updating fifo */ static void wsp_reset_buf(struct wsp_softc *sc); static void wsp_add_to_queue(struct wsp_softc *, int, int, int, uint32_t); /* Device methods. */ static device_probe_t wsp_probe; static device_attach_t wsp_attach; static device_detach_t wsp_detach; static usb_callback_t wsp_intr_callback; static const struct usb_config wsp_config[WSP_N_TRANSFER] = { [WSP_INTR_DT] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = { .pipe_bof = 0, .short_xfer_ok = 1, }, .bufsize = WSP_BUFFER_MAX, .callback = &wsp_intr_callback, }, }; static usb_error_t wsp_set_device_mode(struct wsp_softc *sc, interface_mode mode) { uint8_t mode_bytes[8]; usb_error_t err; err = usbd_req_get_report(sc->sc_usb_device, NULL, mode_bytes, sizeof(mode_bytes), 0, 0x03, 0x00); if (err != USB_ERR_NORMAL_COMPLETION) { DPRINTF("Failed to read device mode (%d)\n", err); return (err); } /* * XXX Need to wait at least 250ms for hardware to get * ready. The device mode handling appears to be handled * asynchronously and we should not issue these commands too * quickly. */ pause("WHW", hz / 4); mode_bytes[0] = mode; return (usbd_req_set_report(sc->sc_usb_device, NULL, mode_bytes, sizeof(mode_bytes), 0, 0x03, 0x00)); } static int wsp_enable(struct wsp_softc *sc) { /* reset status */ memset(&sc->sc_status, 0, sizeof(sc->sc_status)); sc->sc_state |= WSP_ENABLED; DPRINTFN(WSP_LLEVEL_INFO, "enabled wsp\n"); return (0); } static void wsp_disable(struct wsp_softc *sc) { sc->sc_state &= ~WSP_ENABLED; DPRINTFN(WSP_LLEVEL_INFO, "disabled wsp\n"); } static int wsp_probe(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bIfaceIndex != WSP_IFACE_INDEX) return (ENXIO); if ((uaa->info.bInterfaceClass != UICLASS_HID) || (uaa->info.bInterfaceProtocol != 0)) return (ENXIO); return (usbd_lookup_id_by_uaa(wsp_devs, sizeof(wsp_devs), uaa)); } static int wsp_attach(device_t dev) { struct wsp_softc *sc = device_get_softc(dev); struct usb_attach_arg *uaa = device_get_ivars(dev); usb_error_t err; void *d_ptr = NULL; uint16_t d_len; DPRINTFN(WSP_LLEVEL_INFO, "sc=%p\n", sc); /* Get HID descriptor */ err = usbd_req_get_hid_desc(uaa->device, NULL, &d_ptr, &d_len, M_TEMP, uaa->info.bIfaceIndex); if (err == USB_ERR_NORMAL_COMPLETION) { /* Get HID report descriptor length */ sc->tp_datalen = hid_report_size(d_ptr, d_len, hid_input, NULL); free(d_ptr, M_TEMP); if (sc->tp_datalen <= 0 || sc->tp_datalen > WSP_BUFFER_MAX) { DPRINTF("Invalid datalength or too big " "datalength: %d\n", sc->tp_datalen); return (ENXIO); } } else { return (ENXIO); } sc->sc_usb_device = uaa->device; /* * By default the touchpad behaves like a HID device, sending * packets with reportID = 8. Such reports contain only * limited information. They encode movement deltas and button * events, but do not include data from the pressure * sensors. The device input mode can be switched from HID * reports to raw sensor data using vendor-specific USB * control commands: */ /* * During re-enumeration of the device we need to force the * device back into HID mode before switching it to RAW * mode. Else the device does not work like expected. */ err = wsp_set_device_mode(sc, HID_MODE); if (err != USB_ERR_NORMAL_COMPLETION) { DPRINTF("Failed to set mode to HID MODE (%d)\n", err); return (ENXIO); } err = wsp_set_device_mode(sc, RAW_SENSOR_MODE); if (err != USB_ERR_NORMAL_COMPLETION) { DPRINTF("failed to set mode to RAW MODE (%d)\n", err); return (ENXIO); } mtx_init(&sc->sc_mutex, "wspmtx", NULL, MTX_DEF | MTX_RECURSE); /* get device specific configuration */ sc->sc_params = wsp_dev_params + USB_GET_DRIVER_INFO(uaa); err = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex, sc->sc_xfer, wsp_config, WSP_N_TRANSFER, sc, &sc->sc_mutex); if (err) { DPRINTF("error=%s\n", usbd_errstr(err)); goto detach; } if (usb_fifo_attach(sc->sc_usb_device, sc, &sc->sc_mutex, &wsp_fifo_methods, &sc->sc_fifo, device_get_unit(dev), -1, uaa->info.bIfaceIndex, UID_ROOT, GID_OPERATOR, 0644)) { goto detach; } device_set_usb_desc(dev); sc->sc_hw.buttons = 3; sc->sc_hw.iftype = MOUSE_IF_USB; sc->sc_hw.type = MOUSE_PAD; sc->sc_hw.model = MOUSE_MODEL_GENERIC; sc->sc_mode.protocol = MOUSE_PROTO_MSC; sc->sc_mode.rate = -1; sc->sc_mode.resolution = MOUSE_RES_UNKNOWN; sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC; sc->sc_touch = WSP_UNTOUCH; sc->scr_mode = WSP_SCR_NONE; return (0); detach: wsp_detach(dev); return (ENOMEM); } static int wsp_detach(device_t dev) { struct wsp_softc *sc = device_get_softc(dev); (void) wsp_set_device_mode(sc, HID_MODE); mtx_lock(&sc->sc_mutex); if (sc->sc_state & WSP_ENABLED) wsp_disable(sc); mtx_unlock(&sc->sc_mutex); usb_fifo_detach(&sc->sc_fifo); usbd_transfer_unsetup(sc->sc_xfer, WSP_N_TRANSFER); mtx_destroy(&sc->sc_mutex); return (0); } static void wsp_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct wsp_softc *sc = usbd_xfer_softc(xfer); const struct wsp_dev_params *params = sc->sc_params; struct usb_page_cache *pc; struct tp_finger *f; struct tp_header *h; struct wsp_tuning tun = wsp_tuning; int ntouch = 0; /* the finger number in touch */ int ibt = 0; /* button status */ int dx = 0; int dy = 0; int dz = 0; int rdx = 0; int rdy = 0; int rdz = 0; int len; int i; wsp_runing_rangecheck(&tun); if (sc->dz_count == 0) sc->dz_count = WSP_DZ_MAX_COUNT; usbd_xfer_status(xfer, &len, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: /* copy out received data */ pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, sc->tp_data, len); if (len < sc->tp_datalen) { /* make sure we don't process old data */ memset(sc->tp_data + len, 0, sc->tp_datalen - len); } h = (struct tp_header *)(sc->tp_data); if (params->tp_type == TYPE2) { ibt = sc->tp_data[BUTTON_TYPE2]; ntouch = sc->tp_data[BUTTON_TYPE2 - 1]; } else if (params->tp_type == TYPE3) { ibt = sc->tp_data[BUTTON_TYPE3]; ntouch = sc->tp_data[BUTTON_TYPE3 - 1]; } /* range check */ if (ntouch < 0) ntouch = 0; else if (ntouch > MAX_FINGERS) ntouch = MAX_FINGERS; f = (struct tp_finger *)(sc->tp_data + params->tp_offset); for (i = 0; i != ntouch; i++) { /* swap endianness, if any */ if (le16toh(0x1234) != 0x1234) { f[i].origin = le16toh((uint16_t)f[i].origin); f[i].abs_x = le16toh((uint16_t)f[i].abs_x); f[i].abs_y = le16toh((uint16_t)f[i].abs_y); f[i].rel_x = le16toh((uint16_t)f[i].rel_x); f[i].rel_y = le16toh((uint16_t)f[i].rel_y); f[i].tool_major = le16toh((uint16_t)f[i].tool_major); f[i].tool_minor = le16toh((uint16_t)f[i].tool_minor); f[i].orientation = le16toh((uint16_t)f[i].orientation); f[i].touch_major = le16toh((uint16_t)f[i].touch_major); f[i].touch_minor = le16toh((uint16_t)f[i].touch_minor); f[i].multi = le16toh((uint16_t)f[i].multi); } DPRINTFN(WSP_LLEVEL_INFO, "[%d]ibt=%d, taps=%d, u=%x, o=%4d, ax=%5d, ay=%5d, " "rx=%5d, ry=%5d, tlmaj=%4d, tlmin=%4d, ot=%5d, tchmaj=%4d, tchmin=%4d, m=%4x\n", i, ibt, ntouch, h->q2, f[i].origin, f[i].abs_x, f[i].abs_y, f[i].rel_x, f[i].rel_y, f[i].tool_major, f[i].tool_minor, f[i].orientation, f[i].touch_major, f[i].touch_minor, f[i].multi); sc->pos_x[i] = f[i].abs_x; sc->pos_y[i] = -f[i].abs_y; sc->index[i] = &f[i]; } sc->sc_status.flags &= ~MOUSE_POSCHANGED; sc->sc_status.flags &= ~MOUSE_STDBUTTONSCHANGED; sc->sc_status.obutton = sc->sc_status.button; sc->sc_status.button = 0; if (ibt != 0) { sc->sc_status.button |= MOUSE_BUTTON1DOWN; sc->ibtn = 1; } if (h->q2 == 4) sc->intr_count++; if (sc->ntaps < ntouch) { switch (ntouch) { case 1: if (f[0].touch_major > tun.pressure_tap_threshold) sc->ntaps = 1; break; case 2: if (f[0].touch_major > tun.pressure_tap_threshold && f[1].touch_major > tun.pressure_tap_threshold) sc->ntaps = 2; break; case 3: if (f[0].touch_major > tun.pressure_tap_threshold && f[1].touch_major > tun.pressure_tap_threshold && f[2].touch_major > tun.pressure_tap_threshold) sc->ntaps = 3; break; default: break; } } if (ntouch == 2) { sc->distance = max(sc->distance, max( abs(sc->pos_x[0] - sc->pos_x[1]), abs(sc->pos_y[0] - sc->pos_y[1]))); } if (f[0].touch_major < tun.pressure_untouch_threshold && sc->sc_status.button == 0) { sc->sc_touch = WSP_UNTOUCH; if (sc->intr_count < WSP_TAP_MAX_COUNT && sc->intr_count > WSP_TAP_THRESHOLD && sc->ntaps && sc->ibtn == 0) { /* * Add a pair of events (button-down and * button-up). */ switch (sc->ntaps) { case 1: if (!(params->caps & HAS_INTEGRATED_BUTTON)) { wsp_add_to_queue(sc, 0, 0, 0, MOUSE_BUTTON1DOWN); DPRINTFN(WSP_LLEVEL_INFO, "LEFT CLICK!\n"); } break; case 2: DPRINTFN(WSP_LLEVEL_INFO, "sum_x=%5d, sum_y=%5d\n", sc->dx_sum, sc->dy_sum); if (sc->distance < MAX_DISTANCE && abs(sc->dx_sum) < 5 && abs(sc->dy_sum) < 5) { wsp_add_to_queue(sc, 0, 0, 0, MOUSE_BUTTON3DOWN); DPRINTFN(WSP_LLEVEL_INFO, "RIGHT CLICK!\n"); } break; case 3: wsp_add_to_queue(sc, 0, 0, 0, MOUSE_BUTTON2DOWN); break; default: /* we don't handle taps of more than three fingers */ break; } wsp_add_to_queue(sc, 0, 0, 0, 0); /* button release */ } if ((sc->dt_sum / tun.scr_hor_threshold) != 0 && sc->ntaps == 2 && sc->scr_mode == WSP_SCR_HOR) { /* * translate T-axis into button presses * until further */ if (sc->dt_sum > 0) wsp_add_to_queue(sc, 0, 0, 0, 1UL << 3); else if (sc->dt_sum < 0) wsp_add_to_queue(sc, 0, 0, 0, 1UL << 4); } sc->dz_count = WSP_DZ_MAX_COUNT; sc->dz_sum = 0; sc->intr_count = 0; sc->ibtn = 0; sc->ntaps = 0; sc->finger = 0; sc->distance = 0; sc->dt_sum = 0; sc->dx_sum = 0; sc->dy_sum = 0; sc->rdx = 0; sc->rdy = 0; sc->rdz = 0; sc->scr_mode = WSP_SCR_NONE; } else if (f[0].touch_major >= tun.pressure_touch_threshold && sc->sc_touch == WSP_UNTOUCH) { /* ignore first touch */ sc->sc_touch = WSP_FIRST_TOUCH; } else if (f[0].touch_major >= tun.pressure_touch_threshold && sc->sc_touch == WSP_FIRST_TOUCH) { /* ignore second touch */ sc->sc_touch = WSP_SECOND_TOUCH; DPRINTFN(WSP_LLEVEL_INFO, "Fist pre_x=%5d, pre_y=%5d\n", sc->pre_pos_x, sc->pre_pos_y); } else { if (sc->sc_touch == WSP_SECOND_TOUCH) sc->sc_touch = WSP_TOUCHING; if (ntouch != 0 && h->q2 == 4 && f[0].touch_major >= tun.pressure_touch_threshold) { dx = sc->pos_x[0] - sc->pre_pos_x; dy = sc->pos_y[0] - sc->pre_pos_y; /* Ignore movement from ibt=1 to ibt=0 */ if (sc->sc_status.obutton != 0 && sc->sc_status.button == 0) { dx = 0; dy = 0; } /* Ignore movement if ntouch changed */ if (sc->o_ntouch != ntouch) { dx = 0; dy = 0; } if (ntouch == 2 && sc->sc_status.button != 0) { dx = sc->pos_x[sc->finger] - sc->pre_pos_x; dy = sc->pos_y[sc->finger] - sc->pre_pos_y; /* * Ignore movement of switch finger or * movement from ibt=0 to ibt=1 */ if (f[0].origin == 0 || f[1].origin == 0 || sc->sc_status.obutton != sc->sc_status.button) { dx = 0; dy = 0; sc->finger = 0; } if ((abs(f[0].rel_x) + abs(f[0].rel_y)) < (abs(f[1].rel_x) + abs(f[1].rel_y)) && sc->finger == 0) { sc->sc_touch = WSP_SECOND_TOUCH; dx = 0; dy = 0; sc->finger = 1; } if ((abs(f[0].rel_x) + abs(f[0].rel_y)) >= (abs(f[1].rel_x) + abs(f[1].rel_y)) && sc->finger == 1) { sc->sc_touch = WSP_SECOND_TOUCH; dx = 0; dy = 0; sc->finger = 0; } DPRINTFN(WSP_LLEVEL_INFO, "dx=%5d, dy=%5d, mov=%5d\n", dx, dy, sc->finger); } if (sc->dz_count--) { rdz = (dy + sc->rdz) % tun.scale_factor; sc->dz_sum -= (dy + sc->rdz) / tun.scale_factor; sc->rdz = rdz; } if ((sc->dz_sum / tun.z_factor) != 0) sc->dz_count = 0; } rdx = (dx + sc->rdx) % tun.scale_factor; dx = (dx + sc->rdx) / tun.scale_factor; sc->rdx = rdx; rdy = (dy + sc->rdy) % tun.scale_factor; dy = (dy + sc->rdy) / tun.scale_factor; sc->rdy = rdy; sc->dx_sum += dx; sc->dy_sum += dy; if (ntouch == 2 && sc->sc_status.button == 0) { if (sc->scr_mode == WSP_SCR_NONE && abs(sc->dx_sum) + abs(sc->dy_sum) > tun.scr_hor_threshold) sc->scr_mode = abs(sc->dx_sum) > abs(sc->dy_sum) * 3 ? WSP_SCR_HOR : WSP_SCR_VER; DPRINTFN(WSP_LLEVEL_INFO, "scr_mode=%5d, count=%d, dx_sum=%d, dy_sum=%d\n", sc->scr_mode, sc->intr_count, sc->dx_sum, sc->dy_sum); if (sc->scr_mode == WSP_SCR_HOR) sc->dt_sum += dx; else sc->dt_sum = 0; dx = 0; dy = 0; if (sc->dz_count == 0) dz = sc->dz_sum / tun.z_factor; if (sc->scr_mode == WSP_SCR_HOR || abs(sc->pos_x[0] - sc->pos_x[1]) > MAX_DISTANCE || abs(sc->pos_y[0] - sc->pos_y[1]) > MAX_DISTANCE) dz = 0; } if (ntouch == 3) { dx = 0; dy = 0; dz = 0; } if (sc->intr_count < WSP_TAP_MAX_COUNT && abs(dx) < 3 && abs(dy) < 3 && abs(dz) < 3) { dx = dy = dz = 0; } else sc->intr_count = WSP_TAP_MAX_COUNT; if (dx || dy || dz) sc->sc_status.flags |= MOUSE_POSCHANGED; DPRINTFN(WSP_LLEVEL_INFO, "dx=%5d, dy=%5d, dz=%5d, sc_touch=%x, btn=%x\n", dx, dy, dz, sc->sc_touch, sc->sc_status.button); sc->sc_status.dx += dx; sc->sc_status.dy += dy; sc->sc_status.dz += dz; wsp_add_to_queue(sc, dx, -dy, dz, sc->sc_status.button); if (sc->dz_count == 0) { sc->dz_sum = 0; sc->rdz = 0; } } sc->pre_pos_x = sc->pos_x[0]; sc->pre_pos_y = sc->pos_y[0]; if (ntouch == 2 && sc->sc_status.button != 0) { sc->pre_pos_x = sc->pos_x[sc->finger]; sc->pre_pos_y = sc->pos_y[sc->finger]; } sc->o_ntouch = ntouch; case USB_ST_SETUP: tr_setup: /* check if we can put more data into the FIFO */ if (usb_fifo_put_bytes_max( sc->sc_fifo.fp[USB_FIFO_RX]) != 0) { usbd_xfer_set_frame_len(xfer, 0, sc->tp_datalen); usbd_transfer_submit(xfer); } break; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void wsp_add_to_queue(struct wsp_softc *sc, int dx, int dy, int dz, uint32_t buttons_in) { uint32_t buttons_out; uint8_t buf[8]; dx = imin(dx, 254); dx = imax(dx, -256); dy = imin(dy, 254); dy = imax(dy, -256); dz = imin(dz, 126); dz = imax(dz, -128); buttons_out = MOUSE_MSC_BUTTONS; if (buttons_in & MOUSE_BUTTON1DOWN) buttons_out &= ~MOUSE_MSC_BUTTON1UP; else if (buttons_in & MOUSE_BUTTON2DOWN) buttons_out &= ~MOUSE_MSC_BUTTON2UP; else if (buttons_in & MOUSE_BUTTON3DOWN) buttons_out &= ~MOUSE_MSC_BUTTON3UP; /* Encode the mouse data in standard format; refer to mouse(4) */ buf[0] = sc->sc_mode.syncmask[1]; buf[0] |= buttons_out; buf[1] = dx >> 1; buf[2] = dy >> 1; buf[3] = dx - (dx >> 1); buf[4] = dy - (dy >> 1); /* Encode extra bytes for level 1 */ if (sc->sc_mode.level == 1) { buf[5] = dz >> 1; /* dz / 2 */ buf[6] = dz - (dz >> 1);/* dz - (dz / 2) */ buf[7] = (((~buttons_in) >> 3) & MOUSE_SYS_EXTBUTTONS); } usb_fifo_put_data_linear(sc->sc_fifo.fp[USB_FIFO_RX], buf, sc->sc_mode.packetsize, 1); } static void wsp_reset_buf(struct wsp_softc *sc) { /* reset read queue */ usb_fifo_reset(sc->sc_fifo.fp[USB_FIFO_RX]); } static void wsp_start_read(struct usb_fifo *fifo) { struct wsp_softc *sc = usb_fifo_softc(fifo); int rate; /* Check if we should override the default polling interval */ rate = sc->sc_pollrate; /* Range check rate */ if (rate > 1000) rate = 1000; /* Check for set rate */ if ((rate > 0) && (sc->sc_xfer[WSP_INTR_DT] != NULL)) { /* Stop current transfer, if any */ usbd_transfer_stop(sc->sc_xfer[WSP_INTR_DT]); /* Set new interval */ usbd_xfer_set_interval(sc->sc_xfer[WSP_INTR_DT], 1000 / rate); /* Only set pollrate once */ sc->sc_pollrate = 0; } usbd_transfer_start(sc->sc_xfer[WSP_INTR_DT]); } static void wsp_stop_read(struct usb_fifo *fifo) { struct wsp_softc *sc = usb_fifo_softc(fifo); usbd_transfer_stop(sc->sc_xfer[WSP_INTR_DT]); } static int wsp_open(struct usb_fifo *fifo, int fflags) { DPRINTFN(WSP_LLEVEL_INFO, "\n"); if (fflags & FREAD) { struct wsp_softc *sc = usb_fifo_softc(fifo); int rc; if (sc->sc_state & WSP_ENABLED) return (EBUSY); if (usb_fifo_alloc_buffer(fifo, WSP_FIFO_BUF_SIZE, WSP_FIFO_QUEUE_MAXLEN)) { return (ENOMEM); } rc = wsp_enable(sc); if (rc != 0) { usb_fifo_free_buffer(fifo); return (rc); } } return (0); } static void wsp_close(struct usb_fifo *fifo, int fflags) { if (fflags & FREAD) { struct wsp_softc *sc = usb_fifo_softc(fifo); wsp_disable(sc); usb_fifo_free_buffer(fifo); } } int wsp_ioctl(struct usb_fifo *fifo, u_long cmd, void *addr, int fflags) { struct wsp_softc *sc = usb_fifo_softc(fifo); mousemode_t mode; int error = 0; mtx_lock(&sc->sc_mutex); switch (cmd) { case MOUSE_GETHWINFO: *(mousehw_t *)addr = sc->sc_hw; break; case MOUSE_GETMODE: *(mousemode_t *)addr = sc->sc_mode; break; case MOUSE_SETMODE: mode = *(mousemode_t *)addr; if (mode.level == -1) /* Don't change the current setting */ ; else if ((mode.level < 0) || (mode.level > 1)) { error = EINVAL; goto done; } sc->sc_mode.level = mode.level; sc->sc_pollrate = mode.rate; sc->sc_hw.buttons = 3; if (sc->sc_mode.level == 0) { sc->sc_mode.protocol = MOUSE_PROTO_MSC; sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC; } else if (sc->sc_mode.level == 1) { sc->sc_mode.protocol = MOUSE_PROTO_SYSMOUSE; sc->sc_mode.packetsize = MOUSE_SYS_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_SYS_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_SYS_SYNC; } wsp_reset_buf(sc); break; case MOUSE_GETLEVEL: *(int *)addr = sc->sc_mode.level; break; case MOUSE_SETLEVEL: if (*(int *)addr < 0 || *(int *)addr > 1) { error = EINVAL; goto done; } sc->sc_mode.level = *(int *)addr; sc->sc_hw.buttons = 3; if (sc->sc_mode.level == 0) { sc->sc_mode.protocol = MOUSE_PROTO_MSC; sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC; } else if (sc->sc_mode.level == 1) { sc->sc_mode.protocol = MOUSE_PROTO_SYSMOUSE; sc->sc_mode.packetsize = MOUSE_SYS_PACKETSIZE; sc->sc_mode.syncmask[0] = MOUSE_SYS_SYNCMASK; sc->sc_mode.syncmask[1] = MOUSE_SYS_SYNC; } wsp_reset_buf(sc); break; case MOUSE_GETSTATUS:{ mousestatus_t *status = (mousestatus_t *)addr; *status = sc->sc_status; sc->sc_status.obutton = sc->sc_status.button; sc->sc_status.button = 0; sc->sc_status.dx = 0; sc->sc_status.dy = 0; sc->sc_status.dz = 0; if (status->dx || status->dy || status->dz) status->flags |= MOUSE_POSCHANGED; if (status->button != status->obutton) status->flags |= MOUSE_BUTTONSCHANGED; break; } default: error = ENOTTY; } done: mtx_unlock(&sc->sc_mutex); return (error); } static device_method_t wsp_methods[] = { /* Device interface */ DEVMETHOD(device_probe, wsp_probe), DEVMETHOD(device_attach, wsp_attach), DEVMETHOD(device_detach, wsp_detach), DEVMETHOD_END }; static driver_t wsp_driver = { .name = WSP_DRIVER_NAME, .methods = wsp_methods, .size = sizeof(struct wsp_softc) }; static devclass_t wsp_devclass; DRIVER_MODULE(wsp, uhub, wsp_driver, wsp_devclass, NULL, 0); MODULE_DEPEND(wsp, usb, 1, 1, 1); MODULE_VERSION(wsp, 1); Index: head/sys/dev/usb/misc/udbp.c =================================================================== --- head/sys/dev/usb/misc/udbp.c (revision 276700) +++ head/sys/dev/usb/misc/udbp.c (revision 276701) @@ -1,859 +1,859 @@ /*- * Copyright (c) 1996-2000 Whistle Communications, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of author nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY NICK HIBMA AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include __FBSDID("$FreeBSD$"); /* Driver for arbitrary double bulk pipe devices. * The driver assumes that there will be the same driver on the other side. * * XXX Some more information on what the framing of the IP packets looks like. * * To take full advantage of bulk transmission, packets should be chosen * between 1k and 5k in size (1k to make sure the sending side starts * streaming, and <5k to avoid overflowing the system with small TDs). */ /* probe/attach/detach: * Connect the driver to the hardware and netgraph * * The reason we submit a bulk in transfer is that USB does not know about * interrupts. The bulk transfer continuously polls the device for data. * While the device has no data available, the device NAKs the TDs. As soon * as there is data, the transfer happens and the data comes flowing in. * * In case you were wondering, interrupt transfers happen exactly that way. * It therefore doesn't make sense to use the interrupt pipe to signal * 'data ready' and then schedule a bulk transfer to fetch it. That would * incur a 2ms delay at least, without reducing bandwidth requirements. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR udbp_debug #include #include #include #include #include #include #include #ifdef USB_DEBUG static int udbp_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, udbp, CTLFLAG_RW, 0, "USB udbp"); -SYSCTL_INT(_hw_usb_udbp, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_udbp, OID_AUTO, debug, CTLFLAG_RWTUN, &udbp_debug, 0, "udbp debug level"); #endif #define UDBP_TIMEOUT 2000 /* timeout on outbound transfers, in * msecs */ #define UDBP_BUFFERSIZE MCLBYTES /* maximum number of bytes in one * transfer */ #define UDBP_T_WR 0 #define UDBP_T_RD 1 #define UDBP_T_WR_CS 2 #define UDBP_T_RD_CS 3 #define UDBP_T_MAX 4 #define UDBP_Q_MAXLEN 50 struct udbp_softc { struct mtx sc_mtx; struct ng_bt_mbufq sc_xmitq_hipri; /* hi-priority transmit queue */ struct ng_bt_mbufq sc_xmitq; /* low-priority transmit queue */ struct usb_xfer *sc_xfer[UDBP_T_MAX]; node_p sc_node; /* back pointer to node */ hook_p sc_hook; /* pointer to the hook */ struct mbuf *sc_bulk_in_buffer; uint32_t sc_packets_in; /* packets in from downstream */ uint32_t sc_packets_out; /* packets out towards downstream */ uint8_t sc_flags; #define UDBP_FLAG_READ_STALL 0x01 /* read transfer stalled */ #define UDBP_FLAG_WRITE_STALL 0x02 /* write transfer stalled */ uint8_t sc_name[16]; }; /* prototypes */ static int udbp_modload(module_t mod, int event, void *data); static device_probe_t udbp_probe; static device_attach_t udbp_attach; static device_detach_t udbp_detach; static usb_callback_t udbp_bulk_read_callback; static usb_callback_t udbp_bulk_read_clear_stall_callback; static usb_callback_t udbp_bulk_write_callback; static usb_callback_t udbp_bulk_write_clear_stall_callback; static void udbp_bulk_read_complete(node_p, hook_p, void *, int); static ng_constructor_t ng_udbp_constructor; static ng_rcvmsg_t ng_udbp_rcvmsg; static ng_shutdown_t ng_udbp_rmnode; static ng_newhook_t ng_udbp_newhook; static ng_connect_t ng_udbp_connect; static ng_rcvdata_t ng_udbp_rcvdata; static ng_disconnect_t ng_udbp_disconnect; /* Parse type for struct ngudbpstat */ static const struct ng_parse_struct_field ng_udbp_stat_type_fields[] = NG_UDBP_STATS_TYPE_INFO; static const struct ng_parse_type ng_udbp_stat_type = { &ng_parse_struct_type, &ng_udbp_stat_type_fields }; /* List of commands and how to convert arguments to/from ASCII */ static const struct ng_cmdlist ng_udbp_cmdlist[] = { { NGM_UDBP_COOKIE, NGM_UDBP_GET_STATUS, "getstatus", NULL, &ng_udbp_stat_type, }, { NGM_UDBP_COOKIE, NGM_UDBP_SET_FLAG, "setflag", &ng_parse_int32_type, NULL }, {0} }; /* Netgraph node type descriptor */ static struct ng_type ng_udbp_typestruct = { .version = NG_ABI_VERSION, .name = NG_UDBP_NODE_TYPE, .constructor = ng_udbp_constructor, .rcvmsg = ng_udbp_rcvmsg, .shutdown = ng_udbp_rmnode, .newhook = ng_udbp_newhook, .connect = ng_udbp_connect, .rcvdata = ng_udbp_rcvdata, .disconnect = ng_udbp_disconnect, .cmdlist = ng_udbp_cmdlist, }; /* USB config */ static const struct usb_config udbp_config[UDBP_T_MAX] = { [UDBP_T_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = UDBP_BUFFERSIZE, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = &udbp_bulk_write_callback, .timeout = UDBP_TIMEOUT, }, [UDBP_T_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = UDBP_BUFFERSIZE, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &udbp_bulk_read_callback, }, [UDBP_T_WR_CS] = { .type = UE_CONTROL, .endpoint = 0x00, /* Control pipe */ .direction = UE_DIR_ANY, .bufsize = sizeof(struct usb_device_request), .callback = &udbp_bulk_write_clear_stall_callback, .timeout = 1000, /* 1 second */ .interval = 50, /* 50ms */ }, [UDBP_T_RD_CS] = { .type = UE_CONTROL, .endpoint = 0x00, /* Control pipe */ .direction = UE_DIR_ANY, .bufsize = sizeof(struct usb_device_request), .callback = &udbp_bulk_read_clear_stall_callback, .timeout = 1000, /* 1 second */ .interval = 50, /* 50ms */ }, }; static devclass_t udbp_devclass; static device_method_t udbp_methods[] = { /* Device interface */ DEVMETHOD(device_probe, udbp_probe), DEVMETHOD(device_attach, udbp_attach), DEVMETHOD(device_detach, udbp_detach), DEVMETHOD_END }; static driver_t udbp_driver = { .name = "udbp", .methods = udbp_methods, .size = sizeof(struct udbp_softc), }; DRIVER_MODULE(udbp, uhub, udbp_driver, udbp_devclass, udbp_modload, 0); MODULE_DEPEND(udbp, netgraph, NG_ABI_VERSION, NG_ABI_VERSION, NG_ABI_VERSION); MODULE_DEPEND(udbp, usb, 1, 1, 1); MODULE_VERSION(udbp, 1); static int udbp_modload(module_t mod, int event, void *data) { int error; switch (event) { case MOD_LOAD: error = ng_newtype(&ng_udbp_typestruct); if (error != 0) { printf("%s: Could not register " "Netgraph node type, error=%d\n", NG_UDBP_NODE_TYPE, error); } break; case MOD_UNLOAD: error = ng_rmtype(&ng_udbp_typestruct); break; default: error = EOPNOTSUPP; break; } return (error); } static const STRUCT_USB_HOST_ID udbp_devs[] = { {USB_VPI(USB_VENDOR_NETCHIP, USB_PRODUCT_NETCHIP_TURBOCONNECT, 0)}, {USB_VPI(USB_VENDOR_NETCHIP, USB_PRODUCT_NETCHIP_GADGETZERO, 0)}, {USB_VPI(USB_VENDOR_PROLIFIC, USB_PRODUCT_PROLIFIC_PL2301, 0)}, {USB_VPI(USB_VENDOR_PROLIFIC, USB_PRODUCT_PROLIFIC_PL2302, 0)}, {USB_VPI(USB_VENDOR_ANCHOR, USB_PRODUCT_ANCHOR_EZLINK, 0)}, {USB_VPI(USB_VENDOR_GENESYS, USB_PRODUCT_GENESYS_GL620USB, 0)}, }; static int udbp_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != 0) return (ENXIO); if (uaa->info.bIfaceIndex != 0) return (ENXIO); return (usbd_lookup_id_by_uaa(udbp_devs, sizeof(udbp_devs), uaa)); } static int udbp_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct udbp_softc *sc = device_get_softc(dev); int error; device_set_usb_desc(dev); snprintf(sc->sc_name, sizeof(sc->sc_name), "%s", device_get_nameunit(dev)); mtx_init(&sc->sc_mtx, "udbp lock", NULL, MTX_DEF | MTX_RECURSE); error = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex, sc->sc_xfer, udbp_config, UDBP_T_MAX, sc, &sc->sc_mtx); if (error) { DPRINTF("error=%s\n", usbd_errstr(error)); goto detach; } NG_BT_MBUFQ_INIT(&sc->sc_xmitq, UDBP_Q_MAXLEN); NG_BT_MBUFQ_INIT(&sc->sc_xmitq_hipri, UDBP_Q_MAXLEN); /* create Netgraph node */ if (ng_make_node_common(&ng_udbp_typestruct, &sc->sc_node) != 0) { printf("%s: Could not create Netgraph node\n", sc->sc_name); sc->sc_node = NULL; goto detach; } /* name node */ if (ng_name_node(sc->sc_node, sc->sc_name) != 0) { printf("%s: Could not name node\n", sc->sc_name); NG_NODE_UNREF(sc->sc_node); sc->sc_node = NULL; goto detach; } NG_NODE_SET_PRIVATE(sc->sc_node, sc); /* the device is now operational */ return (0); /* success */ detach: udbp_detach(dev); return (ENOMEM); /* failure */ } static int udbp_detach(device_t dev) { struct udbp_softc *sc = device_get_softc(dev); /* destroy Netgraph node */ if (sc->sc_node != NULL) { NG_NODE_SET_PRIVATE(sc->sc_node, NULL); ng_rmnode_self(sc->sc_node); sc->sc_node = NULL; } /* free USB transfers, if any */ usbd_transfer_unsetup(sc->sc_xfer, UDBP_T_MAX); mtx_destroy(&sc->sc_mtx); /* destroy queues */ NG_BT_MBUFQ_DESTROY(&sc->sc_xmitq); NG_BT_MBUFQ_DESTROY(&sc->sc_xmitq_hipri); /* extra check */ if (sc->sc_bulk_in_buffer) { m_freem(sc->sc_bulk_in_buffer); sc->sc_bulk_in_buffer = NULL; } return (0); /* success */ } static void udbp_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct udbp_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; struct mbuf *m; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: /* allocate new mbuf */ MGETHDR(m, M_NOWAIT, MT_DATA); if (m == NULL) { goto tr_setup; } MCLGET(m, M_NOWAIT); if (!(m->m_flags & M_EXT)) { m_freem(m); goto tr_setup; } m->m_pkthdr.len = m->m_len = actlen; pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, m->m_data, actlen); sc->sc_bulk_in_buffer = m; DPRINTF("received package %d bytes\n", actlen); case USB_ST_SETUP: tr_setup: if (sc->sc_bulk_in_buffer) { ng_send_fn(sc->sc_node, NULL, &udbp_bulk_read_complete, NULL, 0); return; } if (sc->sc_flags & UDBP_FLAG_READ_STALL) { usbd_transfer_start(sc->sc_xfer[UDBP_T_RD_CS]); return; } usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ sc->sc_flags |= UDBP_FLAG_READ_STALL; usbd_transfer_start(sc->sc_xfer[UDBP_T_RD_CS]); } return; } } static void udbp_bulk_read_clear_stall_callback(struct usb_xfer *xfer, usb_error_t error) { struct udbp_softc *sc = usbd_xfer_softc(xfer); struct usb_xfer *xfer_other = sc->sc_xfer[UDBP_T_RD]; if (usbd_clear_stall_callback(xfer, xfer_other)) { DPRINTF("stall cleared\n"); sc->sc_flags &= ~UDBP_FLAG_READ_STALL; usbd_transfer_start(xfer_other); } } static void udbp_bulk_read_complete(node_p node, hook_p hook, void *arg1, int arg2) { struct udbp_softc *sc = NG_NODE_PRIVATE(node); struct mbuf *m; int error; if (sc == NULL) { return; } mtx_lock(&sc->sc_mtx); m = sc->sc_bulk_in_buffer; if (m) { sc->sc_bulk_in_buffer = NULL; if ((sc->sc_hook == NULL) || NG_HOOK_NOT_VALID(sc->sc_hook)) { DPRINTF("No upstream hook\n"); goto done; } sc->sc_packets_in++; NG_SEND_DATA_ONLY(error, sc->sc_hook, m); m = NULL; } done: if (m) { m_freem(m); } /* start USB bulk-in transfer, if not already started */ usbd_transfer_start(sc->sc_xfer[UDBP_T_RD]); mtx_unlock(&sc->sc_mtx); } static void udbp_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct udbp_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; struct mbuf *m; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: sc->sc_packets_out++; case USB_ST_SETUP: if (sc->sc_flags & UDBP_FLAG_WRITE_STALL) { usbd_transfer_start(sc->sc_xfer[UDBP_T_WR_CS]); return; } /* get next mbuf, if any */ NG_BT_MBUFQ_DEQUEUE(&sc->sc_xmitq_hipri, m); if (m == NULL) { NG_BT_MBUFQ_DEQUEUE(&sc->sc_xmitq, m); if (m == NULL) { DPRINTF("Data queue is empty\n"); return; } } if (m->m_pkthdr.len > MCLBYTES) { DPRINTF("truncating large packet " "from %d to %d bytes\n", m->m_pkthdr.len, MCLBYTES); m->m_pkthdr.len = MCLBYTES; } pc = usbd_xfer_get_frame(xfer, 0); usbd_m_copy_in(pc, 0, m, 0, m->m_pkthdr.len); usbd_xfer_set_frame_len(xfer, 0, m->m_pkthdr.len); DPRINTF("packet out: %d bytes\n", m->m_pkthdr.len); m_freem(m); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ sc->sc_flags |= UDBP_FLAG_WRITE_STALL; usbd_transfer_start(sc->sc_xfer[UDBP_T_WR_CS]); } return; } } static void udbp_bulk_write_clear_stall_callback(struct usb_xfer *xfer, usb_error_t error) { struct udbp_softc *sc = usbd_xfer_softc(xfer); struct usb_xfer *xfer_other = sc->sc_xfer[UDBP_T_WR]; if (usbd_clear_stall_callback(xfer, xfer_other)) { DPRINTF("stall cleared\n"); sc->sc_flags &= ~UDBP_FLAG_WRITE_STALL; usbd_transfer_start(xfer_other); } } /*********************************************************************** * Start of Netgraph methods **********************************************************************/ /* * If this is a device node so this work is done in the attach() * routine and the constructor will return EINVAL as you should not be able * to create nodes that depend on hardware (unless you can add the hardware :) */ static int ng_udbp_constructor(node_p node) { return (EINVAL); } /* * Give our ok for a hook to be added... * If we are not running this might kick a device into life. * Possibly decode information out of the hook name. * Add the hook's private info to the hook structure. * (if we had some). In this example, we assume that there is a * an array of structs, called 'channel' in the private info, * one for each active channel. The private * pointer of each hook points to the appropriate UDBP_hookinfo struct * so that the source of an input packet is easily identified. */ static int ng_udbp_newhook(node_p node, hook_p hook, const char *name) { struct udbp_softc *sc = NG_NODE_PRIVATE(node); int32_t error = 0; if (strcmp(name, NG_UDBP_HOOK_NAME)) { return (EINVAL); } mtx_lock(&sc->sc_mtx); if (sc->sc_hook != NULL) { error = EISCONN; } else { sc->sc_hook = hook; NG_HOOK_SET_PRIVATE(hook, NULL); } mtx_unlock(&sc->sc_mtx); return (error); } /* * Get a netgraph control message. * Check it is one we understand. If needed, send a response. * We could save the address for an async action later, but don't here. * Always free the message. * The response should be in a malloc'd region that the caller can 'free'. * A response is not required. * Theoretically you could respond defferently to old message types if * the cookie in the header didn't match what we consider to be current * (so that old userland programs could continue to work). */ static int ng_udbp_rcvmsg(node_p node, item_p item, hook_p lasthook) { struct udbp_softc *sc = NG_NODE_PRIVATE(node); struct ng_mesg *resp = NULL; int error = 0; struct ng_mesg *msg; NGI_GET_MSG(item, msg); /* Deal with message according to cookie and command */ switch (msg->header.typecookie) { case NGM_UDBP_COOKIE: switch (msg->header.cmd) { case NGM_UDBP_GET_STATUS: { struct ngudbpstat *stats; NG_MKRESPONSE(resp, msg, sizeof(*stats), M_NOWAIT); if (!resp) { error = ENOMEM; break; } stats = (struct ngudbpstat *)resp->data; mtx_lock(&sc->sc_mtx); stats->packets_in = sc->sc_packets_in; stats->packets_out = sc->sc_packets_out; mtx_unlock(&sc->sc_mtx); break; } case NGM_UDBP_SET_FLAG: if (msg->header.arglen != sizeof(uint32_t)) { error = EINVAL; break; } DPRINTF("flags = 0x%08x\n", *((uint32_t *)msg->data)); break; default: error = EINVAL; /* unknown command */ break; } break; default: error = EINVAL; /* unknown cookie type */ break; } /* Take care of synchronous response, if any */ NG_RESPOND_MSG(error, node, item, resp); NG_FREE_MSG(msg); return (error); } /* * Accept data from the hook and queue it for output. */ static int ng_udbp_rcvdata(hook_p hook, item_p item) { struct udbp_softc *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook)); struct ng_bt_mbufq *queue_ptr; struct mbuf *m; struct ng_tag_prio *ptag; int error; if (sc == NULL) { NG_FREE_ITEM(item); return (EHOSTDOWN); } NGI_GET_M(item, m); NG_FREE_ITEM(item); /* * Now queue the data for when it can be sent */ ptag = (void *)m_tag_locate(m, NGM_GENERIC_COOKIE, NG_TAG_PRIO, NULL); if (ptag && (ptag->priority > NG_PRIO_CUTOFF)) queue_ptr = &sc->sc_xmitq_hipri; else queue_ptr = &sc->sc_xmitq; mtx_lock(&sc->sc_mtx); if (NG_BT_MBUFQ_FULL(queue_ptr)) { NG_BT_MBUFQ_DROP(queue_ptr); NG_FREE_M(m); error = ENOBUFS; } else { NG_BT_MBUFQ_ENQUEUE(queue_ptr, m); /* * start bulk-out transfer, if not already started: */ usbd_transfer_start(sc->sc_xfer[UDBP_T_WR]); error = 0; } mtx_unlock(&sc->sc_mtx); return (error); } /* * Do local shutdown processing.. * We are a persistant device, we refuse to go away, and * only remove our links and reset ourself. */ static int ng_udbp_rmnode(node_p node) { struct udbp_softc *sc = NG_NODE_PRIVATE(node); /* Let old node go */ NG_NODE_SET_PRIVATE(node, NULL); NG_NODE_UNREF(node); /* forget it ever existed */ if (sc == NULL) { goto done; } /* Create Netgraph node */ if (ng_make_node_common(&ng_udbp_typestruct, &sc->sc_node) != 0) { printf("%s: Could not create Netgraph node\n", sc->sc_name); sc->sc_node = NULL; goto done; } /* Name node */ if (ng_name_node(sc->sc_node, sc->sc_name) != 0) { printf("%s: Could not name Netgraph node\n", sc->sc_name); NG_NODE_UNREF(sc->sc_node); sc->sc_node = NULL; goto done; } NG_NODE_SET_PRIVATE(sc->sc_node, sc); done: if (sc) { mtx_unlock(&sc->sc_mtx); } return (0); } /* * This is called once we've already connected a new hook to the other node. * It gives us a chance to balk at the last minute. */ static int ng_udbp_connect(hook_p hook) { struct udbp_softc *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook)); /* probably not at splnet, force outward queueing */ NG_HOOK_FORCE_QUEUE(NG_HOOK_PEER(hook)); mtx_lock(&sc->sc_mtx); sc->sc_flags |= (UDBP_FLAG_READ_STALL | UDBP_FLAG_WRITE_STALL); /* start bulk-in transfer */ usbd_transfer_start(sc->sc_xfer[UDBP_T_RD]); /* start bulk-out transfer */ usbd_transfer_start(sc->sc_xfer[UDBP_T_WR]); mtx_unlock(&sc->sc_mtx); return (0); } /* * Dook disconnection * * For this type, removal of the last link destroys the node */ static int ng_udbp_disconnect(hook_p hook) { struct udbp_softc *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook)); int error = 0; if (sc != NULL) { mtx_lock(&sc->sc_mtx); if (hook != sc->sc_hook) { error = EINVAL; } else { /* stop bulk-in transfer */ usbd_transfer_stop(sc->sc_xfer[UDBP_T_RD_CS]); usbd_transfer_stop(sc->sc_xfer[UDBP_T_RD]); /* stop bulk-out transfer */ usbd_transfer_stop(sc->sc_xfer[UDBP_T_WR_CS]); usbd_transfer_stop(sc->sc_xfer[UDBP_T_WR]); /* cleanup queues */ NG_BT_MBUFQ_DRAIN(&sc->sc_xmitq); NG_BT_MBUFQ_DRAIN(&sc->sc_xmitq_hipri); if (sc->sc_bulk_in_buffer) { m_freem(sc->sc_bulk_in_buffer); sc->sc_bulk_in_buffer = NULL; } sc->sc_hook = NULL; } mtx_unlock(&sc->sc_mtx); } if ((NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0) && (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))) ng_rmnode_self(NG_HOOK_NODE(hook)); return (error); } Index: head/sys/dev/usb/net/if_aue.c =================================================================== --- head/sys/dev/usb/net/if_aue.c (revision 276700) +++ head/sys/dev/usb/net/if_aue.c (revision 276701) @@ -1,1065 +1,1065 @@ /*- * Copyright (c) 1997, 1998, 1999, 2000 * Bill Paul . All rights reserved. * * Copyright (c) 2006 * Alfred Perlstein . All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Bill Paul. * 4. Neither the name of the author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * ADMtek AN986 Pegasus and AN8511 Pegasus II USB to ethernet driver. * Datasheet is available from http://www.admtek.com.tw. * * Written by Bill Paul * Electrical Engineering Department * Columbia University, New York City * * SMP locking by Alfred Perlstein . * RED Inc. */ /* * The Pegasus chip uses four USB "endpoints" to provide 10/100 ethernet * support: the control endpoint for reading/writing registers, burst * read endpoint for packet reception, burst write for packet transmission * and one for "interrupts." The chip uses the same RX filter scheme * as the other ADMtek ethernet parts: one perfect filter entry for the * the station address and a 64-bit multicast hash table. The chip supports * both MII and HomePNA attachments. * * Since the maximum data transfer speed of USB is supposed to be 12Mbps, * you're never really going to get 100Mbps speeds from this device. I * think the idea is to allow the device to connect to 10 or 100Mbps * networks, not necessarily to provide 100Mbps performance. Also, since * the controller uses an external PHY chip, it's possible that board * designers might simply choose a 10Mbps PHY. * * Registers are accessed using uether_do_request(). Packet * transfers are done using usbd_transfer() and friends. */ #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 "usbdevs.h" #define USB_DEBUG_VAR aue_debug #include #include #include #include #ifdef USB_DEBUG static int aue_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, aue, CTLFLAG_RW, 0, "USB aue"); -SYSCTL_INT(_hw_usb_aue, OID_AUTO, debug, CTLFLAG_RW, &aue_debug, 0, +SYSCTL_INT(_hw_usb_aue, OID_AUTO, debug, CTLFLAG_RWTUN, &aue_debug, 0, "Debug level"); #endif /* * Various supported device vendors/products. */ static const STRUCT_USB_HOST_ID aue_devs[] = { #define AUE_DEV(v,p,i) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, i) } AUE_DEV(3COM, 3C460B, AUE_FLAG_PII), AUE_DEV(ABOCOM, DSB650TX_PNA, 0), AUE_DEV(ABOCOM, UFE1000, AUE_FLAG_LSYS), AUE_DEV(ABOCOM, XX10, 0), AUE_DEV(ABOCOM, XX1, AUE_FLAG_PNA | AUE_FLAG_PII), AUE_DEV(ABOCOM, XX2, AUE_FLAG_PII), AUE_DEV(ABOCOM, XX4, AUE_FLAG_PNA), AUE_DEV(ABOCOM, XX5, AUE_FLAG_PNA), AUE_DEV(ABOCOM, XX6, AUE_FLAG_PII), AUE_DEV(ABOCOM, XX7, AUE_FLAG_PII), AUE_DEV(ABOCOM, XX8, AUE_FLAG_PII), AUE_DEV(ABOCOM, XX9, AUE_FLAG_PNA), AUE_DEV(ACCTON, SS1001, AUE_FLAG_PII), AUE_DEV(ACCTON, USB320_EC, 0), AUE_DEV(ADMTEK, PEGASUSII_2, AUE_FLAG_PII), AUE_DEV(ADMTEK, PEGASUSII_3, AUE_FLAG_PII), AUE_DEV(ADMTEK, PEGASUSII_4, AUE_FLAG_PII), AUE_DEV(ADMTEK, PEGASUSII, AUE_FLAG_PII), AUE_DEV(ADMTEK, PEGASUS, AUE_FLAG_PNA | AUE_FLAG_DUAL_PHY), AUE_DEV(AEI, FASTETHERNET, AUE_FLAG_PII), AUE_DEV(ALLIEDTELESYN, ATUSB100, AUE_FLAG_PII), AUE_DEV(ATEN, UC110T, AUE_FLAG_PII), AUE_DEV(BELKIN, USB2LAN, AUE_FLAG_PII), AUE_DEV(BILLIONTON, USB100, 0), AUE_DEV(BILLIONTON, USBE100, AUE_FLAG_PII), AUE_DEV(BILLIONTON, USBEL100, 0), AUE_DEV(BILLIONTON, USBLP100, AUE_FLAG_PNA), AUE_DEV(COREGA, FETHER_USB_TXS, AUE_FLAG_PII), AUE_DEV(COREGA, FETHER_USB_TX, 0), AUE_DEV(DLINK, DSB650TX1, AUE_FLAG_LSYS), AUE_DEV(DLINK, DSB650TX2, AUE_FLAG_LSYS | AUE_FLAG_PII), AUE_DEV(DLINK, DSB650TX3, AUE_FLAG_LSYS | AUE_FLAG_PII), AUE_DEV(DLINK, DSB650TX4, AUE_FLAG_LSYS | AUE_FLAG_PII), AUE_DEV(DLINK, DSB650TX_PNA, AUE_FLAG_PNA), AUE_DEV(DLINK, DSB650TX, AUE_FLAG_LSYS), AUE_DEV(DLINK, DSB650, AUE_FLAG_LSYS), AUE_DEV(ELCON, PLAN, AUE_FLAG_PNA | AUE_FLAG_PII), AUE_DEV(ELECOM, LDUSB20, AUE_FLAG_PII), AUE_DEV(ELECOM, LDUSBLTX, AUE_FLAG_PII), AUE_DEV(ELECOM, LDUSBTX0, 0), AUE_DEV(ELECOM, LDUSBTX1, AUE_FLAG_LSYS), AUE_DEV(ELECOM, LDUSBTX2, 0), AUE_DEV(ELECOM, LDUSBTX3, AUE_FLAG_LSYS), AUE_DEV(ELSA, USB2ETHERNET, 0), AUE_DEV(GIGABYTE, GNBR402W, 0), AUE_DEV(HAWKING, UF100, AUE_FLAG_PII), AUE_DEV(HP, HN210E, AUE_FLAG_PII), AUE_DEV(IODATA, USBETTXS, AUE_FLAG_PII), AUE_DEV(IODATA, USBETTX, 0), AUE_DEV(KINGSTON, KNU101TX, 0), AUE_DEV(LINKSYS, USB100H1, AUE_FLAG_LSYS | AUE_FLAG_PNA), AUE_DEV(LINKSYS, USB100TX, AUE_FLAG_LSYS), AUE_DEV(LINKSYS, USB10TA, AUE_FLAG_LSYS), AUE_DEV(LINKSYS, USB10TX1, AUE_FLAG_LSYS | AUE_FLAG_PII), AUE_DEV(LINKSYS, USB10TX2, AUE_FLAG_LSYS | AUE_FLAG_PII), AUE_DEV(LINKSYS, USB10T, AUE_FLAG_LSYS), AUE_DEV(MELCO, LUA2TX5, AUE_FLAG_PII), AUE_DEV(MELCO, LUATX1, 0), AUE_DEV(MELCO, LUATX5, 0), AUE_DEV(MICROSOFT, MN110, AUE_FLAG_PII), AUE_DEV(NETGEAR, FA101, AUE_FLAG_PII), AUE_DEV(SIEMENS, SPEEDSTREAM, AUE_FLAG_PII), AUE_DEV(SIIG2, USBTOETHER, AUE_FLAG_PII), AUE_DEV(SMARTBRIDGES, SMARTNIC, AUE_FLAG_PII), AUE_DEV(SMC, 2202USB, 0), AUE_DEV(SMC, 2206USB, AUE_FLAG_PII), AUE_DEV(SOHOWARE, NUB100, 0), AUE_DEV(SOHOWARE, NUB110, AUE_FLAG_PII), #undef AUE_DEV }; /* prototypes */ static device_probe_t aue_probe; static device_attach_t aue_attach; static device_detach_t aue_detach; static miibus_readreg_t aue_miibus_readreg; static miibus_writereg_t aue_miibus_writereg; static miibus_statchg_t aue_miibus_statchg; static usb_callback_t aue_intr_callback; static usb_callback_t aue_bulk_read_callback; static usb_callback_t aue_bulk_write_callback; static uether_fn_t aue_attach_post; static uether_fn_t aue_init; static uether_fn_t aue_stop; static uether_fn_t aue_start; static uether_fn_t aue_tick; static uether_fn_t aue_setmulti; static uether_fn_t aue_setpromisc; static uint8_t aue_csr_read_1(struct aue_softc *, uint16_t); static uint16_t aue_csr_read_2(struct aue_softc *, uint16_t); static void aue_csr_write_1(struct aue_softc *, uint16_t, uint8_t); static void aue_csr_write_2(struct aue_softc *, uint16_t, uint16_t); static uint16_t aue_eeprom_getword(struct aue_softc *, int); static void aue_reset(struct aue_softc *); static void aue_reset_pegasus_II(struct aue_softc *); static int aue_ifmedia_upd(struct ifnet *); static void aue_ifmedia_sts(struct ifnet *, struct ifmediareq *); static const struct usb_config aue_config[AUE_N_TRANSFER] = { [AUE_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = (MCLBYTES + 2), .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = aue_bulk_write_callback, .timeout = 10000, /* 10 seconds */ }, [AUE_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = (MCLBYTES + 4 + ETHER_CRC_LEN), .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = aue_bulk_read_callback, }, [AUE_INTR_DT_RD] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = aue_intr_callback, }, }; static device_method_t aue_methods[] = { /* Device interface */ DEVMETHOD(device_probe, aue_probe), DEVMETHOD(device_attach, aue_attach), DEVMETHOD(device_detach, aue_detach), /* MII interface */ DEVMETHOD(miibus_readreg, aue_miibus_readreg), DEVMETHOD(miibus_writereg, aue_miibus_writereg), DEVMETHOD(miibus_statchg, aue_miibus_statchg), DEVMETHOD_END }; static driver_t aue_driver = { .name = "aue", .methods = aue_methods, .size = sizeof(struct aue_softc) }; static devclass_t aue_devclass; DRIVER_MODULE(aue, uhub, aue_driver, aue_devclass, NULL, 0); DRIVER_MODULE(miibus, aue, miibus_driver, miibus_devclass, 0, 0); MODULE_DEPEND(aue, uether, 1, 1, 1); MODULE_DEPEND(aue, usb, 1, 1, 1); MODULE_DEPEND(aue, ether, 1, 1, 1); MODULE_DEPEND(aue, miibus, 1, 1, 1); MODULE_VERSION(aue, 1); static const struct usb_ether_methods aue_ue_methods = { .ue_attach_post = aue_attach_post, .ue_start = aue_start, .ue_init = aue_init, .ue_stop = aue_stop, .ue_tick = aue_tick, .ue_setmulti = aue_setmulti, .ue_setpromisc = aue_setpromisc, .ue_mii_upd = aue_ifmedia_upd, .ue_mii_sts = aue_ifmedia_sts, }; #define AUE_SETBIT(sc, reg, x) \ aue_csr_write_1(sc, reg, aue_csr_read_1(sc, reg) | (x)) #define AUE_CLRBIT(sc, reg, x) \ aue_csr_write_1(sc, reg, aue_csr_read_1(sc, reg) & ~(x)) static uint8_t aue_csr_read_1(struct aue_softc *sc, uint16_t reg) { struct usb_device_request req; usb_error_t err; uint8_t val; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = AUE_UR_READREG; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, 1); err = uether_do_request(&sc->sc_ue, &req, &val, 1000); if (err) return (0); return (val); } static uint16_t aue_csr_read_2(struct aue_softc *sc, uint16_t reg) { struct usb_device_request req; usb_error_t err; uint16_t val; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = AUE_UR_READREG; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, 2); err = uether_do_request(&sc->sc_ue, &req, &val, 1000); if (err) return (0); return (le16toh(val)); } static void aue_csr_write_1(struct aue_softc *sc, uint16_t reg, uint8_t val) { struct usb_device_request req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = AUE_UR_WRITEREG; req.wValue[0] = val; req.wValue[1] = 0; USETW(req.wIndex, reg); USETW(req.wLength, 1); if (uether_do_request(&sc->sc_ue, &req, &val, 1000)) { /* error ignored */ } } static void aue_csr_write_2(struct aue_softc *sc, uint16_t reg, uint16_t val) { struct usb_device_request req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = AUE_UR_WRITEREG; USETW(req.wValue, val); USETW(req.wIndex, reg); USETW(req.wLength, 2); val = htole16(val); if (uether_do_request(&sc->sc_ue, &req, &val, 1000)) { /* error ignored */ } } /* * Read a word of data stored in the EEPROM at address 'addr.' */ static uint16_t aue_eeprom_getword(struct aue_softc *sc, int addr) { int i; aue_csr_write_1(sc, AUE_EE_REG, addr); aue_csr_write_1(sc, AUE_EE_CTL, AUE_EECTL_READ); for (i = 0; i != AUE_TIMEOUT; i++) { if (aue_csr_read_1(sc, AUE_EE_CTL) & AUE_EECTL_DONE) break; if (uether_pause(&sc->sc_ue, hz / 100)) break; } if (i == AUE_TIMEOUT) device_printf(sc->sc_ue.ue_dev, "EEPROM read timed out\n"); return (aue_csr_read_2(sc, AUE_EE_DATA)); } /* * Read station address(offset 0) from the EEPROM. */ static void aue_read_mac(struct aue_softc *sc, uint8_t *eaddr) { int i, offset; uint16_t word; for (i = 0, offset = 0; i < ETHER_ADDR_LEN / 2; i++) { word = aue_eeprom_getword(sc, offset + i); eaddr[i * 2] = (uint8_t)word; eaddr[i * 2 + 1] = (uint8_t)(word >> 8); } } static int aue_miibus_readreg(device_t dev, int phy, int reg) { struct aue_softc *sc = device_get_softc(dev); int i, locked; uint16_t val = 0; locked = mtx_owned(&sc->sc_mtx); if (!locked) AUE_LOCK(sc); /* * The Am79C901 HomePNA PHY actually contains two transceivers: a 1Mbps * HomePNA PHY and a 10Mbps full/half duplex ethernet PHY with NWAY * autoneg. However in the ADMtek adapter, only the 1Mbps PHY is * actually connected to anything, so we ignore the 10Mbps one. It * happens to be configured for MII address 3, so we filter that out. */ if (sc->sc_flags & AUE_FLAG_DUAL_PHY) { if (phy == 3) goto done; #if 0 if (phy != 1) goto done; #endif } aue_csr_write_1(sc, AUE_PHY_ADDR, phy); aue_csr_write_1(sc, AUE_PHY_CTL, reg | AUE_PHYCTL_READ); for (i = 0; i != AUE_TIMEOUT; i++) { if (aue_csr_read_1(sc, AUE_PHY_CTL) & AUE_PHYCTL_DONE) break; if (uether_pause(&sc->sc_ue, hz / 100)) break; } if (i == AUE_TIMEOUT) device_printf(sc->sc_ue.ue_dev, "MII read timed out\n"); val = aue_csr_read_2(sc, AUE_PHY_DATA); done: if (!locked) AUE_UNLOCK(sc); return (val); } static int aue_miibus_writereg(device_t dev, int phy, int reg, int data) { struct aue_softc *sc = device_get_softc(dev); int i; int locked; if (phy == 3) return (0); locked = mtx_owned(&sc->sc_mtx); if (!locked) AUE_LOCK(sc); aue_csr_write_2(sc, AUE_PHY_DATA, data); aue_csr_write_1(sc, AUE_PHY_ADDR, phy); aue_csr_write_1(sc, AUE_PHY_CTL, reg | AUE_PHYCTL_WRITE); for (i = 0; i != AUE_TIMEOUT; i++) { if (aue_csr_read_1(sc, AUE_PHY_CTL) & AUE_PHYCTL_DONE) break; if (uether_pause(&sc->sc_ue, hz / 100)) break; } if (i == AUE_TIMEOUT) device_printf(sc->sc_ue.ue_dev, "MII write timed out\n"); if (!locked) AUE_UNLOCK(sc); return (0); } static void aue_miibus_statchg(device_t dev) { struct aue_softc *sc = device_get_softc(dev); struct mii_data *mii = GET_MII(sc); int locked; locked = mtx_owned(&sc->sc_mtx); if (!locked) AUE_LOCK(sc); AUE_CLRBIT(sc, AUE_CTL0, AUE_CTL0_RX_ENB | AUE_CTL0_TX_ENB); if (IFM_SUBTYPE(mii->mii_media_active) == IFM_100_TX) AUE_SETBIT(sc, AUE_CTL1, AUE_CTL1_SPEEDSEL); else AUE_CLRBIT(sc, AUE_CTL1, AUE_CTL1_SPEEDSEL); if ((mii->mii_media_active & IFM_GMASK) == IFM_FDX) AUE_SETBIT(sc, AUE_CTL1, AUE_CTL1_DUPLEX); else AUE_CLRBIT(sc, AUE_CTL1, AUE_CTL1_DUPLEX); AUE_SETBIT(sc, AUE_CTL0, AUE_CTL0_RX_ENB | AUE_CTL0_TX_ENB); /* * Set the LED modes on the LinkSys adapter. * This turns on the 'dual link LED' bin in the auxmode * register of the Broadcom PHY. */ if (sc->sc_flags & AUE_FLAG_LSYS) { uint16_t auxmode; auxmode = aue_miibus_readreg(dev, 0, 0x1b); aue_miibus_writereg(dev, 0, 0x1b, auxmode | 0x04); } if (!locked) AUE_UNLOCK(sc); } #define AUE_BITS 6 static void aue_setmulti(struct usb_ether *ue) { struct aue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); struct ifmultiaddr *ifma; uint32_t h = 0; uint32_t i; uint8_t hashtbl[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; AUE_LOCK_ASSERT(sc, MA_OWNED); if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) { AUE_SETBIT(sc, AUE_CTL0, AUE_CTL0_ALLMULTI); return; } AUE_CLRBIT(sc, AUE_CTL0, AUE_CTL0_ALLMULTI); /* now program new ones */ if_maddr_rlock(ifp); TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) { if (ifma->ifma_addr->sa_family != AF_LINK) continue; h = ether_crc32_le(LLADDR((struct sockaddr_dl *) ifma->ifma_addr), ETHER_ADDR_LEN) & ((1 << AUE_BITS) - 1); hashtbl[(h >> 3)] |= 1 << (h & 0x7); } if_maddr_runlock(ifp); /* write the hashtable */ for (i = 0; i != 8; i++) aue_csr_write_1(sc, AUE_MAR0 + i, hashtbl[i]); } static void aue_reset_pegasus_II(struct aue_softc *sc) { /* Magic constants taken from Linux driver. */ aue_csr_write_1(sc, AUE_REG_1D, 0); aue_csr_write_1(sc, AUE_REG_7B, 2); #if 0 if ((sc->sc_flags & HAS_HOME_PNA) && mii_mode) aue_csr_write_1(sc, AUE_REG_81, 6); else #endif aue_csr_write_1(sc, AUE_REG_81, 2); } static void aue_reset(struct aue_softc *sc) { int i; AUE_SETBIT(sc, AUE_CTL1, AUE_CTL1_RESETMAC); for (i = 0; i != AUE_TIMEOUT; i++) { if (!(aue_csr_read_1(sc, AUE_CTL1) & AUE_CTL1_RESETMAC)) break; if (uether_pause(&sc->sc_ue, hz / 100)) break; } if (i == AUE_TIMEOUT) device_printf(sc->sc_ue.ue_dev, "reset failed\n"); /* * The PHY(s) attached to the Pegasus chip may be held * in reset until we flip on the GPIO outputs. Make sure * to set the GPIO pins high so that the PHY(s) will * be enabled. * * NOTE: We used to force all of the GPIO pins low first and then * enable the ones we want. This has been changed to better * match the ADMtek's reference design to avoid setting the * power-down configuration line of the PHY at the same time * it is reset. */ aue_csr_write_1(sc, AUE_GPIO0, AUE_GPIO_SEL0|AUE_GPIO_SEL1); aue_csr_write_1(sc, AUE_GPIO0, AUE_GPIO_SEL0|AUE_GPIO_SEL1|AUE_GPIO_OUT0); if (sc->sc_flags & AUE_FLAG_LSYS) { /* Grrr. LinkSys has to be different from everyone else. */ aue_csr_write_1(sc, AUE_GPIO0, AUE_GPIO_SEL0|AUE_GPIO_SEL1); aue_csr_write_1(sc, AUE_GPIO0, AUE_GPIO_SEL0|AUE_GPIO_SEL1|AUE_GPIO_OUT0); } if (sc->sc_flags & AUE_FLAG_PII) aue_reset_pegasus_II(sc); /* Wait a little while for the chip to get its brains in order: */ uether_pause(&sc->sc_ue, hz / 100); } static void aue_attach_post(struct usb_ether *ue) { struct aue_softc *sc = uether_getsc(ue); /* reset the adapter */ aue_reset(sc); /* get station address from the EEPROM */ aue_read_mac(sc, ue->ue_eaddr); } /* * Probe for a Pegasus chip. */ static int aue_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != AUE_CONFIG_INDEX) return (ENXIO); if (uaa->info.bIfaceIndex != AUE_IFACE_IDX) return (ENXIO); /* * Belkin USB Bluetooth dongles of the F8T012xx1 model series conflict * with older Belkin USB2LAN adapters. Skip if_aue if we detect one of * the devices that look like Bluetooth adapters. */ if (uaa->info.idVendor == USB_VENDOR_BELKIN && uaa->info.idProduct == USB_PRODUCT_BELKIN_F8T012 && uaa->info.bcdDevice == 0x0413) return (ENXIO); return (usbd_lookup_id_by_uaa(aue_devs, sizeof(aue_devs), uaa)); } /* * Attach the interface. Allocate softc structures, do ifmedia * setup and ethernet/BPF attach. */ static int aue_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct aue_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; uint8_t iface_index; int error; sc->sc_flags = USB_GET_DRIVER_INFO(uaa); if (uaa->info.bcdDevice >= 0x0201) { /* XXX currently undocumented */ sc->sc_flags |= AUE_FLAG_VER_2; } device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF); iface_index = AUE_IFACE_IDX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, aue_config, AUE_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(dev, "allocating USB transfers failed\n"); goto detach; } ue->ue_sc = sc; ue->ue_dev = dev; ue->ue_udev = uaa->device; ue->ue_mtx = &sc->sc_mtx; ue->ue_methods = &aue_ue_methods; error = uether_ifattach(ue); if (error) { device_printf(dev, "could not attach interface\n"); goto detach; } return (0); /* success */ detach: aue_detach(dev); return (ENXIO); /* failure */ } static int aue_detach(device_t dev) { struct aue_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; usbd_transfer_unsetup(sc->sc_xfer, AUE_N_TRANSFER); uether_ifdetach(ue); mtx_destroy(&sc->sc_mtx); return (0); } static void aue_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct aue_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct aue_intrpkt pkt; struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if ((ifp->if_drv_flags & IFF_DRV_RUNNING) && actlen >= (int)sizeof(pkt)) { pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, &pkt, sizeof(pkt)); if (pkt.aue_txstat0) if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); if (pkt.aue_txstat0 & (AUE_TXSTAT0_LATECOLL | AUE_TXSTAT0_EXCESSCOLL)) if_inc_counter(ifp, IFCOUNTER_COLLISIONS, 1); } /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void aue_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct aue_softc *sc = usbd_xfer_softc(xfer); struct usb_ether *ue = &sc->sc_ue; struct ifnet *ifp = uether_getifp(ue); struct aue_rxpkt stat; struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); pc = usbd_xfer_get_frame(xfer, 0); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(11, "received %d bytes\n", actlen); if (sc->sc_flags & AUE_FLAG_VER_2) { if (actlen == 0) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } } else { if (actlen <= (int)(sizeof(stat) + ETHER_CRC_LEN)) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } usbd_copy_out(pc, actlen - sizeof(stat), &stat, sizeof(stat)); /* * turn off all the non-error bits in the rx status * word: */ stat.aue_rxstat &= AUE_RXSTAT_MASK; if (stat.aue_rxstat) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } /* No errors; receive the packet. */ actlen -= (sizeof(stat) + ETHER_CRC_LEN); } uether_rxbuf(ue, pc, 0, actlen); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); uether_rxflush(ue); return; default: /* Error */ DPRINTF("bulk read error, %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void aue_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct aue_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct usb_page_cache *pc; struct mbuf *m; uint8_t buf[2]; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); pc = usbd_xfer_get_frame(xfer, 0); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(11, "transfer of %d bytes complete\n", actlen); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: if ((sc->sc_flags & AUE_FLAG_LINK) == 0) { /* * don't send anything if there is no link ! */ return; } IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) return; if (m->m_pkthdr.len > MCLBYTES) m->m_pkthdr.len = MCLBYTES; if (sc->sc_flags & AUE_FLAG_VER_2) { usbd_xfer_set_frame_len(xfer, 0, m->m_pkthdr.len); usbd_m_copy_in(pc, 0, m, 0, m->m_pkthdr.len); } else { usbd_xfer_set_frame_len(xfer, 0, (m->m_pkthdr.len + 2)); /* * The ADMtek documentation says that the * packet length is supposed to be specified * in the first two bytes of the transfer, * however it actually seems to ignore this * info and base the frame size on the bulk * transfer length. */ buf[0] = (uint8_t)(m->m_pkthdr.len); buf[1] = (uint8_t)(m->m_pkthdr.len >> 8); usbd_copy_in(pc, 0, buf, 2); usbd_m_copy_in(pc, 2, m, 0, m->m_pkthdr.len); } /* * if there's a BPF listener, bounce a copy * of this frame to him: */ BPF_MTAP(ifp, m); m_freem(m); usbd_transfer_submit(xfer); return; default: /* Error */ DPRINTFN(11, "transfer error, %s\n", usbd_errstr(error)); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void aue_tick(struct usb_ether *ue) { struct aue_softc *sc = uether_getsc(ue); struct mii_data *mii = GET_MII(sc); AUE_LOCK_ASSERT(sc, MA_OWNED); mii_tick(mii); if ((sc->sc_flags & AUE_FLAG_LINK) == 0 && mii->mii_media_status & IFM_ACTIVE && IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) { sc->sc_flags |= AUE_FLAG_LINK; aue_start(ue); } } static void aue_start(struct usb_ether *ue) { struct aue_softc *sc = uether_getsc(ue); /* * start the USB transfers, if not already started: */ usbd_transfer_start(sc->sc_xfer[AUE_INTR_DT_RD]); usbd_transfer_start(sc->sc_xfer[AUE_BULK_DT_RD]); usbd_transfer_start(sc->sc_xfer[AUE_BULK_DT_WR]); } static void aue_init(struct usb_ether *ue) { struct aue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); int i; AUE_LOCK_ASSERT(sc, MA_OWNED); /* * Cancel pending I/O */ aue_reset(sc); /* Set MAC address */ for (i = 0; i != ETHER_ADDR_LEN; i++) aue_csr_write_1(sc, AUE_PAR0 + i, IF_LLADDR(ifp)[i]); /* update promiscuous setting */ aue_setpromisc(ue); /* Load the multicast filter. */ aue_setmulti(ue); /* Enable RX and TX */ aue_csr_write_1(sc, AUE_CTL0, AUE_CTL0_RXSTAT_APPEND | AUE_CTL0_RX_ENB); AUE_SETBIT(sc, AUE_CTL0, AUE_CTL0_TX_ENB); AUE_SETBIT(sc, AUE_CTL2, AUE_CTL2_EP3_CLR); usbd_xfer_set_stall(sc->sc_xfer[AUE_BULK_DT_WR]); ifp->if_drv_flags |= IFF_DRV_RUNNING; aue_start(ue); } static void aue_setpromisc(struct usb_ether *ue) { struct aue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); AUE_LOCK_ASSERT(sc, MA_OWNED); /* if we want promiscuous mode, set the allframes bit: */ if (ifp->if_flags & IFF_PROMISC) AUE_SETBIT(sc, AUE_CTL2, AUE_CTL2_RX_PROMISC); else AUE_CLRBIT(sc, AUE_CTL2, AUE_CTL2_RX_PROMISC); } /* * Set media options. */ static int aue_ifmedia_upd(struct ifnet *ifp) { struct aue_softc *sc = ifp->if_softc; struct mii_data *mii = GET_MII(sc); struct mii_softc *miisc; int error; AUE_LOCK_ASSERT(sc, MA_OWNED); sc->sc_flags &= ~AUE_FLAG_LINK; LIST_FOREACH(miisc, &mii->mii_phys, mii_list) PHY_RESET(miisc); error = mii_mediachg(mii); return (error); } /* * Report current media status. */ static void aue_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr) { struct aue_softc *sc = ifp->if_softc; struct mii_data *mii = GET_MII(sc); AUE_LOCK(sc); mii_pollstat(mii); ifmr->ifm_active = mii->mii_media_active; ifmr->ifm_status = mii->mii_media_status; AUE_UNLOCK(sc); } /* * Stop the adapter and free any mbufs allocated to the * RX and TX lists. */ static void aue_stop(struct usb_ether *ue) { struct aue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); AUE_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags &= ~IFF_DRV_RUNNING; sc->sc_flags &= ~AUE_FLAG_LINK; /* * stop all the transfers, if not already stopped: */ usbd_transfer_stop(sc->sc_xfer[AUE_BULK_DT_WR]); usbd_transfer_stop(sc->sc_xfer[AUE_BULK_DT_RD]); usbd_transfer_stop(sc->sc_xfer[AUE_INTR_DT_RD]); aue_csr_write_1(sc, AUE_CTL0, 0); aue_csr_write_1(sc, AUE_CTL1, 0); aue_reset(sc); } Index: head/sys/dev/usb/net/if_axe.c =================================================================== --- head/sys/dev/usb/net/if_axe.c (revision 276700) +++ head/sys/dev/usb/net/if_axe.c (revision 276701) @@ -1,1503 +1,1503 @@ /*- * Copyright (c) 1997, 1998, 1999, 2000-2003 * Bill Paul . All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Bill Paul. * 4. Neither the name of the author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * ASIX Electronics AX88172/AX88178/AX88778 USB 2.0 ethernet driver. * Used in the LinkSys USB200M and various other adapters. * * Manuals available from: * http://www.asix.com.tw/datasheet/mac/Ax88172.PDF * Note: you need the manual for the AX88170 chip (USB 1.x ethernet * controller) to find the definitions for the RX control register. * http://www.asix.com.tw/datasheet/mac/Ax88170.PDF * * Written by Bill Paul * Senior Engineer * Wind River Systems */ /* * The AX88172 provides USB ethernet supports at 10 and 100Mbps. * It uses an external PHY (reference designs use a RealTek chip), * and has a 64-bit multicast hash filter. There is some information * missing from the manual which one needs to know in order to make * the chip function: * * - You must set bit 7 in the RX control register, otherwise the * chip won't receive any packets. * - You must initialize all 3 IPG registers, or you won't be able * to send any packets. * * Note that this device appears to only support loading the station * address via autload from the EEPROM (i.e. there's no way to manaully * set it). * * (Adam Weinberger wanted me to name this driver if_gir.c.) */ /* * Ax88178 and Ax88772 support backported from the OpenBSD driver. * 2007/02/12, J.R. Oldroyd, fbsd@opal.com * * Manual here: * http://www.asix.com.tw/FrootAttach/datasheet/AX88178_datasheet_Rev10.pdf * http://www.asix.com.tw/FrootAttach/datasheet/AX88772_datasheet_Rev10.pdf */ #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 "usbdevs.h" #define USB_DEBUG_VAR axe_debug #include #include #include #include /* * AXE_178_MAX_FRAME_BURST * max frame burst size for Ax88178 and Ax88772 * 0 2048 bytes * 1 4096 bytes * 2 8192 bytes * 3 16384 bytes * use the largest your system can handle without USB stalling. * * NB: 88772 parts appear to generate lots of input errors with * a 2K rx buffer and 8K is only slightly faster than 4K on an * EHCI port on a T42 so change at your own risk. */ #define AXE_178_MAX_FRAME_BURST 1 #define AXE_CSUM_FEATURES (CSUM_IP | CSUM_TCP | CSUM_UDP) #ifdef USB_DEBUG static int axe_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, axe, CTLFLAG_RW, 0, "USB axe"); -SYSCTL_INT(_hw_usb_axe, OID_AUTO, debug, CTLFLAG_RW, &axe_debug, 0, +SYSCTL_INT(_hw_usb_axe, OID_AUTO, debug, CTLFLAG_RWTUN, &axe_debug, 0, "Debug level"); #endif /* * Various supported device vendors/products. */ static const STRUCT_USB_HOST_ID axe_devs[] = { #define AXE_DEV(v,p,i) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, i) } AXE_DEV(ABOCOM, UF200, 0), AXE_DEV(ACERCM, EP1427X2, 0), AXE_DEV(APPLE, ETHERNET, AXE_FLAG_772), AXE_DEV(ASIX, AX88172, 0), AXE_DEV(ASIX, AX88178, AXE_FLAG_178), AXE_DEV(ASIX, AX88772, AXE_FLAG_772), AXE_DEV(ASIX, AX88772A, AXE_FLAG_772A), AXE_DEV(ASIX, AX88772B, AXE_FLAG_772B), AXE_DEV(ASIX, AX88772B_1, AXE_FLAG_772B), AXE_DEV(ATEN, UC210T, 0), AXE_DEV(BELKIN, F5D5055, AXE_FLAG_178), AXE_DEV(BILLIONTON, USB2AR, 0), AXE_DEV(CISCOLINKSYS, USB200MV2, AXE_FLAG_772A), AXE_DEV(COREGA, FETHER_USB2_TX, 0), AXE_DEV(DLINK, DUBE100, 0), AXE_DEV(DLINK, DUBE100B1, AXE_FLAG_772), AXE_DEV(DLINK, DUBE100C1, AXE_FLAG_772B), AXE_DEV(GOODWAY, GWUSB2E, 0), AXE_DEV(IODATA, ETGUS2, AXE_FLAG_178), AXE_DEV(JVC, MP_PRX1, 0), AXE_DEV(LENOVO, ETHERNET, AXE_FLAG_772B), AXE_DEV(LINKSYS2, USB200M, 0), AXE_DEV(LINKSYS4, USB1000, AXE_FLAG_178), AXE_DEV(LOGITEC, LAN_GTJU2A, AXE_FLAG_178), AXE_DEV(MELCO, LUAU2KTX, 0), AXE_DEV(MELCO, LUA3U2AGT, AXE_FLAG_178), AXE_DEV(NETGEAR, FA120, 0), AXE_DEV(OQO, ETHER01PLUS, AXE_FLAG_772), AXE_DEV(PLANEX3, GU1000T, AXE_FLAG_178), AXE_DEV(SITECOM, LN029, 0), AXE_DEV(SITECOMEU, LN028, AXE_FLAG_178), AXE_DEV(SYSTEMTALKS, SGCX2UL, 0), #undef AXE_DEV }; static device_probe_t axe_probe; static device_attach_t axe_attach; static device_detach_t axe_detach; static usb_callback_t axe_bulk_read_callback; static usb_callback_t axe_bulk_write_callback; static miibus_readreg_t axe_miibus_readreg; static miibus_writereg_t axe_miibus_writereg; static miibus_statchg_t axe_miibus_statchg; static uether_fn_t axe_attach_post; static uether_fn_t axe_init; static uether_fn_t axe_stop; static uether_fn_t axe_start; static uether_fn_t axe_tick; static uether_fn_t axe_setmulti; static uether_fn_t axe_setpromisc; static int axe_attach_post_sub(struct usb_ether *); static int axe_ifmedia_upd(struct ifnet *); static void axe_ifmedia_sts(struct ifnet *, struct ifmediareq *); static int axe_cmd(struct axe_softc *, int, int, int, void *); static void axe_ax88178_init(struct axe_softc *); static void axe_ax88772_init(struct axe_softc *); static void axe_ax88772_phywake(struct axe_softc *); static void axe_ax88772a_init(struct axe_softc *); static void axe_ax88772b_init(struct axe_softc *); static int axe_get_phyno(struct axe_softc *, int); static int axe_ioctl(struct ifnet *, u_long, caddr_t); static int axe_rx_frame(struct usb_ether *, struct usb_page_cache *, int); static int axe_rxeof(struct usb_ether *, struct usb_page_cache *, unsigned int offset, unsigned int, struct axe_csum_hdr *); static void axe_csum_cfg(struct usb_ether *); static const struct usb_config axe_config[AXE_N_TRANSFER] = { [AXE_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .frames = 16, .bufsize = 16 * MCLBYTES, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = axe_bulk_write_callback, .timeout = 10000, /* 10 seconds */ }, [AXE_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = 16384, /* bytes */ .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = axe_bulk_read_callback, .timeout = 0, /* no timeout */ }, }; static const struct ax88772b_mfb ax88772b_mfb_table[] = { { 0x8000, 0x8001, 2048 }, { 0x8100, 0x8147, 4096}, { 0x8200, 0x81EB, 6144}, { 0x8300, 0x83D7, 8192}, { 0x8400, 0x851E, 16384}, { 0x8500, 0x8666, 20480}, { 0x8600, 0x87AE, 24576}, { 0x8700, 0x8A3D, 32768} }; static device_method_t axe_methods[] = { /* Device interface */ DEVMETHOD(device_probe, axe_probe), DEVMETHOD(device_attach, axe_attach), DEVMETHOD(device_detach, axe_detach), /* MII interface */ DEVMETHOD(miibus_readreg, axe_miibus_readreg), DEVMETHOD(miibus_writereg, axe_miibus_writereg), DEVMETHOD(miibus_statchg, axe_miibus_statchg), DEVMETHOD_END }; static driver_t axe_driver = { .name = "axe", .methods = axe_methods, .size = sizeof(struct axe_softc), }; static devclass_t axe_devclass; DRIVER_MODULE(axe, uhub, axe_driver, axe_devclass, NULL, 0); DRIVER_MODULE(miibus, axe, miibus_driver, miibus_devclass, 0, 0); MODULE_DEPEND(axe, uether, 1, 1, 1); MODULE_DEPEND(axe, usb, 1, 1, 1); MODULE_DEPEND(axe, ether, 1, 1, 1); MODULE_DEPEND(axe, miibus, 1, 1, 1); MODULE_VERSION(axe, 1); static const struct usb_ether_methods axe_ue_methods = { .ue_attach_post = axe_attach_post, .ue_attach_post_sub = axe_attach_post_sub, .ue_start = axe_start, .ue_init = axe_init, .ue_stop = axe_stop, .ue_tick = axe_tick, .ue_setmulti = axe_setmulti, .ue_setpromisc = axe_setpromisc, .ue_mii_upd = axe_ifmedia_upd, .ue_mii_sts = axe_ifmedia_sts, }; static int axe_cmd(struct axe_softc *sc, int cmd, int index, int val, void *buf) { struct usb_device_request req; usb_error_t err; AXE_LOCK_ASSERT(sc, MA_OWNED); req.bmRequestType = (AXE_CMD_IS_WRITE(cmd) ? UT_WRITE_VENDOR_DEVICE : UT_READ_VENDOR_DEVICE); req.bRequest = AXE_CMD_CMD(cmd); USETW(req.wValue, val); USETW(req.wIndex, index); USETW(req.wLength, AXE_CMD_LEN(cmd)); err = uether_do_request(&sc->sc_ue, &req, buf, 1000); return (err); } static int axe_miibus_readreg(device_t dev, int phy, int reg) { struct axe_softc *sc = device_get_softc(dev); uint16_t val; int locked; locked = mtx_owned(&sc->sc_mtx); if (!locked) AXE_LOCK(sc); axe_cmd(sc, AXE_CMD_MII_OPMODE_SW, 0, 0, NULL); axe_cmd(sc, AXE_CMD_MII_READ_REG, reg, phy, &val); axe_cmd(sc, AXE_CMD_MII_OPMODE_HW, 0, 0, NULL); val = le16toh(val); if (AXE_IS_772(sc) && reg == MII_BMSR) { /* * BMSR of AX88772 indicates that it supports extended * capability but the extended status register is * revered for embedded ethernet PHY. So clear the * extended capability bit of BMSR. */ val &= ~BMSR_EXTCAP; } if (!locked) AXE_UNLOCK(sc); return (val); } static int axe_miibus_writereg(device_t dev, int phy, int reg, int val) { struct axe_softc *sc = device_get_softc(dev); int locked; val = htole32(val); locked = mtx_owned(&sc->sc_mtx); if (!locked) AXE_LOCK(sc); axe_cmd(sc, AXE_CMD_MII_OPMODE_SW, 0, 0, NULL); axe_cmd(sc, AXE_CMD_MII_WRITE_REG, reg, phy, &val); axe_cmd(sc, AXE_CMD_MII_OPMODE_HW, 0, 0, NULL); if (!locked) AXE_UNLOCK(sc); return (0); } static void axe_miibus_statchg(device_t dev) { struct axe_softc *sc = device_get_softc(dev); struct mii_data *mii = GET_MII(sc); struct ifnet *ifp; uint16_t val; int err, locked; locked = mtx_owned(&sc->sc_mtx); if (!locked) AXE_LOCK(sc); ifp = uether_getifp(&sc->sc_ue); if (mii == NULL || ifp == NULL || (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) goto done; sc->sc_flags &= ~AXE_FLAG_LINK; if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) == (IFM_ACTIVE | IFM_AVALID)) { switch (IFM_SUBTYPE(mii->mii_media_active)) { case IFM_10_T: case IFM_100_TX: sc->sc_flags |= AXE_FLAG_LINK; break; case IFM_1000_T: if ((sc->sc_flags & AXE_FLAG_178) == 0) break; sc->sc_flags |= AXE_FLAG_LINK; break; default: break; } } /* Lost link, do nothing. */ if ((sc->sc_flags & AXE_FLAG_LINK) == 0) goto done; val = 0; if ((IFM_OPTIONS(mii->mii_media_active) & IFM_FDX) != 0) { val |= AXE_MEDIA_FULL_DUPLEX; if (AXE_IS_178_FAMILY(sc)) { if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_TXPAUSE) != 0) val |= AXE_178_MEDIA_TXFLOW_CONTROL_EN; if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_RXPAUSE) != 0) val |= AXE_178_MEDIA_RXFLOW_CONTROL_EN; } } if (AXE_IS_178_FAMILY(sc)) { val |= AXE_178_MEDIA_RX_EN | AXE_178_MEDIA_MAGIC; if ((sc->sc_flags & AXE_FLAG_178) != 0) val |= AXE_178_MEDIA_ENCK; switch (IFM_SUBTYPE(mii->mii_media_active)) { case IFM_1000_T: val |= AXE_178_MEDIA_GMII | AXE_178_MEDIA_ENCK; break; case IFM_100_TX: val |= AXE_178_MEDIA_100TX; break; case IFM_10_T: /* doesn't need to be handled */ break; } } err = axe_cmd(sc, AXE_CMD_WRITE_MEDIA, 0, val, NULL); if (err) device_printf(dev, "media change failed, error %d\n", err); done: if (!locked) AXE_UNLOCK(sc); } /* * Set media options. */ static int axe_ifmedia_upd(struct ifnet *ifp) { struct axe_softc *sc = ifp->if_softc; struct mii_data *mii = GET_MII(sc); struct mii_softc *miisc; int error; AXE_LOCK_ASSERT(sc, MA_OWNED); LIST_FOREACH(miisc, &mii->mii_phys, mii_list) PHY_RESET(miisc); error = mii_mediachg(mii); return (error); } /* * Report current media status. */ static void axe_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr) { struct axe_softc *sc = ifp->if_softc; struct mii_data *mii = GET_MII(sc); AXE_LOCK(sc); mii_pollstat(mii); ifmr->ifm_active = mii->mii_media_active; ifmr->ifm_status = mii->mii_media_status; AXE_UNLOCK(sc); } static void axe_setmulti(struct usb_ether *ue) { struct axe_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); struct ifmultiaddr *ifma; uint32_t h = 0; uint16_t rxmode; uint8_t hashtbl[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; AXE_LOCK_ASSERT(sc, MA_OWNED); axe_cmd(sc, AXE_CMD_RXCTL_READ, 0, 0, &rxmode); rxmode = le16toh(rxmode); if (ifp->if_flags & (IFF_ALLMULTI | IFF_PROMISC)) { rxmode |= AXE_RXCMD_ALLMULTI; axe_cmd(sc, AXE_CMD_RXCTL_WRITE, 0, rxmode, NULL); return; } rxmode &= ~AXE_RXCMD_ALLMULTI; if_maddr_rlock(ifp); TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) { if (ifma->ifma_addr->sa_family != AF_LINK) continue; h = ether_crc32_be(LLADDR((struct sockaddr_dl *) ifma->ifma_addr), ETHER_ADDR_LEN) >> 26; hashtbl[h / 8] |= 1 << (h % 8); } if_maddr_runlock(ifp); axe_cmd(sc, AXE_CMD_WRITE_MCAST, 0, 0, (void *)&hashtbl); axe_cmd(sc, AXE_CMD_RXCTL_WRITE, 0, rxmode, NULL); } static int axe_get_phyno(struct axe_softc *sc, int sel) { int phyno; switch (AXE_PHY_TYPE(sc->sc_phyaddrs[sel])) { case PHY_TYPE_100_HOME: case PHY_TYPE_GIG: phyno = AXE_PHY_NO(sc->sc_phyaddrs[sel]); break; case PHY_TYPE_SPECIAL: /* FALLTHROUGH */ case PHY_TYPE_RSVD: /* FALLTHROUGH */ case PHY_TYPE_NON_SUP: /* FALLTHROUGH */ default: phyno = -1; break; } return (phyno); } #define AXE_GPIO_WRITE(x, y) do { \ axe_cmd(sc, AXE_CMD_WRITE_GPIO, 0, (x), NULL); \ uether_pause(ue, (y)); \ } while (0) static void axe_ax88178_init(struct axe_softc *sc) { struct usb_ether *ue; int gpio0, ledmode, phymode; uint16_t eeprom, val; ue = &sc->sc_ue; axe_cmd(sc, AXE_CMD_SROM_WR_ENABLE, 0, 0, NULL); /* XXX magic */ axe_cmd(sc, AXE_CMD_SROM_READ, 0, 0x0017, &eeprom); eeprom = le16toh(eeprom); axe_cmd(sc, AXE_CMD_SROM_WR_DISABLE, 0, 0, NULL); /* if EEPROM is invalid we have to use to GPIO0 */ if (eeprom == 0xffff) { phymode = AXE_PHY_MODE_MARVELL; gpio0 = 1; ledmode = 0; } else { phymode = eeprom & 0x7f; gpio0 = (eeprom & 0x80) ? 0 : 1; ledmode = eeprom >> 8; } if (bootverbose) device_printf(sc->sc_ue.ue_dev, "EEPROM data : 0x%04x, phymode : 0x%02x\n", eeprom, phymode); /* Program GPIOs depending on PHY hardware. */ switch (phymode) { case AXE_PHY_MODE_MARVELL: if (gpio0 == 1) { AXE_GPIO_WRITE(AXE_GPIO_RELOAD_EEPROM | AXE_GPIO0_EN, hz / 32); AXE_GPIO_WRITE(AXE_GPIO0_EN | AXE_GPIO2 | AXE_GPIO2_EN, hz / 32); AXE_GPIO_WRITE(AXE_GPIO0_EN | AXE_GPIO2_EN, hz / 4); AXE_GPIO_WRITE(AXE_GPIO0_EN | AXE_GPIO2 | AXE_GPIO2_EN, hz / 32); } else { AXE_GPIO_WRITE(AXE_GPIO_RELOAD_EEPROM | AXE_GPIO1 | AXE_GPIO1_EN, hz / 3); if (ledmode == 1) { AXE_GPIO_WRITE(AXE_GPIO1_EN, hz / 3); AXE_GPIO_WRITE(AXE_GPIO1 | AXE_GPIO1_EN, hz / 3); } else { AXE_GPIO_WRITE(AXE_GPIO1 | AXE_GPIO1_EN | AXE_GPIO2 | AXE_GPIO2_EN, hz / 32); AXE_GPIO_WRITE(AXE_GPIO1 | AXE_GPIO1_EN | AXE_GPIO2_EN, hz / 4); AXE_GPIO_WRITE(AXE_GPIO1 | AXE_GPIO1_EN | AXE_GPIO2 | AXE_GPIO2_EN, hz / 32); } } break; case AXE_PHY_MODE_CICADA: case AXE_PHY_MODE_CICADA_V2: case AXE_PHY_MODE_CICADA_V2_ASIX: if (gpio0 == 1) AXE_GPIO_WRITE(AXE_GPIO_RELOAD_EEPROM | AXE_GPIO0 | AXE_GPIO0_EN, hz / 32); else AXE_GPIO_WRITE(AXE_GPIO_RELOAD_EEPROM | AXE_GPIO1 | AXE_GPIO1_EN, hz / 32); break; case AXE_PHY_MODE_AGERE: AXE_GPIO_WRITE(AXE_GPIO_RELOAD_EEPROM | AXE_GPIO1 | AXE_GPIO1_EN, hz / 32); AXE_GPIO_WRITE(AXE_GPIO1 | AXE_GPIO1_EN | AXE_GPIO2 | AXE_GPIO2_EN, hz / 32); AXE_GPIO_WRITE(AXE_GPIO1 | AXE_GPIO1_EN | AXE_GPIO2_EN, hz / 4); AXE_GPIO_WRITE(AXE_GPIO1 | AXE_GPIO1_EN | AXE_GPIO2 | AXE_GPIO2_EN, hz / 32); break; case AXE_PHY_MODE_REALTEK_8211CL: case AXE_PHY_MODE_REALTEK_8211BN: case AXE_PHY_MODE_REALTEK_8251CL: val = gpio0 == 1 ? AXE_GPIO0 | AXE_GPIO0_EN : AXE_GPIO1 | AXE_GPIO1_EN; AXE_GPIO_WRITE(val, hz / 32); AXE_GPIO_WRITE(val | AXE_GPIO2 | AXE_GPIO2_EN, hz / 32); AXE_GPIO_WRITE(val | AXE_GPIO2_EN, hz / 4); AXE_GPIO_WRITE(val | AXE_GPIO2 | AXE_GPIO2_EN, hz / 32); if (phymode == AXE_PHY_MODE_REALTEK_8211CL) { axe_miibus_writereg(ue->ue_dev, sc->sc_phyno, 0x1F, 0x0005); axe_miibus_writereg(ue->ue_dev, sc->sc_phyno, 0x0C, 0x0000); val = axe_miibus_readreg(ue->ue_dev, sc->sc_phyno, 0x0001); axe_miibus_writereg(ue->ue_dev, sc->sc_phyno, 0x01, val | 0x0080); axe_miibus_writereg(ue->ue_dev, sc->sc_phyno, 0x1F, 0x0000); } break; default: /* Unknown PHY model or no need to program GPIOs. */ break; } /* soft reset */ axe_cmd(sc, AXE_CMD_SW_RESET_REG, 0, AXE_SW_RESET_CLEAR, NULL); uether_pause(ue, hz / 4); axe_cmd(sc, AXE_CMD_SW_RESET_REG, 0, AXE_SW_RESET_PRL | AXE_178_RESET_MAGIC, NULL); uether_pause(ue, hz / 4); /* Enable MII/GMII/RGMII interface to work with external PHY. */ axe_cmd(sc, AXE_CMD_SW_PHY_SELECT, 0, 0, NULL); uether_pause(ue, hz / 4); axe_cmd(sc, AXE_CMD_RXCTL_WRITE, 0, 0, NULL); } static void axe_ax88772_init(struct axe_softc *sc) { axe_cmd(sc, AXE_CMD_WRITE_GPIO, 0, 0x00b0, NULL); uether_pause(&sc->sc_ue, hz / 16); if (sc->sc_phyno == AXE_772_PHY_NO_EPHY) { /* ask for the embedded PHY */ axe_cmd(sc, AXE_CMD_SW_PHY_SELECT, 0, 0x01, NULL); uether_pause(&sc->sc_ue, hz / 64); /* power down and reset state, pin reset state */ axe_cmd(sc, AXE_CMD_SW_RESET_REG, 0, AXE_SW_RESET_CLEAR, NULL); uether_pause(&sc->sc_ue, hz / 16); /* power down/reset state, pin operating state */ axe_cmd(sc, AXE_CMD_SW_RESET_REG, 0, AXE_SW_RESET_IPPD | AXE_SW_RESET_PRL, NULL); uether_pause(&sc->sc_ue, hz / 4); /* power up, reset */ axe_cmd(sc, AXE_CMD_SW_RESET_REG, 0, AXE_SW_RESET_PRL, NULL); /* power up, operating */ axe_cmd(sc, AXE_CMD_SW_RESET_REG, 0, AXE_SW_RESET_IPRL | AXE_SW_RESET_PRL, NULL); } else { /* ask for external PHY */ axe_cmd(sc, AXE_CMD_SW_PHY_SELECT, 0, 0x00, NULL); uether_pause(&sc->sc_ue, hz / 64); /* power down internal PHY */ axe_cmd(sc, AXE_CMD_SW_RESET_REG, 0, AXE_SW_RESET_IPPD | AXE_SW_RESET_PRL, NULL); } uether_pause(&sc->sc_ue, hz / 4); axe_cmd(sc, AXE_CMD_RXCTL_WRITE, 0, 0, NULL); } static void axe_ax88772_phywake(struct axe_softc *sc) { struct usb_ether *ue; ue = &sc->sc_ue; if (sc->sc_phyno == AXE_772_PHY_NO_EPHY) { /* Manually select internal(embedded) PHY - MAC mode. */ axe_cmd(sc, AXE_CMD_SW_PHY_SELECT, 0, AXE_SW_PHY_SELECT_SS_ENB | AXE_SW_PHY_SELECT_EMBEDDED | AXE_SW_PHY_SELECT_SS_MII, NULL); uether_pause(&sc->sc_ue, hz / 32); } else { /* * Manually select external PHY - MAC mode. * Reverse MII/RMII is for AX88772A PHY mode. */ axe_cmd(sc, AXE_CMD_SW_PHY_SELECT, 0, AXE_SW_PHY_SELECT_SS_ENB | AXE_SW_PHY_SELECT_EXT | AXE_SW_PHY_SELECT_SS_MII, NULL); uether_pause(&sc->sc_ue, hz / 32); } /* Take PHY out of power down. */ axe_cmd(sc, AXE_CMD_SW_RESET_REG, 0, AXE_SW_RESET_IPPD | AXE_SW_RESET_IPRL, NULL); uether_pause(&sc->sc_ue, hz / 4); axe_cmd(sc, AXE_CMD_SW_RESET_REG, 0, AXE_SW_RESET_IPRL, NULL); uether_pause(&sc->sc_ue, hz); axe_cmd(sc, AXE_CMD_SW_RESET_REG, 0, AXE_SW_RESET_CLEAR, NULL); uether_pause(&sc->sc_ue, hz / 32); axe_cmd(sc, AXE_CMD_SW_RESET_REG, 0, AXE_SW_RESET_IPRL, NULL); uether_pause(&sc->sc_ue, hz / 32); } static void axe_ax88772a_init(struct axe_softc *sc) { struct usb_ether *ue; ue = &sc->sc_ue; /* Reload EEPROM. */ AXE_GPIO_WRITE(AXE_GPIO_RELOAD_EEPROM, hz / 32); axe_ax88772_phywake(sc); /* Stop MAC. */ axe_cmd(sc, AXE_CMD_RXCTL_WRITE, 0, 0, NULL); } static void axe_ax88772b_init(struct axe_softc *sc) { struct usb_ether *ue; uint16_t eeprom; uint8_t *eaddr; int i; ue = &sc->sc_ue; /* Reload EEPROM. */ AXE_GPIO_WRITE(AXE_GPIO_RELOAD_EEPROM, hz / 32); /* * Save PHY power saving configuration(high byte) and * clear EEPROM checksum value(low byte). */ axe_cmd(sc, AXE_CMD_SROM_READ, 0, AXE_EEPROM_772B_PHY_PWRCFG, &eeprom); sc->sc_pwrcfg = le16toh(eeprom) & 0xFF00; /* * Auto-loaded default station address from internal ROM is * 00:00:00:00:00:00 such that an explicit access to EEPROM * is required to get real station address. */ eaddr = ue->ue_eaddr; for (i = 0; i < ETHER_ADDR_LEN / 2; i++) { axe_cmd(sc, AXE_CMD_SROM_READ, 0, AXE_EEPROM_772B_NODE_ID + i, &eeprom); eeprom = le16toh(eeprom); *eaddr++ = (uint8_t)(eeprom & 0xFF); *eaddr++ = (uint8_t)((eeprom >> 8) & 0xFF); } /* Wakeup PHY. */ axe_ax88772_phywake(sc); /* Stop MAC. */ axe_cmd(sc, AXE_CMD_RXCTL_WRITE, 0, 0, NULL); } #undef AXE_GPIO_WRITE static void axe_reset(struct axe_softc *sc) { struct usb_config_descriptor *cd; usb_error_t err; cd = usbd_get_config_descriptor(sc->sc_ue.ue_udev); err = usbd_req_set_config(sc->sc_ue.ue_udev, &sc->sc_mtx, cd->bConfigurationValue); if (err) DPRINTF("reset failed (ignored)\n"); /* Wait a little while for the chip to get its brains in order. */ uether_pause(&sc->sc_ue, hz / 100); /* Reinitialize controller to achieve full reset. */ if (sc->sc_flags & AXE_FLAG_178) axe_ax88178_init(sc); else if (sc->sc_flags & AXE_FLAG_772) axe_ax88772_init(sc); else if (sc->sc_flags & AXE_FLAG_772A) axe_ax88772a_init(sc); else if (sc->sc_flags & AXE_FLAG_772B) axe_ax88772b_init(sc); } static void axe_attach_post(struct usb_ether *ue) { struct axe_softc *sc = uether_getsc(ue); /* * Load PHY indexes first. Needed by axe_xxx_init(). */ axe_cmd(sc, AXE_CMD_READ_PHYID, 0, 0, sc->sc_phyaddrs); if (bootverbose) device_printf(sc->sc_ue.ue_dev, "PHYADDR 0x%02x:0x%02x\n", sc->sc_phyaddrs[0], sc->sc_phyaddrs[1]); sc->sc_phyno = axe_get_phyno(sc, AXE_PHY_SEL_PRI); if (sc->sc_phyno == -1) sc->sc_phyno = axe_get_phyno(sc, AXE_PHY_SEL_SEC); if (sc->sc_phyno == -1) { device_printf(sc->sc_ue.ue_dev, "no valid PHY address found, assuming PHY address 0\n"); sc->sc_phyno = 0; } /* Initialize controller and get station address. */ if (sc->sc_flags & AXE_FLAG_178) { axe_ax88178_init(sc); axe_cmd(sc, AXE_178_CMD_READ_NODEID, 0, 0, ue->ue_eaddr); } else if (sc->sc_flags & AXE_FLAG_772) { axe_ax88772_init(sc); axe_cmd(sc, AXE_178_CMD_READ_NODEID, 0, 0, ue->ue_eaddr); } else if (sc->sc_flags & AXE_FLAG_772A) { axe_ax88772a_init(sc); axe_cmd(sc, AXE_178_CMD_READ_NODEID, 0, 0, ue->ue_eaddr); } else if (sc->sc_flags & AXE_FLAG_772B) { axe_ax88772b_init(sc); } else axe_cmd(sc, AXE_172_CMD_READ_NODEID, 0, 0, ue->ue_eaddr); /* * Fetch IPG values. */ if (sc->sc_flags & (AXE_FLAG_772A | AXE_FLAG_772B)) { /* Set IPG values. */ sc->sc_ipgs[0] = 0x15; sc->sc_ipgs[1] = 0x16; sc->sc_ipgs[2] = 0x1A; } else axe_cmd(sc, AXE_CMD_READ_IPG012, 0, 0, sc->sc_ipgs); } static int axe_attach_post_sub(struct usb_ether *ue) { struct axe_softc *sc; struct ifnet *ifp; u_int adv_pause; int error; sc = uether_getsc(ue); ifp = ue->ue_ifp; ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; ifp->if_start = uether_start; ifp->if_ioctl = axe_ioctl; ifp->if_init = uether_init; IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen); ifp->if_snd.ifq_drv_maxlen = ifqmaxlen; IFQ_SET_READY(&ifp->if_snd); if (AXE_IS_178_FAMILY(sc)) ifp->if_capabilities |= IFCAP_VLAN_MTU; if (sc->sc_flags & AXE_FLAG_772B) { ifp->if_capabilities |= IFCAP_TXCSUM | IFCAP_RXCSUM; ifp->if_hwassist = AXE_CSUM_FEATURES; /* * Checksum offloading of AX88772B also works with VLAN * tagged frames but there is no way to take advantage * of the feature because vlan(4) assumes * IFCAP_VLAN_HWTAGGING is prerequisite condition to * support checksum offloading with VLAN. VLAN hardware * tagging support of AX88772B is very limited so it's * not possible to announce IFCAP_VLAN_HWTAGGING. */ } ifp->if_capenable = ifp->if_capabilities; if (sc->sc_flags & (AXE_FLAG_772A | AXE_FLAG_772B | AXE_FLAG_178)) adv_pause = MIIF_DOPAUSE; else adv_pause = 0; mtx_lock(&Giant); error = mii_attach(ue->ue_dev, &ue->ue_miibus, ifp, uether_ifmedia_upd, ue->ue_methods->ue_mii_sts, BMSR_DEFCAPMASK, sc->sc_phyno, MII_OFFSET_ANY, adv_pause); mtx_unlock(&Giant); return (error); } /* * Probe for a AX88172 chip. */ static int axe_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != AXE_CONFIG_IDX) return (ENXIO); if (uaa->info.bIfaceIndex != AXE_IFACE_IDX) return (ENXIO); return (usbd_lookup_id_by_uaa(axe_devs, sizeof(axe_devs), uaa)); } /* * Attach the interface. Allocate softc structures, do ifmedia * setup and ethernet/BPF attach. */ static int axe_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct axe_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; uint8_t iface_index; int error; sc->sc_flags = USB_GET_DRIVER_INFO(uaa); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF); iface_index = AXE_IFACE_IDX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, axe_config, AXE_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(dev, "allocating USB transfers failed\n"); goto detach; } ue->ue_sc = sc; ue->ue_dev = dev; ue->ue_udev = uaa->device; ue->ue_mtx = &sc->sc_mtx; ue->ue_methods = &axe_ue_methods; error = uether_ifattach(ue); if (error) { device_printf(dev, "could not attach interface\n"); goto detach; } return (0); /* success */ detach: axe_detach(dev); return (ENXIO); /* failure */ } static int axe_detach(device_t dev) { struct axe_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; usbd_transfer_unsetup(sc->sc_xfer, AXE_N_TRANSFER); uether_ifdetach(ue); mtx_destroy(&sc->sc_mtx); return (0); } #if (AXE_BULK_BUF_SIZE >= 0x10000) #error "Please update axe_bulk_read_callback()!" #endif static void axe_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct axe_softc *sc = usbd_xfer_softc(xfer); struct usb_ether *ue = &sc->sc_ue; struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); axe_rx_frame(ue, pc, actlen); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); uether_rxflush(ue); return; default: /* Error */ DPRINTF("bulk read error, %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static int axe_rx_frame(struct usb_ether *ue, struct usb_page_cache *pc, int actlen) { struct axe_softc *sc; struct axe_sframe_hdr hdr; struct axe_csum_hdr csum_hdr; int error, len, pos; sc = uether_getsc(ue); pos = 0; len = 0; error = 0; if ((sc->sc_flags & AXE_FLAG_STD_FRAME) != 0) { while (pos < actlen) { if ((int)(pos + sizeof(hdr)) > actlen) { /* too little data */ error = EINVAL; break; } usbd_copy_out(pc, pos, &hdr, sizeof(hdr)); if ((hdr.len ^ hdr.ilen) != sc->sc_lenmask) { /* we lost sync */ error = EINVAL; break; } pos += sizeof(hdr); len = le16toh(hdr.len); if (pos + len > actlen) { /* invalid length */ error = EINVAL; break; } axe_rxeof(ue, pc, pos, len, NULL); pos += len + (len % 2); } } else if ((sc->sc_flags & AXE_FLAG_CSUM_FRAME) != 0) { while (pos < actlen) { if ((int)(pos + sizeof(csum_hdr)) > actlen) { /* too little data */ error = EINVAL; break; } usbd_copy_out(pc, pos, &csum_hdr, sizeof(csum_hdr)); csum_hdr.len = le16toh(csum_hdr.len); csum_hdr.ilen = le16toh(csum_hdr.ilen); csum_hdr.cstatus = le16toh(csum_hdr.cstatus); if ((AXE_CSUM_RXBYTES(csum_hdr.len) ^ AXE_CSUM_RXBYTES(csum_hdr.ilen)) != sc->sc_lenmask) { /* we lost sync */ error = EINVAL; break; } /* * Get total transferred frame length including * checksum header. The length should be multiple * of 4. */ len = sizeof(csum_hdr) + AXE_CSUM_RXBYTES(csum_hdr.len); len = (len + 3) & ~3; if (pos + len > actlen) { /* invalid length */ error = EINVAL; break; } axe_rxeof(ue, pc, pos + sizeof(csum_hdr), AXE_CSUM_RXBYTES(csum_hdr.len), &csum_hdr); pos += len; } } else axe_rxeof(ue, pc, 0, actlen, NULL); if (error != 0) if_inc_counter(ue->ue_ifp, IFCOUNTER_IERRORS, 1); return (error); } static int axe_rxeof(struct usb_ether *ue, struct usb_page_cache *pc, unsigned int offset, unsigned int len, struct axe_csum_hdr *csum_hdr) { struct ifnet *ifp = ue->ue_ifp; struct mbuf *m; if (len < ETHER_HDR_LEN || len > MCLBYTES - ETHER_ALIGN) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); return (EINVAL); } m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); if (m == NULL) { if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1); return (ENOMEM); } m->m_len = m->m_pkthdr.len = MCLBYTES; m_adj(m, ETHER_ALIGN); usbd_copy_out(pc, offset, mtod(m, uint8_t *), len); if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1); m->m_pkthdr.rcvif = ifp; m->m_pkthdr.len = m->m_len = len; if (csum_hdr != NULL && csum_hdr->cstatus & AXE_CSUM_HDR_L3_TYPE_IPV4) { if ((csum_hdr->cstatus & (AXE_CSUM_HDR_L4_CSUM_ERR | AXE_CSUM_HDR_L3_CSUM_ERR)) == 0) { m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED | CSUM_IP_VALID; if ((csum_hdr->cstatus & AXE_CSUM_HDR_L4_TYPE_MASK) == AXE_CSUM_HDR_L4_TYPE_TCP || (csum_hdr->cstatus & AXE_CSUM_HDR_L4_TYPE_MASK) == AXE_CSUM_HDR_L4_TYPE_UDP) { m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR; m->m_pkthdr.csum_data = 0xffff; } } } _IF_ENQUEUE(&ue->ue_rxq, m); return (0); } #if ((AXE_BULK_BUF_SIZE >= 0x10000) || (AXE_BULK_BUF_SIZE < (MCLBYTES+4))) #error "Please update axe_bulk_write_callback()!" #endif static void axe_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct axe_softc *sc = usbd_xfer_softc(xfer); struct axe_sframe_hdr hdr; struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct usb_page_cache *pc; struct mbuf *m; int nframes, pos; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(11, "transfer complete\n"); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: if ((sc->sc_flags & AXE_FLAG_LINK) == 0 || (ifp->if_drv_flags & IFF_DRV_OACTIVE) != 0) { /* * Don't send anything if there is no link or * controller is busy. */ return; } for (nframes = 0; nframes < 16 && !IFQ_DRV_IS_EMPTY(&ifp->if_snd); nframes++) { IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; usbd_xfer_set_frame_offset(xfer, nframes * MCLBYTES, nframes); pos = 0; pc = usbd_xfer_get_frame(xfer, nframes); if (AXE_IS_178_FAMILY(sc)) { hdr.len = htole16(m->m_pkthdr.len); hdr.ilen = ~hdr.len; /* * If upper stack computed checksum, driver * should tell controller not to insert * computed checksum for checksum offloading * enabled controller. */ if (ifp->if_capabilities & IFCAP_TXCSUM) { if ((m->m_pkthdr.csum_flags & AXE_CSUM_FEATURES) != 0) hdr.len |= htole16( AXE_TX_CSUM_PSEUDO_HDR); else hdr.len |= htole16( AXE_TX_CSUM_DIS); } usbd_copy_in(pc, pos, &hdr, sizeof(hdr)); pos += sizeof(hdr); usbd_m_copy_in(pc, pos, m, 0, m->m_pkthdr.len); pos += m->m_pkthdr.len; if ((pos % 512) == 0) { hdr.len = 0; hdr.ilen = 0xffff; usbd_copy_in(pc, pos, &hdr, sizeof(hdr)); pos += sizeof(hdr); } } else { usbd_m_copy_in(pc, pos, m, 0, m->m_pkthdr.len); pos += m->m_pkthdr.len; } /* * XXX * Update TX packet counter here. This is not * correct way but it seems that there is no way * to know how many packets are sent at the end * of transfer because controller combines * multiple writes into single one if there is * room in TX buffer of controller. */ if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* * if there's a BPF listener, bounce a copy * of this frame to him: */ BPF_MTAP(ifp, m); m_freem(m); /* Set frame length. */ usbd_xfer_set_frame_len(xfer, nframes, pos); } if (nframes != 0) { usbd_xfer_set_frames(xfer, nframes); usbd_transfer_submit(xfer); ifp->if_drv_flags |= IFF_DRV_OACTIVE; } return; /* NOTREACHED */ default: /* Error */ DPRINTFN(11, "transfer error, %s\n", usbd_errstr(error)); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void axe_tick(struct usb_ether *ue) { struct axe_softc *sc = uether_getsc(ue); struct mii_data *mii = GET_MII(sc); AXE_LOCK_ASSERT(sc, MA_OWNED); mii_tick(mii); if ((sc->sc_flags & AXE_FLAG_LINK) == 0) { axe_miibus_statchg(ue->ue_dev); if ((sc->sc_flags & AXE_FLAG_LINK) != 0) axe_start(ue); } } static void axe_start(struct usb_ether *ue) { struct axe_softc *sc = uether_getsc(ue); /* * start the USB transfers, if not already started: */ usbd_transfer_start(sc->sc_xfer[AXE_BULK_DT_RD]); usbd_transfer_start(sc->sc_xfer[AXE_BULK_DT_WR]); } static void axe_csum_cfg(struct usb_ether *ue) { struct axe_softc *sc; struct ifnet *ifp; uint16_t csum1, csum2; sc = uether_getsc(ue); AXE_LOCK_ASSERT(sc, MA_OWNED); if ((sc->sc_flags & AXE_FLAG_772B) != 0) { ifp = uether_getifp(ue); csum1 = 0; csum2 = 0; if ((ifp->if_capenable & IFCAP_TXCSUM) != 0) csum1 |= AXE_TXCSUM_IP | AXE_TXCSUM_TCP | AXE_TXCSUM_UDP; axe_cmd(sc, AXE_772B_CMD_WRITE_TXCSUM, csum2, csum1, NULL); csum1 = 0; csum2 = 0; if ((ifp->if_capenable & IFCAP_RXCSUM) != 0) csum1 |= AXE_RXCSUM_IP | AXE_RXCSUM_IPVE | AXE_RXCSUM_TCP | AXE_RXCSUM_UDP | AXE_RXCSUM_ICMP | AXE_RXCSUM_IGMP; axe_cmd(sc, AXE_772B_CMD_WRITE_RXCSUM, csum2, csum1, NULL); } } static void axe_init(struct usb_ether *ue) { struct axe_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); uint16_t rxmode; AXE_LOCK_ASSERT(sc, MA_OWNED); if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0) return; /* Cancel pending I/O */ axe_stop(ue); axe_reset(sc); /* Set MAC address and transmitter IPG values. */ if (AXE_IS_178_FAMILY(sc)) { axe_cmd(sc, AXE_178_CMD_WRITE_NODEID, 0, 0, IF_LLADDR(ifp)); axe_cmd(sc, AXE_178_CMD_WRITE_IPG012, sc->sc_ipgs[2], (sc->sc_ipgs[1] << 8) | (sc->sc_ipgs[0]), NULL); } else { axe_cmd(sc, AXE_172_CMD_WRITE_NODEID, 0, 0, IF_LLADDR(ifp)); axe_cmd(sc, AXE_172_CMD_WRITE_IPG0, 0, sc->sc_ipgs[0], NULL); axe_cmd(sc, AXE_172_CMD_WRITE_IPG1, 0, sc->sc_ipgs[1], NULL); axe_cmd(sc, AXE_172_CMD_WRITE_IPG2, 0, sc->sc_ipgs[2], NULL); } if (AXE_IS_178_FAMILY(sc)) { sc->sc_flags &= ~(AXE_FLAG_STD_FRAME | AXE_FLAG_CSUM_FRAME); if ((sc->sc_flags & AXE_FLAG_772B) != 0 && (ifp->if_capenable & IFCAP_RXCSUM) != 0) { sc->sc_lenmask = AXE_CSUM_HDR_LEN_MASK; sc->sc_flags |= AXE_FLAG_CSUM_FRAME; } else { sc->sc_lenmask = AXE_HDR_LEN_MASK; sc->sc_flags |= AXE_FLAG_STD_FRAME; } } /* Configure TX/RX checksum offloading. */ axe_csum_cfg(ue); if (sc->sc_flags & AXE_FLAG_772B) { /* AX88772B uses different maximum frame burst configuration. */ axe_cmd(sc, AXE_772B_CMD_RXCTL_WRITE_CFG, ax88772b_mfb_table[AX88772B_MFB_16K].threshold, ax88772b_mfb_table[AX88772B_MFB_16K].byte_cnt, NULL); } /* Enable receiver, set RX mode. */ rxmode = (AXE_RXCMD_MULTICAST | AXE_RXCMD_ENABLE); if (AXE_IS_178_FAMILY(sc)) { if (sc->sc_flags & AXE_FLAG_772B) { /* * Select RX header format type 1. Aligning IP * header on 4 byte boundary is not needed when * checksum offloading feature is not used * because we always copy the received frame in * RX handler. When RX checksum offloading is * active, aligning IP header is required to * reflect actual frame length including RX * header size. */ rxmode |= AXE_772B_RXCMD_HDR_TYPE_1; if ((ifp->if_capenable & IFCAP_RXCSUM) != 0) rxmode |= AXE_772B_RXCMD_IPHDR_ALIGN; } else { /* * Default Rx buffer size is too small to get * maximum performance. */ rxmode |= AXE_178_RXCMD_MFB_16384; } } else { rxmode |= AXE_172_RXCMD_UNICAST; } /* If we want promiscuous mode, set the allframes bit. */ if (ifp->if_flags & IFF_PROMISC) rxmode |= AXE_RXCMD_PROMISC; if (ifp->if_flags & IFF_BROADCAST) rxmode |= AXE_RXCMD_BROADCAST; axe_cmd(sc, AXE_CMD_RXCTL_WRITE, 0, rxmode, NULL); /* Load the multicast filter. */ axe_setmulti(ue); usbd_xfer_set_stall(sc->sc_xfer[AXE_BULK_DT_WR]); ifp->if_drv_flags |= IFF_DRV_RUNNING; /* Switch to selected media. */ axe_ifmedia_upd(ifp); } static void axe_setpromisc(struct usb_ether *ue) { struct axe_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); uint16_t rxmode; axe_cmd(sc, AXE_CMD_RXCTL_READ, 0, 0, &rxmode); rxmode = le16toh(rxmode); if (ifp->if_flags & IFF_PROMISC) { rxmode |= AXE_RXCMD_PROMISC; } else { rxmode &= ~AXE_RXCMD_PROMISC; } axe_cmd(sc, AXE_CMD_RXCTL_WRITE, 0, rxmode, NULL); axe_setmulti(ue); } static void axe_stop(struct usb_ether *ue) { struct axe_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); AXE_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); sc->sc_flags &= ~AXE_FLAG_LINK; /* * stop all the transfers, if not already stopped: */ usbd_transfer_stop(sc->sc_xfer[AXE_BULK_DT_WR]); usbd_transfer_stop(sc->sc_xfer[AXE_BULK_DT_RD]); } static int axe_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) { struct usb_ether *ue = ifp->if_softc; struct axe_softc *sc; struct ifreq *ifr; int error, mask, reinit; sc = uether_getsc(ue); ifr = (struct ifreq *)data; error = 0; reinit = 0; if (cmd == SIOCSIFCAP) { AXE_LOCK(sc); mask = ifr->ifr_reqcap ^ ifp->if_capenable; if ((mask & IFCAP_TXCSUM) != 0 && (ifp->if_capabilities & IFCAP_TXCSUM) != 0) { ifp->if_capenable ^= IFCAP_TXCSUM; if ((ifp->if_capenable & IFCAP_TXCSUM) != 0) ifp->if_hwassist |= AXE_CSUM_FEATURES; else ifp->if_hwassist &= ~AXE_CSUM_FEATURES; reinit++; } if ((mask & IFCAP_RXCSUM) != 0 && (ifp->if_capabilities & IFCAP_RXCSUM) != 0) { ifp->if_capenable ^= IFCAP_RXCSUM; reinit++; } if (reinit > 0 && ifp->if_drv_flags & IFF_DRV_RUNNING) ifp->if_drv_flags &= ~IFF_DRV_RUNNING; else reinit = 0; AXE_UNLOCK(sc); if (reinit > 0) uether_init(ue); } else error = uether_ioctl(ifp, cmd, data); return (error); } Index: head/sys/dev/usb/net/if_axge.c =================================================================== --- head/sys/dev/usb/net/if_axge.c (revision 276700) +++ head/sys/dev/usb/net/if_axge.c (revision 276701) @@ -1,1038 +1,1038 @@ /*- * Copyright (c) 2013-2014 Kevin Lo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * ASIX Electronics AX88178A/AX88179 USB 2.0/3.0 gigabit ethernet driver. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR axge_debug #include #include #include #include /* * Various supported device vendors/products. */ static const STRUCT_USB_HOST_ID axge_devs[] = { #define AXGE_DEV(v,p) { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) } AXGE_DEV(ASIX, AX88178A), AXGE_DEV(ASIX, AX88179), AXGE_DEV(DLINK, DUB1312), AXGE_DEV(SITECOMEU, LN032), #undef AXGE_DEV }; static const struct { uint8_t ctrl; uint8_t timer_l; uint8_t timer_h; uint8_t size; uint8_t ifg; } __packed axge_bulk_size[] = { { 7, 0x4f, 0x00, 0x12, 0xff }, { 7, 0x20, 0x03, 0x16, 0xff }, { 7, 0xae, 0x07, 0x18, 0xff }, { 7, 0xcc, 0x4c, 0x18, 0x08 } }; /* prototypes */ static device_probe_t axge_probe; static device_attach_t axge_attach; static device_detach_t axge_detach; static usb_callback_t axge_bulk_read_callback; static usb_callback_t axge_bulk_write_callback; static miibus_readreg_t axge_miibus_readreg; static miibus_writereg_t axge_miibus_writereg; static miibus_statchg_t axge_miibus_statchg; static uether_fn_t axge_attach_post; static uether_fn_t axge_init; static uether_fn_t axge_stop; static uether_fn_t axge_start; static uether_fn_t axge_tick; static uether_fn_t axge_setmulti; static uether_fn_t axge_setpromisc; static int axge_read_mem(struct axge_softc *, uint8_t, uint16_t, uint16_t, void *, int); static void axge_write_mem(struct axge_softc *, uint8_t, uint16_t, uint16_t, void *, int); static uint8_t axge_read_cmd_1(struct axge_softc *, uint8_t, uint16_t); static uint16_t axge_read_cmd_2(struct axge_softc *, uint8_t, uint16_t, uint16_t); static void axge_write_cmd_1(struct axge_softc *, uint8_t, uint16_t, uint8_t); static void axge_write_cmd_2(struct axge_softc *, uint8_t, uint16_t, uint16_t, uint16_t); static void axge_chip_init(struct axge_softc *); static void axge_reset(struct axge_softc *); static int axge_attach_post_sub(struct usb_ether *); static int axge_ifmedia_upd(struct ifnet *); static void axge_ifmedia_sts(struct ifnet *, struct ifmediareq *); static int axge_ioctl(struct ifnet *, u_long, caddr_t); static void axge_rx_frame(struct usb_ether *, struct usb_page_cache *, int); static void axge_rxeof(struct usb_ether *, struct usb_page_cache *, unsigned int, unsigned int, uint32_t); static void axge_csum_cfg(struct usb_ether *); #define AXGE_CSUM_FEATURES (CSUM_IP | CSUM_TCP | CSUM_UDP) #ifdef USB_DEBUG static int axge_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, axge, CTLFLAG_RW, 0, "USB axge"); -SYSCTL_INT(_hw_usb_axge, OID_AUTO, debug, CTLFLAG_RW, &axge_debug, 0, +SYSCTL_INT(_hw_usb_axge, OID_AUTO, debug, CTLFLAG_RWTUN, &axge_debug, 0, "Debug level"); #endif static const struct usb_config axge_config[AXGE_N_TRANSFER] = { [AXGE_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .frames = 16, .bufsize = 16 * MCLBYTES, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = axge_bulk_write_callback, .timeout = 10000, /* 10 seconds */ }, [AXGE_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = 65536, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = axge_bulk_read_callback, .timeout = 0, /* no timeout */ }, }; static device_method_t axge_methods[] = { /* Device interface. */ DEVMETHOD(device_probe, axge_probe), DEVMETHOD(device_attach, axge_attach), DEVMETHOD(device_detach, axge_detach), /* MII interface. */ DEVMETHOD(miibus_readreg, axge_miibus_readreg), DEVMETHOD(miibus_writereg, axge_miibus_writereg), DEVMETHOD(miibus_statchg, axge_miibus_statchg), DEVMETHOD_END }; static driver_t axge_driver = { .name = "axge", .methods = axge_methods, .size = sizeof(struct axge_softc), }; static devclass_t axge_devclass; DRIVER_MODULE(axge, uhub, axge_driver, axge_devclass, NULL, NULL); DRIVER_MODULE(miibus, axge, miibus_driver, miibus_devclass, NULL, NULL); MODULE_DEPEND(axge, uether, 1, 1, 1); MODULE_DEPEND(axge, usb, 1, 1, 1); MODULE_DEPEND(axge, ether, 1, 1, 1); MODULE_DEPEND(axge, miibus, 1, 1, 1); MODULE_VERSION(axge, 1); static const struct usb_ether_methods axge_ue_methods = { .ue_attach_post = axge_attach_post, .ue_attach_post_sub = axge_attach_post_sub, .ue_start = axge_start, .ue_init = axge_init, .ue_stop = axge_stop, .ue_tick = axge_tick, .ue_setmulti = axge_setmulti, .ue_setpromisc = axge_setpromisc, .ue_mii_upd = axge_ifmedia_upd, .ue_mii_sts = axge_ifmedia_sts, }; static int axge_read_mem(struct axge_softc *sc, uint8_t cmd, uint16_t index, uint16_t val, void *buf, int len) { struct usb_device_request req; AXGE_LOCK_ASSERT(sc, MA_OWNED); req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = cmd; USETW(req.wValue, val); USETW(req.wIndex, index); USETW(req.wLength, len); return (uether_do_request(&sc->sc_ue, &req, buf, 1000)); } static void axge_write_mem(struct axge_softc *sc, uint8_t cmd, uint16_t index, uint16_t val, void *buf, int len) { struct usb_device_request req; AXGE_LOCK_ASSERT(sc, MA_OWNED); req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = cmd; USETW(req.wValue, val); USETW(req.wIndex, index); USETW(req.wLength, len); if (uether_do_request(&sc->sc_ue, &req, buf, 1000)) { /* Error ignored. */ } } static uint8_t axge_read_cmd_1(struct axge_softc *sc, uint8_t cmd, uint16_t reg) { uint8_t val; axge_read_mem(sc, cmd, 1, reg, &val, 1); return (val); } static uint16_t axge_read_cmd_2(struct axge_softc *sc, uint8_t cmd, uint16_t index, uint16_t reg) { uint8_t val[2]; axge_read_mem(sc, cmd, index, reg, &val, 2); return (UGETW(val)); } static void axge_write_cmd_1(struct axge_softc *sc, uint8_t cmd, uint16_t reg, uint8_t val) { axge_write_mem(sc, cmd, 1, reg, &val, 1); } static void axge_write_cmd_2(struct axge_softc *sc, uint8_t cmd, uint16_t index, uint16_t reg, uint16_t val) { uint8_t temp[2]; USETW(temp, val); axge_write_mem(sc, cmd, index, reg, &temp, 2); } static int axge_miibus_readreg(device_t dev, int phy, int reg) { struct axge_softc *sc; uint16_t val; int locked; sc = device_get_softc(dev); locked = mtx_owned(&sc->sc_mtx); if (!locked) AXGE_LOCK(sc); val = axge_read_cmd_2(sc, AXGE_ACCESS_PHY, reg, phy); if (!locked) AXGE_UNLOCK(sc); return (val); } static int axge_miibus_writereg(device_t dev, int phy, int reg, int val) { struct axge_softc *sc; int locked; sc = device_get_softc(dev); if (sc->sc_phyno != phy) return (0); locked = mtx_owned(&sc->sc_mtx); if (!locked) AXGE_LOCK(sc); axge_write_cmd_2(sc, AXGE_ACCESS_PHY, reg, phy, val); if (!locked) AXGE_UNLOCK(sc); return (0); } static void axge_miibus_statchg(device_t dev) { struct axge_softc *sc; struct mii_data *mii; struct ifnet *ifp; uint8_t link_status, tmp[5]; uint16_t val; int locked; sc = device_get_softc(dev); mii = GET_MII(sc); locked = mtx_owned(&sc->sc_mtx); if (!locked) AXGE_LOCK(sc); ifp = uether_getifp(&sc->sc_ue); if (mii == NULL || ifp == NULL || (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) goto done; sc->sc_flags &= ~AXGE_FLAG_LINK; if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) == (IFM_ACTIVE | IFM_AVALID)) { switch (IFM_SUBTYPE(mii->mii_media_active)) { case IFM_10_T: case IFM_100_TX: case IFM_1000_T: sc->sc_flags |= AXGE_FLAG_LINK; break; default: break; } } /* Lost link, do nothing. */ if ((sc->sc_flags & AXGE_FLAG_LINK) == 0) goto done; link_status = axge_read_cmd_1(sc, AXGE_ACCESS_MAC, AXGE_PLSR); val = 0; if ((IFM_OPTIONS(mii->mii_media_active) & IFM_FDX) != 0) { val |= MSR_FD; if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_TXPAUSE) != 0) val |= MSR_TFC; if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_RXPAUSE) != 0) val |= MSR_RFC; } val |= MSR_RE; switch (IFM_SUBTYPE(mii->mii_media_active)) { case IFM_1000_T: val |= MSR_GM | MSR_EN_125MHZ; if (link_status & PLSR_USB_SS) memcpy(tmp, &axge_bulk_size[0], 5); else if (link_status & PLSR_USB_HS) memcpy(tmp, &axge_bulk_size[1], 5); else memcpy(tmp, &axge_bulk_size[3], 5); break; case IFM_100_TX: val |= MSR_PS; if (link_status & (PLSR_USB_SS | PLSR_USB_HS)) memcpy(tmp, &axge_bulk_size[2], 5); else memcpy(tmp, &axge_bulk_size[3], 5); break; case IFM_10_T: memcpy(tmp, &axge_bulk_size[3], 5); break; } /* Rx bulk configuration. */ axge_write_mem(sc, AXGE_ACCESS_MAC, 5, AXGE_RX_BULKIN_QCTRL, tmp, 5); axge_write_cmd_2(sc, AXGE_ACCESS_MAC, 2, AXGE_MSR, val); done: if (!locked) AXGE_UNLOCK(sc); } static void axge_chip_init(struct axge_softc *sc) { /* Power up ethernet PHY. */ axge_write_cmd_2(sc, AXGE_ACCESS_MAC, 2, AXGE_EPPRCR, 0); axge_write_cmd_2(sc, AXGE_ACCESS_MAC, 2, AXGE_EPPRCR, EPPRCR_IPRL); uether_pause(&sc->sc_ue, hz / 4); axge_write_cmd_1(sc, AXGE_ACCESS_MAC, AXGE_CLK_SELECT, AXGE_CLK_SELECT_ACS | AXGE_CLK_SELECT_BCS); uether_pause(&sc->sc_ue, hz / 10); } static void axge_reset(struct axge_softc *sc) { struct usb_config_descriptor *cd; usb_error_t err; cd = usbd_get_config_descriptor(sc->sc_ue.ue_udev); err = usbd_req_set_config(sc->sc_ue.ue_udev, &sc->sc_mtx, cd->bConfigurationValue); if (err) DPRINTF("reset failed (ignored)\n"); /* Wait a little while for the chip to get its brains in order. */ uether_pause(&sc->sc_ue, hz / 100); /* Reinitialize controller to achieve full reset. */ axge_chip_init(sc); } static void axge_attach_post(struct usb_ether *ue) { struct axge_softc *sc; sc = uether_getsc(ue); sc->sc_phyno = 3; /* Initialize controller and get station address. */ axge_chip_init(sc); axge_read_mem(sc, AXGE_ACCESS_MAC, ETHER_ADDR_LEN, AXGE_NIDR, ue->ue_eaddr, ETHER_ADDR_LEN); } static int axge_attach_post_sub(struct usb_ether *ue) { struct axge_softc *sc; struct ifnet *ifp; int error; sc = uether_getsc(ue); ifp = ue->ue_ifp; ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; ifp->if_start = uether_start; ifp->if_ioctl = axge_ioctl; ifp->if_init = uether_init; IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen); ifp->if_snd.ifq_drv_maxlen = ifqmaxlen; IFQ_SET_READY(&ifp->if_snd); ifp->if_capabilities |= IFCAP_VLAN_MTU | IFCAP_TXCSUM | IFCAP_RXCSUM; ifp->if_hwassist = AXGE_CSUM_FEATURES; ifp->if_capenable = ifp->if_capabilities; mtx_lock(&Giant); error = mii_attach(ue->ue_dev, &ue->ue_miibus, ifp, uether_ifmedia_upd, ue->ue_methods->ue_mii_sts, BMSR_DEFCAPMASK, sc->sc_phyno, MII_OFFSET_ANY, MIIF_DOPAUSE); mtx_unlock(&Giant); return (error); } /* * Set media options. */ static int axge_ifmedia_upd(struct ifnet *ifp) { struct axge_softc *sc; struct mii_data *mii; struct mii_softc *miisc; int error; sc = ifp->if_softc; mii = GET_MII(sc); AXGE_LOCK_ASSERT(sc, MA_OWNED); LIST_FOREACH(miisc, &mii->mii_phys, mii_list) PHY_RESET(miisc); error = mii_mediachg(mii); return (error); } /* * Report current media status. */ static void axge_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr) { struct axge_softc *sc; struct mii_data *mii; sc = ifp->if_softc; mii = GET_MII(sc); AXGE_LOCK(sc); mii_pollstat(mii); ifmr->ifm_active = mii->mii_media_active; ifmr->ifm_status = mii->mii_media_status; AXGE_UNLOCK(sc); } /* * Probe for a AX88179 chip. */ static int axge_probe(device_t dev) { struct usb_attach_arg *uaa; uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != AXGE_CONFIG_IDX) return (ENXIO); if (uaa->info.bIfaceIndex != AXGE_IFACE_IDX) return (ENXIO); return (usbd_lookup_id_by_uaa(axge_devs, sizeof(axge_devs), uaa)); } /* * Attach the interface. Allocate softc structures, do ifmedia * setup and ethernet/BPF attach. */ static int axge_attach(device_t dev) { struct usb_attach_arg *uaa; struct axge_softc *sc; struct usb_ether *ue; uint8_t iface_index; int error; uaa = device_get_ivars(dev); sc = device_get_softc(dev); ue = &sc->sc_ue; device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF); iface_index = AXGE_IFACE_IDX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, axge_config, AXGE_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(dev, "allocating USB transfers failed\n"); goto detach; } ue->ue_sc = sc; ue->ue_dev = dev; ue->ue_udev = uaa->device; ue->ue_mtx = &sc->sc_mtx; ue->ue_methods = &axge_ue_methods; error = uether_ifattach(ue); if (error) { device_printf(dev, "could not attach interface\n"); goto detach; } return (0); /* success */ detach: axge_detach(dev); return (ENXIO); /* failure */ } static int axge_detach(device_t dev) { struct axge_softc *sc; struct usb_ether *ue; sc = device_get_softc(dev); ue = &sc->sc_ue; usbd_transfer_unsetup(sc->sc_xfer, AXGE_N_TRANSFER); uether_ifdetach(ue); mtx_destroy(&sc->sc_mtx); return (0); } static void axge_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct axge_softc *sc; struct usb_ether *ue; struct usb_page_cache *pc; int actlen; sc = usbd_xfer_softc(xfer); ue = &sc->sc_ue; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); axge_rx_frame(ue, pc, actlen); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); uether_rxflush(ue); break; default: if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void axge_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct axge_softc *sc; struct ifnet *ifp; struct usb_page_cache *pc; struct mbuf *m; uint32_t txhdr; int nframes, pos; sc = usbd_xfer_softc(xfer); ifp = uether_getifp(&sc->sc_ue); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: if ((sc->sc_flags & AXGE_FLAG_LINK) == 0 || (ifp->if_drv_flags & IFF_DRV_OACTIVE) != 0) { /* * Don't send anything if there is no link or * controller is busy. */ return; } for (nframes = 0; nframes < 16 && !IFQ_DRV_IS_EMPTY(&ifp->if_snd); nframes++) { IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; usbd_xfer_set_frame_offset(xfer, nframes * MCLBYTES, nframes); pos = 0; pc = usbd_xfer_get_frame(xfer, nframes); txhdr = htole32(m->m_pkthdr.len); usbd_copy_in(pc, 0, &txhdr, sizeof(txhdr)); txhdr = 0; txhdr = htole32(txhdr); usbd_copy_in(pc, 4, &txhdr, sizeof(txhdr)); pos += 8; usbd_m_copy_in(pc, pos, m, 0, m->m_pkthdr.len); pos += m->m_pkthdr.len; if ((pos % usbd_xfer_max_framelen(xfer)) == 0) txhdr |= 0x80008000; /* * XXX * Update TX packet counter here. This is not * correct way but it seems that there is no way * to know how many packets are sent at the end * of transfer because controller combines * multiple writes into single one if there is * room in TX buffer of controller. */ if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* * if there's a BPF listener, bounce a copy * of this frame to him: */ BPF_MTAP(ifp, m); m_freem(m); /* Set frame length. */ usbd_xfer_set_frame_len(xfer, nframes, pos); } if (nframes != 0) { usbd_xfer_set_frames(xfer, nframes); usbd_transfer_submit(xfer); ifp->if_drv_flags |= IFF_DRV_OACTIVE; } return; /* NOTREACHED */ default: if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void axge_tick(struct usb_ether *ue) { struct axge_softc *sc; struct mii_data *mii; sc = uether_getsc(ue); mii = GET_MII(sc); AXGE_LOCK_ASSERT(sc, MA_OWNED); mii_tick(mii); if ((sc->sc_flags & AXGE_FLAG_LINK) == 0) { axge_miibus_statchg(ue->ue_dev); if ((sc->sc_flags & AXGE_FLAG_LINK) != 0) axge_start(ue); } } static void axge_setmulti(struct usb_ether *ue) { struct axge_softc *sc; struct ifnet *ifp; struct ifmultiaddr *ifma; uint32_t h; uint16_t rxmode; uint8_t hashtbl[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; sc = uether_getsc(ue); ifp = uether_getifp(ue); h = 0; AXGE_LOCK_ASSERT(sc, MA_OWNED); rxmode = axge_read_cmd_2(sc, AXGE_ACCESS_MAC, 2, AXGE_RCR); if (ifp->if_flags & (IFF_ALLMULTI | IFF_PROMISC)) { rxmode |= RCR_AMALL; axge_write_cmd_2(sc, AXGE_ACCESS_MAC, 2, AXGE_RCR, rxmode); return; } rxmode &= ~RCR_AMALL; if_maddr_rlock(ifp); TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) { if (ifma->ifma_addr->sa_family != AF_LINK) continue; h = ether_crc32_be(LLADDR((struct sockaddr_dl *) ifma->ifma_addr), ETHER_ADDR_LEN) >> 26; hashtbl[h / 8] |= 1 << (h % 8); } if_maddr_runlock(ifp); axge_write_mem(sc, AXGE_ACCESS_MAC, 8, AXGE_MFA, (void *)&hashtbl, 8); axge_write_cmd_2(sc, AXGE_ACCESS_MAC, 2, AXGE_RCR, rxmode); } static void axge_setpromisc(struct usb_ether *ue) { struct axge_softc *sc; struct ifnet *ifp; uint16_t rxmode; sc = uether_getsc(ue); ifp = uether_getifp(ue); rxmode = axge_read_cmd_2(sc, AXGE_ACCESS_MAC, 2, AXGE_RCR); if (ifp->if_flags & IFF_PROMISC) rxmode |= RCR_PRO; else rxmode &= ~RCR_PRO; axge_write_cmd_2(sc, AXGE_ACCESS_MAC, 2, AXGE_RCR, rxmode); axge_setmulti(ue); } static void axge_start(struct usb_ether *ue) { struct axge_softc *sc; sc = uether_getsc(ue); /* * Start the USB transfers, if not already started. */ usbd_transfer_start(sc->sc_xfer[AXGE_BULK_DT_RD]); usbd_transfer_start(sc->sc_xfer[AXGE_BULK_DT_WR]); } static void axge_init(struct usb_ether *ue) { struct axge_softc *sc; struct ifnet *ifp; uint16_t rxmode; sc = uether_getsc(ue); ifp = uether_getifp(ue); AXGE_LOCK_ASSERT(sc, MA_OWNED); if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0) return; /* * Cancel pending I/O and free all RX/TX buffers. */ axge_stop(ue); axge_reset(sc); /* Set MAC address. */ axge_write_mem(sc, AXGE_ACCESS_MAC, ETHER_ADDR_LEN, AXGE_NIDR, IF_LLADDR(ifp), ETHER_ADDR_LEN); axge_write_cmd_1(sc, AXGE_ACCESS_MAC, AXGE_PWLLR, 0x34); axge_write_cmd_1(sc, AXGE_ACCESS_MAC, AXGE_PWLHR, 0x52); /* Configure TX/RX checksum offloading. */ axge_csum_cfg(ue); /* Configure RX settings. */ rxmode = (RCR_AM | RCR_SO | RCR_DROP_CRCE); if ((ifp->if_capenable & IFCAP_RXCSUM) != 0) rxmode |= RCR_IPE; /* If we want promiscuous mode, set the allframes bit. */ if (ifp->if_flags & IFF_PROMISC) rxmode |= RCR_PRO; if (ifp->if_flags & IFF_BROADCAST) rxmode |= RCR_AB; axge_write_cmd_2(sc, AXGE_ACCESS_MAC, 2, AXGE_RCR, rxmode); axge_write_cmd_1(sc, AXGE_ACCESS_MAC, AXGE_MMSR, MMSR_PME_TYPE | MMSR_PME_POL | MMSR_RWMP); /* Load the multicast filter. */ axge_setmulti(ue); usbd_xfer_set_stall(sc->sc_xfer[AXGE_BULK_DT_WR]); ifp->if_drv_flags |= IFF_DRV_RUNNING; /* Switch to selected media. */ axge_ifmedia_upd(ifp); } static void axge_stop(struct usb_ether *ue) { struct axge_softc *sc; struct ifnet *ifp; sc = uether_getsc(ue); ifp = uether_getifp(ue); AXGE_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); sc->sc_flags &= ~AXGE_FLAG_LINK; /* * Stop all the transfers, if not already stopped: */ usbd_transfer_stop(sc->sc_xfer[AXGE_BULK_DT_WR]); usbd_transfer_stop(sc->sc_xfer[AXGE_BULK_DT_RD]); } static int axge_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) { struct usb_ether *ue; struct axge_softc *sc; struct ifreq *ifr; int error, mask, reinit; ue = ifp->if_softc; sc = uether_getsc(ue); ifr = (struct ifreq *)data; error = 0; reinit = 0; if (cmd == SIOCSIFCAP) { AXGE_LOCK(sc); mask = ifr->ifr_reqcap ^ ifp->if_capenable; if ((mask & IFCAP_TXCSUM) != 0 && (ifp->if_capabilities & IFCAP_TXCSUM) != 0) { ifp->if_capenable ^= IFCAP_TXCSUM; if ((ifp->if_capenable & IFCAP_TXCSUM) != 0) ifp->if_hwassist |= AXGE_CSUM_FEATURES; else ifp->if_hwassist &= ~AXGE_CSUM_FEATURES; reinit++; } if ((mask & IFCAP_RXCSUM) != 0 && (ifp->if_capabilities & IFCAP_RXCSUM) != 0) { ifp->if_capenable ^= IFCAP_RXCSUM; reinit++; } if (reinit > 0 && ifp->if_drv_flags & IFF_DRV_RUNNING) ifp->if_drv_flags &= ~IFF_DRV_RUNNING; else reinit = 0; AXGE_UNLOCK(sc); if (reinit > 0) uether_init(ue); } else error = uether_ioctl(ifp, cmd, data); return (error); } static void axge_rx_frame(struct usb_ether *ue, struct usb_page_cache *pc, int actlen) { uint32_t pos; uint32_t pkt_cnt; uint32_t rxhdr; uint32_t pkt_hdr; uint32_t hdr_off; uint32_t pktlen; /* verify we have enough data */ if (actlen < (int)sizeof(rxhdr)) return; pos = 0; usbd_copy_out(pc, actlen - sizeof(rxhdr), &rxhdr, sizeof(rxhdr)); rxhdr = le32toh(rxhdr); pkt_cnt = (uint16_t)rxhdr; hdr_off = (uint16_t)(rxhdr >> 16); while (pkt_cnt--) { /* verify the header offset */ if ((int)(hdr_off + sizeof(pkt_hdr)) > actlen) { DPRINTF("End of packet headers\n"); break; } if ((int)pos >= actlen) { DPRINTF("Data position reached end\n"); break; } usbd_copy_out(pc, hdr_off, &pkt_hdr, sizeof(pkt_hdr)); pkt_hdr = le32toh(pkt_hdr); pktlen = (pkt_hdr >> 16) & 0x1fff; if (pkt_hdr & (AXGE_RXHDR_CRC_ERR | AXGE_RXHDR_DROP_ERR)) { DPRINTF("Dropped a packet\n"); if_inc_counter(ue->ue_ifp, IFCOUNTER_IERRORS, 1); } if (pktlen >= 6 && (int)(pos + pktlen) <= actlen) { axge_rxeof(ue, pc, pos + 2, pktlen - 6, pkt_hdr); } else { DPRINTF("Invalid packet pos=%d len=%d\n", (int)pos, (int)pktlen); } pos += (pktlen + 7) & ~7; hdr_off += sizeof(pkt_hdr); } } static void axge_rxeof(struct usb_ether *ue, struct usb_page_cache *pc, unsigned int offset, unsigned int len, uint32_t pkt_hdr) { struct ifnet *ifp; struct mbuf *m; ifp = ue->ue_ifp; if (len < ETHER_HDR_LEN || len > MCLBYTES - ETHER_ALIGN) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); return; } m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); if (m == NULL) { if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1); return; } m->m_pkthdr.rcvif = ifp; m->m_len = m->m_pkthdr.len = len + ETHER_ALIGN; m_adj(m, ETHER_ALIGN); usbd_copy_out(pc, offset, mtod(m, uint8_t *), len); if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1); if ((pkt_hdr & (AXGE_RXHDR_L4CSUM_ERR | AXGE_RXHDR_L3CSUM_ERR)) == 0) { if ((pkt_hdr & AXGE_RXHDR_L4_TYPE_MASK) == AXGE_RXHDR_L4_TYPE_TCP || (pkt_hdr & AXGE_RXHDR_L4_TYPE_MASK) == AXGE_RXHDR_L4_TYPE_UDP) { m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR | CSUM_IP_CHECKED | CSUM_IP_VALID; m->m_pkthdr.csum_data = 0xffff; } } _IF_ENQUEUE(&ue->ue_rxq, m); } static void axge_csum_cfg(struct usb_ether *ue) { struct axge_softc *sc; struct ifnet *ifp; uint8_t csum; sc = uether_getsc(ue); AXGE_LOCK_ASSERT(sc, MA_OWNED); ifp = uether_getifp(ue); csum = 0; if ((ifp->if_capenable & IFCAP_TXCSUM) != 0) csum |= CTCR_IP | CTCR_TCP | CTCR_UDP; axge_write_cmd_1(sc, AXGE_ACCESS_MAC, AXGE_CTCR, csum); csum = 0; if ((ifp->if_capenable & IFCAP_RXCSUM) != 0) csum |= CRCR_IP | CRCR_TCP | CRCR_UDP; axge_write_cmd_1(sc, AXGE_ACCESS_MAC, AXGE_CRCR, csum); } Index: head/sys/dev/usb/net/if_cdce.c =================================================================== --- head/sys/dev/usb/net/if_cdce.c (revision 276700) +++ head/sys/dev/usb/net/if_cdce.c (revision 276701) @@ -1,1485 +1,1485 @@ /* $NetBSD: if_cdce.c,v 1.4 2004/10/24 12:50:54 augustss Exp $ */ /*- * Copyright (c) 1997, 1998, 1999, 2000-2003 Bill Paul * Copyright (c) 2003-2005 Craig Boston * Copyright (c) 2004 Daniel Hartmeier * Copyright (c) 2009 Hans Petter Selasky * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Bill Paul. * 4. Neither the name of the author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL Bill Paul, THE VOICES IN HIS HEAD OR * THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * USB Communication Device Class (Ethernet Networking Control Model) * http://www.usb.org/developers/devclass_docs/usbcdc11.pdf */ /* * USB Network Control Model (NCM) * http://www.usb.org/developers/devclass_docs/NCM10.zip */ #include __FBSDID("$FreeBSD$"); #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 "usbdevs.h" #define USB_DEBUG_VAR cdce_debug #include #include #include #include "usb_if.h" #include #include static device_probe_t cdce_probe; static device_attach_t cdce_attach; static device_detach_t cdce_detach; static device_suspend_t cdce_suspend; static device_resume_t cdce_resume; static usb_handle_request_t cdce_handle_request; static usb_callback_t cdce_bulk_write_callback; static usb_callback_t cdce_bulk_read_callback; static usb_callback_t cdce_intr_read_callback; static usb_callback_t cdce_intr_write_callback; #if CDCE_HAVE_NCM static usb_callback_t cdce_ncm_bulk_write_callback; static usb_callback_t cdce_ncm_bulk_read_callback; #endif static uether_fn_t cdce_attach_post; static uether_fn_t cdce_init; static uether_fn_t cdce_stop; static uether_fn_t cdce_start; static uether_fn_t cdce_setmulti; static uether_fn_t cdce_setpromisc; static uint32_t cdce_m_crc32(struct mbuf *, uint32_t, uint32_t); #ifdef USB_DEBUG static int cdce_debug = 0; static int cdce_tx_interval = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, cdce, CTLFLAG_RW, 0, "USB CDC-Ethernet"); -SYSCTL_INT(_hw_usb_cdce, OID_AUTO, debug, CTLFLAG_RW, &cdce_debug, 0, +SYSCTL_INT(_hw_usb_cdce, OID_AUTO, debug, CTLFLAG_RWTUN, &cdce_debug, 0, "Debug level"); -SYSCTL_INT(_hw_usb_cdce, OID_AUTO, interval, CTLFLAG_RW, &cdce_tx_interval, 0, +SYSCTL_INT(_hw_usb_cdce, OID_AUTO, interval, CTLFLAG_RWTUN, &cdce_tx_interval, 0, "NCM transmit interval in ms"); #endif static const struct usb_config cdce_config[CDCE_N_TRANSFER] = { [CDCE_BULK_RX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_RX, .if_index = 0, .frames = CDCE_FRAMES_MAX, .bufsize = (CDCE_FRAMES_MAX * MCLBYTES), .flags = {.pipe_bof = 1,.short_frames_ok = 1,.short_xfer_ok = 1,.ext_buffer = 1,}, .callback = cdce_bulk_read_callback, .timeout = 0, /* no timeout */ .usb_mode = USB_MODE_DUAL, /* both modes */ }, [CDCE_BULK_TX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_TX, .if_index = 0, .frames = CDCE_FRAMES_MAX, .bufsize = (CDCE_FRAMES_MAX * MCLBYTES), .flags = {.pipe_bof = 1,.force_short_xfer = 1,.ext_buffer = 1,}, .callback = cdce_bulk_write_callback, .timeout = 10000, /* 10 seconds */ .usb_mode = USB_MODE_DUAL, /* both modes */ }, [CDCE_INTR_RX] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_RX, .if_index = 1, .bufsize = CDCE_IND_SIZE_MAX, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,.no_pipe_ok = 1,}, .callback = cdce_intr_read_callback, .timeout = 0, .usb_mode = USB_MODE_HOST, }, [CDCE_INTR_TX] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_TX, .if_index = 1, .bufsize = CDCE_IND_SIZE_MAX, .flags = {.pipe_bof = 1,.force_short_xfer = 1,.no_pipe_ok = 1,}, .callback = cdce_intr_write_callback, .timeout = 10000, /* 10 seconds */ .usb_mode = USB_MODE_DEVICE, }, }; #if CDCE_HAVE_NCM static const struct usb_config cdce_ncm_config[CDCE_N_TRANSFER] = { [CDCE_BULK_RX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_RX, .if_index = 0, .frames = CDCE_NCM_RX_FRAMES_MAX, .bufsize = (CDCE_NCM_RX_FRAMES_MAX * CDCE_NCM_RX_MAXLEN), .flags = {.pipe_bof = 1,.short_frames_ok = 1,.short_xfer_ok = 1,}, .callback = cdce_ncm_bulk_read_callback, .timeout = 0, /* no timeout */ .usb_mode = USB_MODE_DUAL, /* both modes */ }, [CDCE_BULK_TX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_TX, .if_index = 0, .frames = CDCE_NCM_TX_FRAMES_MAX, .bufsize = (CDCE_NCM_TX_FRAMES_MAX * CDCE_NCM_TX_MAXLEN), .flags = {.pipe_bof = 1,}, .callback = cdce_ncm_bulk_write_callback, .timeout = 10000, /* 10 seconds */ .usb_mode = USB_MODE_DUAL, /* both modes */ }, [CDCE_INTR_RX] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_RX, .if_index = 1, .bufsize = CDCE_IND_SIZE_MAX, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,.no_pipe_ok = 1,}, .callback = cdce_intr_read_callback, .timeout = 0, .usb_mode = USB_MODE_HOST, }, [CDCE_INTR_TX] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_TX, .if_index = 1, .bufsize = CDCE_IND_SIZE_MAX, .flags = {.pipe_bof = 1,.force_short_xfer = 1,.no_pipe_ok = 1,}, .callback = cdce_intr_write_callback, .timeout = 10000, /* 10 seconds */ .usb_mode = USB_MODE_DEVICE, }, }; #endif static device_method_t cdce_methods[] = { /* USB interface */ DEVMETHOD(usb_handle_request, cdce_handle_request), /* Device interface */ DEVMETHOD(device_probe, cdce_probe), DEVMETHOD(device_attach, cdce_attach), DEVMETHOD(device_detach, cdce_detach), DEVMETHOD(device_suspend, cdce_suspend), DEVMETHOD(device_resume, cdce_resume), DEVMETHOD_END }; static driver_t cdce_driver = { .name = "cdce", .methods = cdce_methods, .size = sizeof(struct cdce_softc), }; static devclass_t cdce_devclass; static eventhandler_tag cdce_etag; static int cdce_driver_loaded(struct module *, int, void *); DRIVER_MODULE(cdce, uhub, cdce_driver, cdce_devclass, cdce_driver_loaded, 0); MODULE_VERSION(cdce, 1); MODULE_DEPEND(cdce, uether, 1, 1, 1); MODULE_DEPEND(cdce, usb, 1, 1, 1); MODULE_DEPEND(cdce, ether, 1, 1, 1); static const struct usb_ether_methods cdce_ue_methods = { .ue_attach_post = cdce_attach_post, .ue_start = cdce_start, .ue_init = cdce_init, .ue_stop = cdce_stop, .ue_setmulti = cdce_setmulti, .ue_setpromisc = cdce_setpromisc, }; static const STRUCT_USB_HOST_ID cdce_switch_devs[] = { {USB_VPI(USB_VENDOR_HUAWEI, USB_PRODUCT_HUAWEI_E3272_INIT, MSC_EJECT_HUAWEI2)}, }; static const STRUCT_USB_HOST_ID cdce_host_devs[] = { {USB_VPI(USB_VENDOR_ACERLABS, USB_PRODUCT_ACERLABS_M5632, CDCE_FLAG_NO_UNION)}, {USB_VPI(USB_VENDOR_AMBIT, USB_PRODUCT_AMBIT_NTL_250, CDCE_FLAG_NO_UNION)}, {USB_VPI(USB_VENDOR_COMPAQ, USB_PRODUCT_COMPAQ_IPAQLINUX, CDCE_FLAG_NO_UNION)}, {USB_VPI(USB_VENDOR_GMATE, USB_PRODUCT_GMATE_YP3X00, CDCE_FLAG_NO_UNION)}, {USB_VPI(USB_VENDOR_MOTOROLA2, USB_PRODUCT_MOTOROLA2_USBLAN, CDCE_FLAG_ZAURUS | CDCE_FLAG_NO_UNION)}, {USB_VPI(USB_VENDOR_MOTOROLA2, USB_PRODUCT_MOTOROLA2_USBLAN2, CDCE_FLAG_ZAURUS | CDCE_FLAG_NO_UNION)}, {USB_VPI(USB_VENDOR_NETCHIP, USB_PRODUCT_NETCHIP_ETHERNETGADGET, CDCE_FLAG_NO_UNION)}, {USB_VPI(USB_VENDOR_PROLIFIC, USB_PRODUCT_PROLIFIC_PL2501, CDCE_FLAG_NO_UNION)}, {USB_VPI(USB_VENDOR_SHARP, USB_PRODUCT_SHARP_SL5500, CDCE_FLAG_ZAURUS)}, {USB_VPI(USB_VENDOR_SHARP, USB_PRODUCT_SHARP_SL5600, CDCE_FLAG_ZAURUS | CDCE_FLAG_NO_UNION)}, {USB_VPI(USB_VENDOR_SHARP, USB_PRODUCT_SHARP_SLA300, CDCE_FLAG_ZAURUS | CDCE_FLAG_NO_UNION)}, {USB_VPI(USB_VENDOR_SHARP, USB_PRODUCT_SHARP_SLC700, CDCE_FLAG_ZAURUS | CDCE_FLAG_NO_UNION)}, {USB_VPI(USB_VENDOR_SHARP, USB_PRODUCT_SHARP_SLC750, CDCE_FLAG_ZAURUS | CDCE_FLAG_NO_UNION)}, {USB_VENDOR(USB_VENDOR_HUAWEI), USB_IFACE_CLASS(UICLASS_VENDOR), USB_IFACE_SUBCLASS(0x02), USB_IFACE_PROTOCOL(0x16), USB_DRIVER_INFO(0)}, {USB_VENDOR(USB_VENDOR_HUAWEI), USB_IFACE_CLASS(UICLASS_VENDOR), USB_IFACE_SUBCLASS(0x02), USB_IFACE_PROTOCOL(0x46), USB_DRIVER_INFO(0)}, {USB_VENDOR(USB_VENDOR_HUAWEI), USB_IFACE_CLASS(UICLASS_VENDOR), USB_IFACE_SUBCLASS(0x02), USB_IFACE_PROTOCOL(0x76), USB_DRIVER_INFO(0)}, }; static const STRUCT_USB_DUAL_ID cdce_dual_devs[] = { {USB_IF_CSI(UICLASS_CDC, UISUBCLASS_ETHERNET_NETWORKING_CONTROL_MODEL, 0)}, {USB_IF_CSI(UICLASS_CDC, UISUBCLASS_MOBILE_DIRECT_LINE_MODEL, 0)}, {USB_IF_CSI(UICLASS_CDC, UISUBCLASS_NETWORK_CONTROL_MODEL, 0)}, }; #if CDCE_HAVE_NCM /*------------------------------------------------------------------------* * cdce_ncm_init * * Return values: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t cdce_ncm_init(struct cdce_softc *sc) { struct usb_ncm_parameters temp; struct usb_device_request req; struct usb_ncm_func_descriptor *ufd; uint8_t value[8]; int err; ufd = usbd_find_descriptor(sc->sc_ue.ue_udev, NULL, sc->sc_ifaces_index[1], UDESC_CS_INTERFACE, 0xFF, UCDC_NCM_FUNC_DESC_SUBTYPE, 0xFF); /* verify length of NCM functional descriptor */ if (ufd != NULL) { if (ufd->bLength < sizeof(*ufd)) ufd = NULL; else DPRINTFN(1, "Found NCM functional descriptor.\n"); } req.bmRequestType = UT_READ_CLASS_INTERFACE; req.bRequest = UCDC_NCM_GET_NTB_PARAMETERS; USETW(req.wValue, 0); req.wIndex[0] = sc->sc_ifaces_index[1]; req.wIndex[1] = 0; USETW(req.wLength, sizeof(temp)); err = usbd_do_request_flags(sc->sc_ue.ue_udev, NULL, &req, &temp, 0, NULL, 1000 /* ms */); if (err) return (1); /* Read correct set of parameters according to device mode */ if (usbd_get_mode(sc->sc_ue.ue_udev) == USB_MODE_HOST) { sc->sc_ncm.rx_max = UGETDW(temp.dwNtbInMaxSize); sc->sc_ncm.tx_max = UGETDW(temp.dwNtbOutMaxSize); sc->sc_ncm.tx_remainder = UGETW(temp.wNdpOutPayloadRemainder); sc->sc_ncm.tx_modulus = UGETW(temp.wNdpOutDivisor); sc->sc_ncm.tx_struct_align = UGETW(temp.wNdpOutAlignment); sc->sc_ncm.tx_nframe = UGETW(temp.wNtbOutMaxDatagrams); } else { sc->sc_ncm.rx_max = UGETDW(temp.dwNtbOutMaxSize); sc->sc_ncm.tx_max = UGETDW(temp.dwNtbInMaxSize); sc->sc_ncm.tx_remainder = UGETW(temp.wNdpInPayloadRemainder); sc->sc_ncm.tx_modulus = UGETW(temp.wNdpInDivisor); sc->sc_ncm.tx_struct_align = UGETW(temp.wNdpInAlignment); sc->sc_ncm.tx_nframe = UGETW(temp.wNtbOutMaxDatagrams); } /* Verify maximum receive length */ if ((sc->sc_ncm.rx_max < 32) || (sc->sc_ncm.rx_max > CDCE_NCM_RX_MAXLEN)) { DPRINTFN(1, "Using default maximum receive length\n"); sc->sc_ncm.rx_max = CDCE_NCM_RX_MAXLEN; } /* Verify maximum transmit length */ if ((sc->sc_ncm.tx_max < 32) || (sc->sc_ncm.tx_max > CDCE_NCM_TX_MAXLEN)) { DPRINTFN(1, "Using default maximum transmit length\n"); sc->sc_ncm.tx_max = CDCE_NCM_TX_MAXLEN; } /* * Verify that the structure alignment is: * - power of two * - not greater than the maximum transmit length * - not less than four bytes */ if ((sc->sc_ncm.tx_struct_align < 4) || (sc->sc_ncm.tx_struct_align != ((-sc->sc_ncm.tx_struct_align) & sc->sc_ncm.tx_struct_align)) || (sc->sc_ncm.tx_struct_align >= sc->sc_ncm.tx_max)) { DPRINTFN(1, "Using default other alignment: 4 bytes\n"); sc->sc_ncm.tx_struct_align = 4; } /* * Verify that the payload alignment is: * - power of two * - not greater than the maximum transmit length * - not less than four bytes */ if ((sc->sc_ncm.tx_modulus < 4) || (sc->sc_ncm.tx_modulus != ((-sc->sc_ncm.tx_modulus) & sc->sc_ncm.tx_modulus)) || (sc->sc_ncm.tx_modulus >= sc->sc_ncm.tx_max)) { DPRINTFN(1, "Using default transmit modulus: 4 bytes\n"); sc->sc_ncm.tx_modulus = 4; } /* Verify that the payload remainder */ if ((sc->sc_ncm.tx_remainder >= sc->sc_ncm.tx_modulus)) { DPRINTFN(1, "Using default transmit remainder: 0 bytes\n"); sc->sc_ncm.tx_remainder = 0; } /* * Offset the TX remainder so that IP packet payload starts at * the tx_modulus. This is not too clear in the specification. */ sc->sc_ncm.tx_remainder = (sc->sc_ncm.tx_remainder - ETHER_HDR_LEN) & (sc->sc_ncm.tx_modulus - 1); /* Verify max datagrams */ if (sc->sc_ncm.tx_nframe == 0 || sc->sc_ncm.tx_nframe > (CDCE_NCM_SUBFRAMES_MAX - 1)) { DPRINTFN(1, "Using default max " "subframes: %u units\n", CDCE_NCM_SUBFRAMES_MAX - 1); /* need to reserve one entry for zero padding */ sc->sc_ncm.tx_nframe = (CDCE_NCM_SUBFRAMES_MAX - 1); } /* Additional configuration, will fail in device side mode, which is OK. */ req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_NCM_SET_NTB_INPUT_SIZE; USETW(req.wValue, 0); req.wIndex[0] = sc->sc_ifaces_index[1]; req.wIndex[1] = 0; if (ufd != NULL && (ufd->bmNetworkCapabilities & UCDC_NCM_CAP_MAX_DGRAM)) { USETW(req.wLength, 8); USETDW(value, sc->sc_ncm.rx_max); USETW(value + 4, (CDCE_NCM_SUBFRAMES_MAX - 1)); USETW(value + 6, 0); } else { USETW(req.wLength, 4); USETDW(value, sc->sc_ncm.rx_max); } err = usbd_do_request_flags(sc->sc_ue.ue_udev, NULL, &req, &value, 0, NULL, 1000 /* ms */); if (err) { DPRINTFN(1, "Setting input size " "to %u failed.\n", sc->sc_ncm.rx_max); } req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_NCM_SET_CRC_MODE; USETW(req.wValue, 0); /* no CRC */ req.wIndex[0] = sc->sc_ifaces_index[1]; req.wIndex[1] = 0; USETW(req.wLength, 0); err = usbd_do_request_flags(sc->sc_ue.ue_udev, NULL, &req, NULL, 0, NULL, 1000 /* ms */); if (err) { DPRINTFN(1, "Setting CRC mode to off failed.\n"); } req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_NCM_SET_NTB_FORMAT; USETW(req.wValue, 0); /* NTB-16 */ req.wIndex[0] = sc->sc_ifaces_index[1]; req.wIndex[1] = 0; USETW(req.wLength, 0); err = usbd_do_request_flags(sc->sc_ue.ue_udev, NULL, &req, NULL, 0, NULL, 1000 /* ms */); if (err) { DPRINTFN(1, "Setting NTB format to 16-bit failed.\n"); } return (0); /* success */ } #endif static void cdce_test_autoinst(void *arg, struct usb_device *udev, struct usb_attach_arg *uaa) { struct usb_interface *iface; struct usb_interface_descriptor *id; if (uaa->dev_state != UAA_DEV_READY) return; iface = usbd_get_iface(udev, 0); if (iface == NULL) return; id = iface->idesc; if (id == NULL || id->bInterfaceClass != UICLASS_MASS) return; if (usbd_lookup_id_by_uaa(cdce_switch_devs, sizeof(cdce_switch_devs), uaa)) return; /* no device match */ if (usb_msc_eject(udev, 0, USB_GET_DRIVER_INFO(uaa)) == 0) { /* success, mark the udev as disappearing */ uaa->dev_state = UAA_DEV_EJECTING; } } static int cdce_driver_loaded(struct module *mod, int what, void *arg) { switch (what) { case MOD_LOAD: /* register our autoinstall handler */ cdce_etag = EVENTHANDLER_REGISTER(usb_dev_configured, cdce_test_autoinst, NULL, EVENTHANDLER_PRI_ANY); return (0); case MOD_UNLOAD: EVENTHANDLER_DEREGISTER(usb_dev_configured, cdce_etag); return (0); default: return (EOPNOTSUPP); } } static int cdce_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); int error; error = usbd_lookup_id_by_uaa(cdce_host_devs, sizeof(cdce_host_devs), uaa); if (error) error = usbd_lookup_id_by_uaa(cdce_dual_devs, sizeof(cdce_dual_devs), uaa); return (error); } static void cdce_attach_post(struct usb_ether *ue) { /* no-op */ return; } static int cdce_attach(device_t dev) { struct cdce_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; struct usb_attach_arg *uaa = device_get_ivars(dev); struct usb_interface *iface; const struct usb_cdc_union_descriptor *ud; const struct usb_interface_descriptor *id; const struct usb_cdc_ethernet_descriptor *ued; const struct usb_config *pcfg; uint32_t seed; int error; uint8_t i; uint8_t data_iface_no; char eaddr_str[5 * ETHER_ADDR_LEN]; /* approx */ sc->sc_flags = USB_GET_DRIVER_INFO(uaa); sc->sc_ue.ue_udev = uaa->device; device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF); ud = usbd_find_descriptor (uaa->device, NULL, uaa->info.bIfaceIndex, UDESC_CS_INTERFACE, 0xFF, UDESCSUB_CDC_UNION, 0xFF); if ((ud == NULL) || (ud->bLength < sizeof(*ud)) || (sc->sc_flags & CDCE_FLAG_NO_UNION)) { DPRINTFN(1, "No union descriptor!\n"); sc->sc_ifaces_index[0] = uaa->info.bIfaceIndex; sc->sc_ifaces_index[1] = uaa->info.bIfaceIndex; goto alloc_transfers; } data_iface_no = ud->bSlaveInterface[0]; for (i = 0;; i++) { iface = usbd_get_iface(uaa->device, i); if (iface) { id = usbd_get_interface_descriptor(iface); if (id && (id->bInterfaceNumber == data_iface_no)) { sc->sc_ifaces_index[0] = i; sc->sc_ifaces_index[1] = uaa->info.bIfaceIndex; usbd_set_parent_iface(uaa->device, i, uaa->info.bIfaceIndex); break; } } else { device_printf(dev, "no data interface found\n"); goto detach; } } /* * * * The Data Class interface of a networking device shall have * a minimum of two interface settings. The first setting * (the default interface setting) includes no endpoints and * therefore no networking traffic is exchanged whenever the * default interface setting is selected. One or more * additional interface settings are used for normal * operation, and therefore each includes a pair of endpoints * (one IN, and one OUT) to exchange network traffic. Select * an alternate interface setting to initialize the network * aspects of the device and to enable the exchange of * network traffic. * * * * Some devices, most notably cable modems, include interface * settings that have no IN or OUT endpoint, therefore loop * through the list of all available interface settings * looking for one with both IN and OUT endpoints. */ alloc_transfers: pcfg = cdce_config; /* Default Configuration */ for (i = 0; i != 32; i++) { error = usbd_set_alt_interface_index(uaa->device, sc->sc_ifaces_index[0], i); if (error) break; #if CDCE_HAVE_NCM if ((i == 0) && (cdce_ncm_init(sc) == 0)) pcfg = cdce_ncm_config; #endif error = usbd_transfer_setup(uaa->device, sc->sc_ifaces_index, sc->sc_xfer, pcfg, CDCE_N_TRANSFER, sc, &sc->sc_mtx); if (error == 0) break; } if (error || (i == 32)) { device_printf(dev, "No valid alternate " "setting found\n"); goto detach; } ued = usbd_find_descriptor (uaa->device, NULL, uaa->info.bIfaceIndex, UDESC_CS_INTERFACE, 0xFF, UDESCSUB_CDC_ENF, 0xFF); if ((ued == NULL) || (ued->bLength < sizeof(*ued))) { error = USB_ERR_INVAL; } else { error = usbd_req_get_string_any(uaa->device, NULL, eaddr_str, sizeof(eaddr_str), ued->iMacAddress); } if (error) { /* fake MAC address */ device_printf(dev, "faking MAC address\n"); seed = ticks; sc->sc_ue.ue_eaddr[0] = 0x2a; memcpy(&sc->sc_ue.ue_eaddr[1], &seed, sizeof(uint32_t)); sc->sc_ue.ue_eaddr[5] = device_get_unit(dev); } else { memset(sc->sc_ue.ue_eaddr, 0, sizeof(sc->sc_ue.ue_eaddr)); for (i = 0; i != (ETHER_ADDR_LEN * 2); i++) { char c = eaddr_str[i]; if ('0' <= c && c <= '9') c -= '0'; else if (c != 0) c -= 'A' - 10; else break; c &= 0xf; if ((i & 1) == 0) c <<= 4; sc->sc_ue.ue_eaddr[i / 2] |= c; } if (uaa->usb_mode == USB_MODE_DEVICE) { /* * Do not use the same MAC address like the peer ! */ sc->sc_ue.ue_eaddr[5] ^= 0xFF; } } ue->ue_sc = sc; ue->ue_dev = dev; ue->ue_udev = uaa->device; ue->ue_mtx = &sc->sc_mtx; ue->ue_methods = &cdce_ue_methods; error = uether_ifattach(ue); if (error) { device_printf(dev, "could not attach interface\n"); goto detach; } return (0); /* success */ detach: cdce_detach(dev); return (ENXIO); /* failure */ } static int cdce_detach(device_t dev) { struct cdce_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; /* stop all USB transfers first */ usbd_transfer_unsetup(sc->sc_xfer, CDCE_N_TRANSFER); uether_ifdetach(ue); mtx_destroy(&sc->sc_mtx); return (0); } static void cdce_start(struct usb_ether *ue) { struct cdce_softc *sc = uether_getsc(ue); /* * Start the USB transfers, if not already started: */ usbd_transfer_start(sc->sc_xfer[CDCE_BULK_TX]); usbd_transfer_start(sc->sc_xfer[CDCE_BULK_RX]); } static void cdce_free_queue(struct mbuf **ppm, uint8_t n) { uint8_t x; for (x = 0; x != n; x++) { if (ppm[x] != NULL) { m_freem(ppm[x]); ppm[x] = NULL; } } } static void cdce_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct cdce_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct mbuf *m; struct mbuf *mt; uint32_t crc; uint8_t x; int actlen, aframes; usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL); DPRINTFN(1, "\n"); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(11, "transfer complete: %u bytes in %u frames\n", actlen, aframes); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* free all previous TX buffers */ cdce_free_queue(sc->sc_tx_buf, CDCE_FRAMES_MAX); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: for (x = 0; x != CDCE_FRAMES_MAX; x++) { IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; if (sc->sc_flags & CDCE_FLAG_ZAURUS) { /* * Zaurus wants a 32-bit CRC appended * to every frame */ crc = cdce_m_crc32(m, 0, m->m_pkthdr.len); crc = htole32(crc); if (!m_append(m, 4, (void *)&crc)) { m_freem(m); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); continue; } } if (m->m_len != m->m_pkthdr.len) { mt = m_defrag(m, M_NOWAIT); if (mt == NULL) { m_freem(m); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); continue; } m = mt; } if (m->m_pkthdr.len > MCLBYTES) { m->m_pkthdr.len = MCLBYTES; } sc->sc_tx_buf[x] = m; usbd_xfer_set_frame_data(xfer, x, m->m_data, m->m_len); /* * If there's a BPF listener, bounce a copy of * this frame to him: */ BPF_MTAP(ifp, m); } if (x != 0) { usbd_xfer_set_frames(xfer, x); usbd_transfer_submit(xfer); } break; default: /* Error */ DPRINTFN(11, "transfer error, %s\n", usbd_errstr(error)); /* free all previous TX buffers */ cdce_free_queue(sc->sc_tx_buf, CDCE_FRAMES_MAX); /* count output errors */ if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static int32_t cdce_m_crc32_cb(void *arg, void *src, uint32_t count) { uint32_t *p_crc = arg; *p_crc = crc32_raw(src, count, *p_crc); return (0); } static uint32_t cdce_m_crc32(struct mbuf *m, uint32_t src_offset, uint32_t src_len) { uint32_t crc = 0xFFFFFFFF; int error; error = m_apply(m, src_offset, src_len, cdce_m_crc32_cb, &crc); return (crc ^ 0xFFFFFFFF); } static void cdce_init(struct usb_ether *ue) { struct cdce_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); CDCE_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags |= IFF_DRV_RUNNING; /* start interrupt transfer */ usbd_transfer_start(sc->sc_xfer[CDCE_INTR_RX]); usbd_transfer_start(sc->sc_xfer[CDCE_INTR_TX]); /* stall data write direction, which depends on USB mode */ usbd_xfer_set_stall(sc->sc_xfer[CDCE_BULK_TX]); /* start data transfers */ cdce_start(ue); } static void cdce_stop(struct usb_ether *ue) { struct cdce_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); CDCE_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags &= ~IFF_DRV_RUNNING; /* * stop all the transfers, if not already stopped: */ usbd_transfer_stop(sc->sc_xfer[CDCE_BULK_RX]); usbd_transfer_stop(sc->sc_xfer[CDCE_BULK_TX]); usbd_transfer_stop(sc->sc_xfer[CDCE_INTR_RX]); usbd_transfer_stop(sc->sc_xfer[CDCE_INTR_TX]); } static void cdce_setmulti(struct usb_ether *ue) { /* no-op */ return; } static void cdce_setpromisc(struct usb_ether *ue) { /* no-op */ return; } static int cdce_suspend(device_t dev) { device_printf(dev, "Suspending\n"); return (0); } static int cdce_resume(device_t dev) { device_printf(dev, "Resuming\n"); return (0); } static void cdce_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct cdce_softc *sc = usbd_xfer_softc(xfer); struct mbuf *m; uint8_t x; int actlen; int aframes; int len; usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTF("received %u bytes in %u frames\n", actlen, aframes); for (x = 0; x != aframes; x++) { m = sc->sc_rx_buf[x]; sc->sc_rx_buf[x] = NULL; len = usbd_xfer_frame_len(xfer, x); /* Strip off CRC added by Zaurus, if any */ if ((sc->sc_flags & CDCE_FLAG_ZAURUS) && len >= 14) len -= 4; if (len < (int)sizeof(struct ether_header)) { m_freem(m); continue; } /* queue up mbuf */ uether_rxmbuf(&sc->sc_ue, m, len); } /* FALLTHROUGH */ case USB_ST_SETUP: /* * TODO: Implement support for multi frame transfers, * when the USB hardware supports it. */ for (x = 0; x != 1; x++) { if (sc->sc_rx_buf[x] == NULL) { m = uether_newbuf(); if (m == NULL) goto tr_stall; sc->sc_rx_buf[x] = m; } else { m = sc->sc_rx_buf[x]; } usbd_xfer_set_frame_data(xfer, x, m->m_data, m->m_len); } /* set number of frames and start hardware */ usbd_xfer_set_frames(xfer, x); usbd_transfer_submit(xfer); /* flush any received frames */ uether_rxflush(&sc->sc_ue); break; default: /* Error */ DPRINTF("error = %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { tr_stall: /* try to clear stall first */ usbd_xfer_set_stall(xfer); usbd_xfer_set_frames(xfer, 0); usbd_transfer_submit(xfer); break; } /* need to free the RX-mbufs when we are cancelled */ cdce_free_queue(sc->sc_rx_buf, CDCE_FRAMES_MAX); break; } } static void cdce_intr_read_callback(struct usb_xfer *xfer, usb_error_t error) { int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTF("Received %d bytes\n", actlen); /* TODO: decode some indications */ /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* start clear stall */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void cdce_intr_write_callback(struct usb_xfer *xfer, usb_error_t error) { int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTF("Transferred %d bytes\n", actlen); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: #if 0 usbd_xfer_set_frame_len(xfer, 0, XXX); usbd_transfer_submit(xfer); #endif break; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* start clear stall */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static int cdce_handle_request(device_t dev, const void *req, void **pptr, uint16_t *plen, uint16_t offset, uint8_t *pstate) { return (ENXIO); /* use builtin handler */ } #if CDCE_HAVE_NCM static void cdce_ncm_tx_zero(struct usb_page_cache *pc, uint32_t start, uint32_t end) { if (start >= CDCE_NCM_TX_MAXLEN) return; if (end > CDCE_NCM_TX_MAXLEN) end = CDCE_NCM_TX_MAXLEN; usbd_frame_zero(pc, start, end - start); } static uint8_t cdce_ncm_fill_tx_frames(struct usb_xfer *xfer, uint8_t index) { struct cdce_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct usb_page_cache *pc = usbd_xfer_get_frame(xfer, index); struct mbuf *m; uint32_t rem; uint32_t offset; uint32_t last_offset; uint16_t n; uint8_t retval; usbd_xfer_set_frame_offset(xfer, index * CDCE_NCM_TX_MAXLEN, index); offset = sizeof(sc->sc_ncm.hdr) + sizeof(sc->sc_ncm.dpt) + sizeof(sc->sc_ncm.dp); /* Store last valid offset before alignment */ last_offset = offset; /* Align offset */ offset = CDCE_NCM_ALIGN(sc->sc_ncm.tx_remainder, offset, sc->sc_ncm.tx_modulus); /* Zero pad */ cdce_ncm_tx_zero(pc, last_offset, offset); /* buffer full */ retval = 2; for (n = 0; n != sc->sc_ncm.tx_nframe; n++) { /* check if end of transmit buffer is reached */ if (offset >= sc->sc_ncm.tx_max) break; /* compute maximum buffer size */ rem = sc->sc_ncm.tx_max - offset; IFQ_DRV_DEQUEUE(&(ifp->if_snd), m); if (m == NULL) { /* buffer not full */ retval = 1; break; } if (m->m_pkthdr.len > (int)rem) { if (n == 0) { /* The frame won't fit in our buffer */ DPRINTFN(1, "Frame too big to be transmitted!\n"); m_freem(m); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); n--; continue; } /* Wait till next buffer becomes ready */ IFQ_DRV_PREPEND(&(ifp->if_snd), m); break; } usbd_m_copy_in(pc, offset, m, 0, m->m_pkthdr.len); USETW(sc->sc_ncm.dp[n].wFrameLength, m->m_pkthdr.len); USETW(sc->sc_ncm.dp[n].wFrameIndex, offset); /* Update offset */ offset += m->m_pkthdr.len; /* Store last valid offset before alignment */ last_offset = offset; /* Align offset */ offset = CDCE_NCM_ALIGN(sc->sc_ncm.tx_remainder, offset, sc->sc_ncm.tx_modulus); /* Zero pad */ cdce_ncm_tx_zero(pc, last_offset, offset); /* * If there's a BPF listener, bounce a copy * of this frame to him: */ BPF_MTAP(ifp, m); /* Free mbuf */ m_freem(m); /* Pre-increment interface counter */ if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); } if (n == 0) return (0); rem = (sizeof(sc->sc_ncm.dpt) + (4 * n) + 4); USETW(sc->sc_ncm.dpt.wLength, rem); /* zero the rest of the data pointer entries */ for (; n != CDCE_NCM_SUBFRAMES_MAX; n++) { USETW(sc->sc_ncm.dp[n].wFrameLength, 0); USETW(sc->sc_ncm.dp[n].wFrameIndex, 0); } offset = last_offset; /* Align offset */ offset = CDCE_NCM_ALIGN(0, offset, CDCE_NCM_TX_MINLEN); /* Optimise, save bandwidth and force short termination */ if (offset >= sc->sc_ncm.tx_max) offset = sc->sc_ncm.tx_max; else offset ++; /* Zero pad */ cdce_ncm_tx_zero(pc, last_offset, offset); /* set frame length */ usbd_xfer_set_frame_len(xfer, index, offset); /* Fill out 16-bit header */ sc->sc_ncm.hdr.dwSignature[0] = 'N'; sc->sc_ncm.hdr.dwSignature[1] = 'C'; sc->sc_ncm.hdr.dwSignature[2] = 'M'; sc->sc_ncm.hdr.dwSignature[3] = 'H'; USETW(sc->sc_ncm.hdr.wHeaderLength, sizeof(sc->sc_ncm.hdr)); USETW(sc->sc_ncm.hdr.wBlockLength, offset); USETW(sc->sc_ncm.hdr.wSequence, sc->sc_ncm.tx_seq); USETW(sc->sc_ncm.hdr.wDptIndex, sizeof(sc->sc_ncm.hdr)); sc->sc_ncm.tx_seq++; /* Fill out 16-bit frame table header */ sc->sc_ncm.dpt.dwSignature[0] = 'N'; sc->sc_ncm.dpt.dwSignature[1] = 'C'; sc->sc_ncm.dpt.dwSignature[2] = 'M'; sc->sc_ncm.dpt.dwSignature[3] = '0'; USETW(sc->sc_ncm.dpt.wNextNdpIndex, 0); /* reserved */ usbd_copy_in(pc, 0, &(sc->sc_ncm.hdr), sizeof(sc->sc_ncm.hdr)); usbd_copy_in(pc, sizeof(sc->sc_ncm.hdr), &(sc->sc_ncm.dpt), sizeof(sc->sc_ncm.dpt)); usbd_copy_in(pc, sizeof(sc->sc_ncm.hdr) + sizeof(sc->sc_ncm.dpt), &(sc->sc_ncm.dp), sizeof(sc->sc_ncm.dp)); return (retval); } static void cdce_ncm_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct cdce_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); uint16_t x; uint8_t temp; int actlen; int aframes; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL); DPRINTFN(10, "transfer complete: " "%u bytes in %u frames\n", actlen, aframes); case USB_ST_SETUP: for (x = 0; x != CDCE_NCM_TX_FRAMES_MAX; x++) { temp = cdce_ncm_fill_tx_frames(xfer, x); if (temp == 0) break; if (temp == 1) { x++; break; } } if (x != 0) { #ifdef USB_DEBUG usbd_xfer_set_interval(xfer, cdce_tx_interval); #endif usbd_xfer_set_frames(xfer, x); usbd_transfer_submit(xfer); } break; default: /* Error */ DPRINTFN(10, "Transfer error: %s\n", usbd_errstr(error)); /* update error counter */ if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); usbd_xfer_set_frames(xfer, 0); usbd_transfer_submit(xfer); } break; } } static void cdce_ncm_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct cdce_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc = usbd_xfer_get_frame(xfer, 0); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct mbuf *m; int sumdata; int sumlen; int actlen; int aframes; int temp; int nframes; int x; int offset; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: usbd_xfer_status(xfer, &actlen, &sumlen, &aframes, NULL); DPRINTFN(1, "received %u bytes in %u frames\n", actlen, aframes); if (actlen < (int)(sizeof(sc->sc_ncm.hdr) + sizeof(sc->sc_ncm.dpt))) { DPRINTFN(1, "frame too short\n"); goto tr_setup; } usbd_copy_out(pc, 0, &(sc->sc_ncm.hdr), sizeof(sc->sc_ncm.hdr)); if ((sc->sc_ncm.hdr.dwSignature[0] != 'N') || (sc->sc_ncm.hdr.dwSignature[1] != 'C') || (sc->sc_ncm.hdr.dwSignature[2] != 'M') || (sc->sc_ncm.hdr.dwSignature[3] != 'H')) { DPRINTFN(1, "invalid HDR signature: " "0x%02x:0x%02x:0x%02x:0x%02x\n", sc->sc_ncm.hdr.dwSignature[0], sc->sc_ncm.hdr.dwSignature[1], sc->sc_ncm.hdr.dwSignature[2], sc->sc_ncm.hdr.dwSignature[3]); goto tr_stall; } temp = UGETW(sc->sc_ncm.hdr.wBlockLength); if (temp > sumlen) { DPRINTFN(1, "unsupported block length %u/%u\n", temp, sumlen); goto tr_stall; } temp = UGETW(sc->sc_ncm.hdr.wDptIndex); if ((int)(temp + sizeof(sc->sc_ncm.dpt)) > actlen) { DPRINTFN(1, "invalid DPT index: 0x%04x\n", temp); goto tr_stall; } usbd_copy_out(pc, temp, &(sc->sc_ncm.dpt), sizeof(sc->sc_ncm.dpt)); if ((sc->sc_ncm.dpt.dwSignature[0] != 'N') || (sc->sc_ncm.dpt.dwSignature[1] != 'C') || (sc->sc_ncm.dpt.dwSignature[2] != 'M') || (sc->sc_ncm.dpt.dwSignature[3] != '0')) { DPRINTFN(1, "invalid DPT signature" "0x%02x:0x%02x:0x%02x:0x%02x\n", sc->sc_ncm.dpt.dwSignature[0], sc->sc_ncm.dpt.dwSignature[1], sc->sc_ncm.dpt.dwSignature[2], sc->sc_ncm.dpt.dwSignature[3]); goto tr_stall; } nframes = UGETW(sc->sc_ncm.dpt.wLength) / 4; /* Subtract size of header and last zero padded entry */ if (nframes >= (2 + 1)) nframes -= (2 + 1); else nframes = 0; DPRINTFN(1, "nframes = %u\n", nframes); temp += sizeof(sc->sc_ncm.dpt); if ((temp + (4 * nframes)) > actlen) goto tr_stall; if (nframes > CDCE_NCM_SUBFRAMES_MAX) { DPRINTFN(1, "Truncating number of frames from %u to %u\n", nframes, CDCE_NCM_SUBFRAMES_MAX); nframes = CDCE_NCM_SUBFRAMES_MAX; } usbd_copy_out(pc, temp, &(sc->sc_ncm.dp), (4 * nframes)); sumdata = 0; for (x = 0; x != nframes; x++) { offset = UGETW(sc->sc_ncm.dp[x].wFrameIndex); temp = UGETW(sc->sc_ncm.dp[x].wFrameLength); if ((offset == 0) || (temp < (int)sizeof(struct ether_header)) || (temp > (MCLBYTES - ETHER_ALIGN))) { DPRINTFN(1, "NULL frame detected at %d\n", x); m = NULL; /* silently ignore this frame */ continue; } else if ((offset + temp) > actlen) { DPRINTFN(1, "invalid frame " "detected at %d\n", x); m = NULL; /* silently ignore this frame */ continue; } else if (temp > (int)(MHLEN - ETHER_ALIGN)) { m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); } else { m = m_gethdr(M_NOWAIT, MT_DATA); } DPRINTFN(16, "frame %u, offset = %u, length = %u \n", x, offset, temp); /* check if we have a buffer */ if (m) { m_adj(m, ETHER_ALIGN); usbd_copy_out(pc, offset, m->m_data, temp); /* enqueue */ uether_rxmbuf(&sc->sc_ue, m, temp); sumdata += temp; } else { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); } } DPRINTFN(1, "Efficiency: %u/%u bytes\n", sumdata, actlen); case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, sc->sc_ncm.rx_max); usbd_xfer_set_frames(xfer, 1); usbd_transfer_submit(xfer); uether_rxflush(&sc->sc_ue); /* must be last */ break; default: /* Error */ DPRINTFN(1, "error = %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { tr_stall: /* try to clear stall first */ usbd_xfer_set_stall(xfer); usbd_xfer_set_frames(xfer, 0); usbd_transfer_submit(xfer); } break; } } #endif Index: head/sys/dev/usb/net/if_cue.c =================================================================== --- head/sys/dev/usb/net/if_cue.c (revision 276700) +++ head/sys/dev/usb/net/if_cue.c (revision 276701) @@ -1,654 +1,654 @@ /*- * Copyright (c) 1997, 1998, 1999, 2000 * Bill Paul . All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Bill Paul. * 4. Neither the name of the author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * CATC USB-EL1210A USB to ethernet driver. Used in the CATC Netmate * adapters and others. * * Written by Bill Paul * Electrical Engineering Department * Columbia University, New York City */ /* * The CATC USB-EL1210A provides USB ethernet support at 10Mbps. The * RX filter uses a 512-bit multicast hash table, single perfect entry * for the station address, and promiscuous mode. Unlike the ADMtek * and KLSI chips, the CATC ASIC supports read and write combining * mode where multiple packets can be transfered using a single bulk * transaction, which helps performance a great deal. */ #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 "usbdevs.h" #define USB_DEBUG_VAR cue_debug #include #include #include #include /* * Various supported device vendors/products. */ /* Belkin F5U111 adapter covered by NETMATE entry */ static const STRUCT_USB_HOST_ID cue_devs[] = { #define CUE_DEV(v,p) { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) } CUE_DEV(CATC, NETMATE), CUE_DEV(CATC, NETMATE2), CUE_DEV(SMARTBRIDGES, SMARTLINK), #undef CUE_DEV }; /* prototypes */ static device_probe_t cue_probe; static device_attach_t cue_attach; static device_detach_t cue_detach; static usb_callback_t cue_bulk_read_callback; static usb_callback_t cue_bulk_write_callback; static uether_fn_t cue_attach_post; static uether_fn_t cue_init; static uether_fn_t cue_stop; static uether_fn_t cue_start; static uether_fn_t cue_tick; static uether_fn_t cue_setmulti; static uether_fn_t cue_setpromisc; static uint8_t cue_csr_read_1(struct cue_softc *, uint16_t); static uint16_t cue_csr_read_2(struct cue_softc *, uint8_t); static int cue_csr_write_1(struct cue_softc *, uint16_t, uint16_t); static int cue_mem(struct cue_softc *, uint8_t, uint16_t, void *, int); static int cue_getmac(struct cue_softc *, void *); static uint32_t cue_mchash(const uint8_t *); static void cue_reset(struct cue_softc *); #ifdef USB_DEBUG static int cue_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, cue, CTLFLAG_RW, 0, "USB cue"); -SYSCTL_INT(_hw_usb_cue, OID_AUTO, debug, CTLFLAG_RW, &cue_debug, 0, +SYSCTL_INT(_hw_usb_cue, OID_AUTO, debug, CTLFLAG_RWTUN, &cue_debug, 0, "Debug level"); #endif static const struct usb_config cue_config[CUE_N_TRANSFER] = { [CUE_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = (MCLBYTES + 2), .flags = {.pipe_bof = 1,}, .callback = cue_bulk_write_callback, .timeout = 10000, /* 10 seconds */ }, [CUE_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = (MCLBYTES + 2), .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = cue_bulk_read_callback, }, }; static device_method_t cue_methods[] = { /* Device interface */ DEVMETHOD(device_probe, cue_probe), DEVMETHOD(device_attach, cue_attach), DEVMETHOD(device_detach, cue_detach), DEVMETHOD_END }; static driver_t cue_driver = { .name = "cue", .methods = cue_methods, .size = sizeof(struct cue_softc), }; static devclass_t cue_devclass; DRIVER_MODULE(cue, uhub, cue_driver, cue_devclass, NULL, 0); MODULE_DEPEND(cue, uether, 1, 1, 1); MODULE_DEPEND(cue, usb, 1, 1, 1); MODULE_DEPEND(cue, ether, 1, 1, 1); MODULE_VERSION(cue, 1); static const struct usb_ether_methods cue_ue_methods = { .ue_attach_post = cue_attach_post, .ue_start = cue_start, .ue_init = cue_init, .ue_stop = cue_stop, .ue_tick = cue_tick, .ue_setmulti = cue_setmulti, .ue_setpromisc = cue_setpromisc, }; #define CUE_SETBIT(sc, reg, x) \ cue_csr_write_1(sc, reg, cue_csr_read_1(sc, reg) | (x)) #define CUE_CLRBIT(sc, reg, x) \ cue_csr_write_1(sc, reg, cue_csr_read_1(sc, reg) & ~(x)) static uint8_t cue_csr_read_1(struct cue_softc *sc, uint16_t reg) { struct usb_device_request req; uint8_t val; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = CUE_CMD_READREG; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, 1); if (uether_do_request(&sc->sc_ue, &req, &val, 1000)) { /* ignore any errors */ } return (val); } static uint16_t cue_csr_read_2(struct cue_softc *sc, uint8_t reg) { struct usb_device_request req; uint16_t val; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = CUE_CMD_READREG; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, 2); (void)uether_do_request(&sc->sc_ue, &req, &val, 1000); return (le16toh(val)); } static int cue_csr_write_1(struct cue_softc *sc, uint16_t reg, uint16_t val) { struct usb_device_request req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = CUE_CMD_WRITEREG; USETW(req.wValue, val); USETW(req.wIndex, reg); USETW(req.wLength, 0); return (uether_do_request(&sc->sc_ue, &req, NULL, 1000)); } static int cue_mem(struct cue_softc *sc, uint8_t cmd, uint16_t addr, void *buf, int len) { struct usb_device_request req; if (cmd == CUE_CMD_READSRAM) req.bmRequestType = UT_READ_VENDOR_DEVICE; else req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = cmd; USETW(req.wValue, 0); USETW(req.wIndex, addr); USETW(req.wLength, len); return (uether_do_request(&sc->sc_ue, &req, buf, 1000)); } static int cue_getmac(struct cue_softc *sc, void *buf) { struct usb_device_request req; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = CUE_CMD_GET_MACADDR; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, ETHER_ADDR_LEN); return (uether_do_request(&sc->sc_ue, &req, buf, 1000)); } #define CUE_BITS 9 static uint32_t cue_mchash(const uint8_t *addr) { uint32_t crc; /* Compute CRC for the address value. */ crc = ether_crc32_le(addr, ETHER_ADDR_LEN); return (crc & ((1 << CUE_BITS) - 1)); } static void cue_setpromisc(struct usb_ether *ue) { struct cue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); CUE_LOCK_ASSERT(sc, MA_OWNED); /* if we want promiscuous mode, set the allframes bit */ if (ifp->if_flags & IFF_PROMISC) CUE_SETBIT(sc, CUE_ETHCTL, CUE_ETHCTL_PROMISC); else CUE_CLRBIT(sc, CUE_ETHCTL, CUE_ETHCTL_PROMISC); /* write multicast hash-bits */ cue_setmulti(ue); } static void cue_setmulti(struct usb_ether *ue) { struct cue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); struct ifmultiaddr *ifma; uint32_t h = 0, i; uint8_t hashtbl[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; CUE_LOCK_ASSERT(sc, MA_OWNED); if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) { for (i = 0; i < 8; i++) hashtbl[i] = 0xff; cue_mem(sc, CUE_CMD_WRITESRAM, CUE_MCAST_TABLE_ADDR, &hashtbl, 8); return; } /* now program new ones */ if_maddr_rlock(ifp); TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) { if (ifma->ifma_addr->sa_family != AF_LINK) continue; h = cue_mchash(LLADDR((struct sockaddr_dl *)ifma->ifma_addr)); hashtbl[h >> 3] |= 1 << (h & 0x7); } if_maddr_runlock(ifp); /* * Also include the broadcast address in the filter * so we can receive broadcast frames. */ if (ifp->if_flags & IFF_BROADCAST) { h = cue_mchash(ifp->if_broadcastaddr); hashtbl[h >> 3] |= 1 << (h & 0x7); } cue_mem(sc, CUE_CMD_WRITESRAM, CUE_MCAST_TABLE_ADDR, &hashtbl, 8); } static void cue_reset(struct cue_softc *sc) { struct usb_device_request req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = CUE_CMD_RESET; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, 0); if (uether_do_request(&sc->sc_ue, &req, NULL, 1000)) { /* ignore any errors */ } /* * wait a little while for the chip to get its brains in order: */ uether_pause(&sc->sc_ue, hz / 100); } static void cue_attach_post(struct usb_ether *ue) { struct cue_softc *sc = uether_getsc(ue); cue_getmac(sc, ue->ue_eaddr); } static int cue_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != CUE_CONFIG_IDX) return (ENXIO); if (uaa->info.bIfaceIndex != CUE_IFACE_IDX) return (ENXIO); return (usbd_lookup_id_by_uaa(cue_devs, sizeof(cue_devs), uaa)); } /* * Attach the interface. Allocate softc structures, do ifmedia * setup and ethernet/BPF attach. */ static int cue_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct cue_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; uint8_t iface_index; int error; device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF); iface_index = CUE_IFACE_IDX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, cue_config, CUE_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(dev, "allocating USB transfers failed\n"); goto detach; } ue->ue_sc = sc; ue->ue_dev = dev; ue->ue_udev = uaa->device; ue->ue_mtx = &sc->sc_mtx; ue->ue_methods = &cue_ue_methods; error = uether_ifattach(ue); if (error) { device_printf(dev, "could not attach interface\n"); goto detach; } return (0); /* success */ detach: cue_detach(dev); return (ENXIO); /* failure */ } static int cue_detach(device_t dev) { struct cue_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; usbd_transfer_unsetup(sc->sc_xfer, CUE_N_TRANSFER); uether_ifdetach(ue); mtx_destroy(&sc->sc_mtx); return (0); } static void cue_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct cue_softc *sc = usbd_xfer_softc(xfer); struct usb_ether *ue = &sc->sc_ue; struct ifnet *ifp = uether_getifp(ue); struct usb_page_cache *pc; uint8_t buf[2]; int len; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen <= (int)(2 + sizeof(struct ether_header))) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, buf, 2); actlen -= 2; len = buf[0] | (buf[1] << 8); len = min(actlen, len); uether_rxbuf(ue, pc, 2, len); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); uether_rxflush(ue); return; default: /* Error */ DPRINTF("bulk read error, %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void cue_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct cue_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct usb_page_cache *pc; struct mbuf *m; uint8_t buf[2]; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(11, "transfer complete\n"); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) return; if (m->m_pkthdr.len > MCLBYTES) m->m_pkthdr.len = MCLBYTES; usbd_xfer_set_frame_len(xfer, 0, (m->m_pkthdr.len + 2)); /* the first two bytes are the frame length */ buf[0] = (uint8_t)(m->m_pkthdr.len); buf[1] = (uint8_t)(m->m_pkthdr.len >> 8); pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, buf, 2); usbd_m_copy_in(pc, 2, m, 0, m->m_pkthdr.len); /* * If there's a BPF listener, bounce a copy of this frame * to him. */ BPF_MTAP(ifp, m); m_freem(m); usbd_transfer_submit(xfer); return; default: /* Error */ DPRINTFN(11, "transfer error, %s\n", usbd_errstr(error)); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void cue_tick(struct usb_ether *ue) { struct cue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); CUE_LOCK_ASSERT(sc, MA_OWNED); if_inc_counter(ifp, IFCOUNTER_COLLISIONS, cue_csr_read_2(sc, CUE_TX_SINGLECOLL)); if_inc_counter(ifp, IFCOUNTER_COLLISIONS, cue_csr_read_2(sc, CUE_TX_MULTICOLL)); if_inc_counter(ifp, IFCOUNTER_COLLISIONS, cue_csr_read_2(sc, CUE_TX_EXCESSCOLL)); if (cue_csr_read_2(sc, CUE_RX_FRAMEERR)) if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); } static void cue_start(struct usb_ether *ue) { struct cue_softc *sc = uether_getsc(ue); /* * start the USB transfers, if not already started: */ usbd_transfer_start(sc->sc_xfer[CUE_BULK_DT_RD]); usbd_transfer_start(sc->sc_xfer[CUE_BULK_DT_WR]); } static void cue_init(struct usb_ether *ue) { struct cue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); int i; CUE_LOCK_ASSERT(sc, MA_OWNED); /* * Cancel pending I/O and free all RX/TX buffers. */ cue_stop(ue); #if 0 cue_reset(sc); #endif /* Set MAC address */ for (i = 0; i < ETHER_ADDR_LEN; i++) cue_csr_write_1(sc, CUE_PAR0 - i, IF_LLADDR(ifp)[i]); /* Enable RX logic. */ cue_csr_write_1(sc, CUE_ETHCTL, CUE_ETHCTL_RX_ON | CUE_ETHCTL_MCAST_ON); /* Load the multicast filter */ cue_setpromisc(ue); /* * Set the number of RX and TX buffers that we want * to reserve inside the ASIC. */ cue_csr_write_1(sc, CUE_RX_BUFPKTS, CUE_RX_FRAMES); cue_csr_write_1(sc, CUE_TX_BUFPKTS, CUE_TX_FRAMES); /* Set advanced operation modes. */ cue_csr_write_1(sc, CUE_ADVANCED_OPMODES, CUE_AOP_EMBED_RXLEN | 0x01);/* 1 wait state */ /* Program the LED operation. */ cue_csr_write_1(sc, CUE_LEDCTL, CUE_LEDCTL_FOLLOW_LINK); usbd_xfer_set_stall(sc->sc_xfer[CUE_BULK_DT_WR]); ifp->if_drv_flags |= IFF_DRV_RUNNING; cue_start(ue); } /* * Stop the adapter and free any mbufs allocated to the * RX and TX lists. */ static void cue_stop(struct usb_ether *ue) { struct cue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); CUE_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags &= ~IFF_DRV_RUNNING; /* * stop all the transfers, if not already stopped: */ usbd_transfer_stop(sc->sc_xfer[CUE_BULK_DT_WR]); usbd_transfer_stop(sc->sc_xfer[CUE_BULK_DT_RD]); cue_csr_write_1(sc, CUE_ETHCTL, 0); cue_reset(sc); } Index: head/sys/dev/usb/net/if_ipheth.c =================================================================== --- head/sys/dev/usb/net/if_ipheth.c (revision 276700) +++ head/sys/dev/usb/net/if_ipheth.c (revision 276701) @@ -1,545 +1,545 @@ /*- * Copyright (c) 2010 Hans Petter Selasky. All rights reserved. * Copyright (c) 2009 Diego Giagio. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Thanks to Diego Giagio for figuring out the programming details for * the Apple iPhone Ethernet driver. */ #include __FBSDID("$FreeBSD$"); #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 "usbdevs.h" #define USB_DEBUG_VAR ipheth_debug #include #include #include #include static device_probe_t ipheth_probe; static device_attach_t ipheth_attach; static device_detach_t ipheth_detach; static usb_callback_t ipheth_bulk_write_callback; static usb_callback_t ipheth_bulk_read_callback; static uether_fn_t ipheth_attach_post; static uether_fn_t ipheth_tick; static uether_fn_t ipheth_init; static uether_fn_t ipheth_stop; static uether_fn_t ipheth_start; static uether_fn_t ipheth_setmulti; static uether_fn_t ipheth_setpromisc; #ifdef USB_DEBUG static int ipheth_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, ipheth, CTLFLAG_RW, 0, "USB iPhone ethernet"); -SYSCTL_INT(_hw_usb_ipheth, OID_AUTO, debug, CTLFLAG_RW, &ipheth_debug, 0, "Debug level"); +SYSCTL_INT(_hw_usb_ipheth, OID_AUTO, debug, CTLFLAG_RWTUN, &ipheth_debug, 0, "Debug level"); #endif static const struct usb_config ipheth_config[IPHETH_N_TRANSFER] = { [IPHETH_BULK_RX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_RX, .frames = IPHETH_RX_FRAMES_MAX, .bufsize = (IPHETH_RX_FRAMES_MAX * MCLBYTES), .flags = {.short_frames_ok = 1,.short_xfer_ok = 1,.ext_buffer = 1,}, .callback = ipheth_bulk_read_callback, .timeout = 0, /* no timeout */ }, [IPHETH_BULK_TX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_TX, .frames = IPHETH_TX_FRAMES_MAX, .bufsize = (IPHETH_TX_FRAMES_MAX * IPHETH_BUF_SIZE), .flags = {.force_short_xfer = 1,}, .callback = ipheth_bulk_write_callback, .timeout = IPHETH_TX_TIMEOUT, }, }; static device_method_t ipheth_methods[] = { /* Device interface */ DEVMETHOD(device_probe, ipheth_probe), DEVMETHOD(device_attach, ipheth_attach), DEVMETHOD(device_detach, ipheth_detach), DEVMETHOD_END }; static driver_t ipheth_driver = { .name = "ipheth", .methods = ipheth_methods, .size = sizeof(struct ipheth_softc), }; static devclass_t ipheth_devclass; DRIVER_MODULE(ipheth, uhub, ipheth_driver, ipheth_devclass, NULL, 0); MODULE_VERSION(ipheth, 1); MODULE_DEPEND(ipheth, uether, 1, 1, 1); MODULE_DEPEND(ipheth, usb, 1, 1, 1); MODULE_DEPEND(ipheth, ether, 1, 1, 1); static const struct usb_ether_methods ipheth_ue_methods = { .ue_attach_post = ipheth_attach_post, .ue_start = ipheth_start, .ue_init = ipheth_init, .ue_tick = ipheth_tick, .ue_stop = ipheth_stop, .ue_setmulti = ipheth_setmulti, .ue_setpromisc = ipheth_setpromisc, }; #define IPHETH_ID(v,p,c,sc,pt) \ USB_VENDOR(v), USB_PRODUCT(p), \ USB_IFACE_CLASS(c), USB_IFACE_SUBCLASS(sc), \ USB_IFACE_PROTOCOL(pt) static const STRUCT_USB_HOST_ID ipheth_devs[] = { #if 0 {IPHETH_ID(USB_VENDOR_APPLE, USB_PRODUCT_APPLE_IPHONE, IPHETH_USBINTF_CLASS, IPHETH_USBINTF_SUBCLASS, IPHETH_USBINTF_PROTO)}, {IPHETH_ID(USB_VENDOR_APPLE, USB_PRODUCT_APPLE_IPHONE_3G, IPHETH_USBINTF_CLASS, IPHETH_USBINTF_SUBCLASS, IPHETH_USBINTF_PROTO)}, {IPHETH_ID(USB_VENDOR_APPLE, USB_PRODUCT_APPLE_IPHONE_3GS, IPHETH_USBINTF_CLASS, IPHETH_USBINTF_SUBCLASS, IPHETH_USBINTF_PROTO)}, {IPHETH_ID(USB_VENDOR_APPLE, USB_PRODUCT_APPLE_IPHONE_4, IPHETH_USBINTF_CLASS, IPHETH_USBINTF_SUBCLASS, IPHETH_USBINTF_PROTO)}, {IPHETH_ID(USB_VENDOR_APPLE, USB_PRODUCT_APPLE_IPHONE_4S, IPHETH_USBINTF_CLASS, IPHETH_USBINTF_SUBCLASS, IPHETH_USBINTF_PROTO)}, {IPHETH_ID(USB_VENDOR_APPLE, USB_PRODUCT_APPLE_IPHONE_5, IPHETH_USBINTF_CLASS, IPHETH_USBINTF_SUBCLASS, IPHETH_USBINTF_PROTO)}, #else /* product agnostic interface match */ {USB_VENDOR(USB_VENDOR_APPLE), USB_IFACE_CLASS(IPHETH_USBINTF_CLASS), USB_IFACE_SUBCLASS(IPHETH_USBINTF_SUBCLASS), USB_IFACE_PROTOCOL(IPHETH_USBINTF_PROTO)}, #endif }; static int ipheth_get_mac_addr(struct ipheth_softc *sc) { struct usb_device_request req; int error; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = IPHETH_CMD_GET_MACADDR; req.wValue[0] = 0; req.wValue[1] = 0; req.wIndex[0] = sc->sc_iface_no; req.wIndex[1] = 0; req.wLength[0] = ETHER_ADDR_LEN; req.wLength[1] = 0; error = usbd_do_request(sc->sc_ue.ue_udev, NULL, &req, sc->sc_data); if (error) return (error); memcpy(sc->sc_ue.ue_eaddr, sc->sc_data, ETHER_ADDR_LEN); return (0); } static int ipheth_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); return (usbd_lookup_id_by_uaa(ipheth_devs, sizeof(ipheth_devs), uaa)); } static int ipheth_attach(device_t dev) { struct ipheth_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; struct usb_attach_arg *uaa = device_get_ivars(dev); int error; sc->sc_iface_no = uaa->info.bIfaceIndex; device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF); error = usbd_set_alt_interface_index(uaa->device, uaa->info.bIfaceIndex, IPHETH_ALT_INTFNUM); if (error) { device_printf(dev, "Cannot set alternate setting\n"); goto detach; } error = usbd_transfer_setup(uaa->device, &sc->sc_iface_no, sc->sc_xfer, ipheth_config, IPHETH_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(dev, "Cannot setup USB transfers\n"); goto detach; } ue->ue_sc = sc; ue->ue_dev = dev; ue->ue_udev = uaa->device; ue->ue_mtx = &sc->sc_mtx; ue->ue_methods = &ipheth_ue_methods; error = ipheth_get_mac_addr(sc); if (error) { device_printf(dev, "Cannot get MAC address\n"); goto detach; } error = uether_ifattach(ue); if (error) { device_printf(dev, "could not attach interface\n"); goto detach; } return (0); /* success */ detach: ipheth_detach(dev); return (ENXIO); /* failure */ } static int ipheth_detach(device_t dev) { struct ipheth_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; /* stop all USB transfers first */ usbd_transfer_unsetup(sc->sc_xfer, IPHETH_N_TRANSFER); uether_ifdetach(ue); mtx_destroy(&sc->sc_mtx); return (0); } static void ipheth_start(struct usb_ether *ue) { struct ipheth_softc *sc = uether_getsc(ue); /* * Start the USB transfers, if not already started: */ usbd_transfer_start(sc->sc_xfer[IPHETH_BULK_TX]); usbd_transfer_start(sc->sc_xfer[IPHETH_BULK_RX]); } static void ipheth_stop(struct usb_ether *ue) { struct ipheth_softc *sc = uether_getsc(ue); /* * Stop the USB transfers, if not already stopped: */ usbd_transfer_stop(sc->sc_xfer[IPHETH_BULK_TX]); usbd_transfer_stop(sc->sc_xfer[IPHETH_BULK_RX]); } static void ipheth_tick(struct usb_ether *ue) { struct ipheth_softc *sc = uether_getsc(ue); struct usb_device_request req; int error; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = IPHETH_CMD_CARRIER_CHECK; req.wValue[0] = 0; req.wValue[1] = 0; req.wIndex[0] = sc->sc_iface_no; req.wIndex[1] = 0; req.wLength[0] = IPHETH_CTRL_BUF_SIZE; req.wLength[1] = 0; error = uether_do_request(ue, &req, sc->sc_data, IPHETH_CTRL_TIMEOUT); if (error) return; sc->sc_carrier_on = (sc->sc_data[0] == IPHETH_CARRIER_ON); } static void ipheth_attach_post(struct usb_ether *ue) { } static void ipheth_init(struct usb_ether *ue) { struct ipheth_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); IPHETH_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags |= IFF_DRV_RUNNING; /* stall data write direction, which depends on USB mode */ usbd_xfer_set_stall(sc->sc_xfer[IPHETH_BULK_TX]); /* start data transfers */ ipheth_start(ue); } static void ipheth_setmulti(struct usb_ether *ue) { } static void ipheth_setpromisc(struct usb_ether *ue) { } static void ipheth_free_queue(struct mbuf **ppm, uint8_t n) { uint8_t x; for (x = 0; x != n; x++) { if (ppm[x] != NULL) { m_freem(ppm[x]); ppm[x] = NULL; } } } static void ipheth_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct ipheth_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct usb_page_cache *pc; struct mbuf *m; uint8_t x; int actlen; int aframes; usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL); DPRINTFN(1, "\n"); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(11, "transfer complete: %u bytes in %u frames\n", actlen, aframes); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* free all previous TX buffers */ ipheth_free_queue(sc->sc_tx_buf, IPHETH_TX_FRAMES_MAX); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: for (x = 0; x != IPHETH_TX_FRAMES_MAX; x++) { IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; usbd_xfer_set_frame_offset(xfer, x * IPHETH_BUF_SIZE, x); pc = usbd_xfer_get_frame(xfer, x); sc->sc_tx_buf[x] = m; if (m->m_pkthdr.len > IPHETH_BUF_SIZE) m->m_pkthdr.len = IPHETH_BUF_SIZE; usbd_m_copy_in(pc, 0, m, 0, m->m_pkthdr.len); usbd_xfer_set_frame_len(xfer, x, IPHETH_BUF_SIZE); if (IPHETH_BUF_SIZE != m->m_pkthdr.len) { usbd_frame_zero(pc, m->m_pkthdr.len, IPHETH_BUF_SIZE - m->m_pkthdr.len); } /* * If there's a BPF listener, bounce a copy of * this frame to him: */ BPF_MTAP(ifp, m); } if (x != 0) { usbd_xfer_set_frames(xfer, x); usbd_transfer_submit(xfer); } break; default: /* Error */ DPRINTFN(11, "transfer error, %s\n", usbd_errstr(error)); /* free all previous TX buffers */ ipheth_free_queue(sc->sc_tx_buf, IPHETH_TX_FRAMES_MAX); /* count output errors */ if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void ipheth_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct ipheth_softc *sc = usbd_xfer_softc(xfer); struct mbuf *m; uint8_t x; int actlen; int aframes; int len; usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTF("received %u bytes in %u frames\n", actlen, aframes); for (x = 0; x != aframes; x++) { m = sc->sc_rx_buf[x]; sc->sc_rx_buf[x] = NULL; len = usbd_xfer_frame_len(xfer, x); if (len < (int)(sizeof(struct ether_header) + IPHETH_RX_ADJ)) { m_freem(m); continue; } m_adj(m, IPHETH_RX_ADJ); /* queue up mbuf */ uether_rxmbuf(&sc->sc_ue, m, len - IPHETH_RX_ADJ); } /* FALLTHROUGH */ case USB_ST_SETUP: for (x = 0; x != IPHETH_RX_FRAMES_MAX; x++) { if (sc->sc_rx_buf[x] == NULL) { m = uether_newbuf(); if (m == NULL) goto tr_stall; /* cancel alignment for ethernet */ m_adj(m, ETHER_ALIGN); sc->sc_rx_buf[x] = m; } else { m = sc->sc_rx_buf[x]; } usbd_xfer_set_frame_data(xfer, x, m->m_data, m->m_len); } /* set number of frames and start hardware */ usbd_xfer_set_frames(xfer, x); usbd_transfer_submit(xfer); /* flush any received frames */ uether_rxflush(&sc->sc_ue); break; default: /* Error */ DPRINTF("error = %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { tr_stall: /* try to clear stall first */ usbd_xfer_set_stall(xfer); usbd_xfer_set_frames(xfer, 0); usbd_transfer_submit(xfer); break; } /* need to free the RX-mbufs when we are cancelled */ ipheth_free_queue(sc->sc_rx_buf, IPHETH_RX_FRAMES_MAX); break; } } Index: head/sys/dev/usb/net/if_kue.c =================================================================== --- head/sys/dev/usb/net/if_kue.c (revision 276700) +++ head/sys/dev/usb/net/if_kue.c (revision 276701) @@ -1,711 +1,711 @@ /*- * Copyright (c) 1997, 1998, 1999, 2000 * Bill Paul . All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Bill Paul. * 4. Neither the name of the author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * Kawasaki LSI KL5KUSB101B USB to ethernet adapter driver. * * Written by Bill Paul * Electrical Engineering Department * Columbia University, New York City */ /* * The KLSI USB to ethernet adapter chip contains an USB serial interface, * ethernet MAC and embedded microcontroller (called the QT Engine). * The chip must have firmware loaded into it before it will operate. * Packets are passed between the chip and host via bulk transfers. * There is an interrupt endpoint mentioned in the software spec, however * it's currently unused. This device is 10Mbps half-duplex only, hence * there is no media selection logic. The MAC supports a 128 entry * multicast filter, though the exact size of the filter can depend * on the firmware. Curiously, while the software spec describes various * ethernet statistics counters, my sample adapter and firmware combination * claims not to support any statistics counters at all. * * Note that once we load the firmware in the device, we have to be * careful not to load it again: if you restart your computer but * leave the adapter attached to the USB controller, it may remain * powered on and retain its firmware. In this case, we don't need * to load the firmware a second time. * * Special thanks to Rob Furr for providing an ADS Technologies * adapter for development and testing. No monkeys were harmed during * the development of this driver. */ #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 "usbdevs.h" #define USB_DEBUG_VAR kue_debug #include #include #include #include #include /* * Various supported device vendors/products. */ static const STRUCT_USB_HOST_ID kue_devs[] = { #define KUE_DEV(v,p) { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) } KUE_DEV(3COM, 3C19250), KUE_DEV(3COM, 3C460), KUE_DEV(ABOCOM, URE450), KUE_DEV(ADS, UBS10BT), KUE_DEV(ADS, UBS10BTX), KUE_DEV(AOX, USB101), KUE_DEV(ASANTE, EA), KUE_DEV(ATEN, DSB650C), KUE_DEV(ATEN, UC10T), KUE_DEV(COREGA, ETHER_USB_T), KUE_DEV(DLINK, DSB650C), KUE_DEV(ENTREGA, E45), KUE_DEV(ENTREGA, XX1), KUE_DEV(ENTREGA, XX2), KUE_DEV(IODATA, USBETT), KUE_DEV(JATON, EDA), KUE_DEV(KINGSTON, XX1), KUE_DEV(KLSI, DUH3E10BT), KUE_DEV(KLSI, DUH3E10BTN), KUE_DEV(LINKSYS, USB10T), KUE_DEV(MOBILITY, EA), KUE_DEV(NETGEAR, EA101), KUE_DEV(NETGEAR, EA101X), KUE_DEV(PERACOM, ENET), KUE_DEV(PERACOM, ENET2), KUE_DEV(PERACOM, ENET3), KUE_DEV(PORTGEAR, EA8), KUE_DEV(PORTGEAR, EA9), KUE_DEV(PORTSMITH, EEA), KUE_DEV(SHARK, PA), KUE_DEV(SILICOM, GPE), KUE_DEV(SILICOM, U2E), KUE_DEV(SMC, 2102USB), #undef KUE_DEV }; /* prototypes */ static device_probe_t kue_probe; static device_attach_t kue_attach; static device_detach_t kue_detach; static usb_callback_t kue_bulk_read_callback; static usb_callback_t kue_bulk_write_callback; static uether_fn_t kue_attach_post; static uether_fn_t kue_init; static uether_fn_t kue_stop; static uether_fn_t kue_start; static uether_fn_t kue_setmulti; static uether_fn_t kue_setpromisc; static int kue_do_request(struct kue_softc *, struct usb_device_request *, void *); static int kue_setword(struct kue_softc *, uint8_t, uint16_t); static int kue_ctl(struct kue_softc *, uint8_t, uint8_t, uint16_t, void *, int); static int kue_load_fw(struct kue_softc *); static void kue_reset(struct kue_softc *); #ifdef USB_DEBUG static int kue_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, kue, CTLFLAG_RW, 0, "USB kue"); -SYSCTL_INT(_hw_usb_kue, OID_AUTO, debug, CTLFLAG_RW, &kue_debug, 0, +SYSCTL_INT(_hw_usb_kue, OID_AUTO, debug, CTLFLAG_RWTUN, &kue_debug, 0, "Debug level"); #endif static const struct usb_config kue_config[KUE_N_TRANSFER] = { [KUE_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = (MCLBYTES + 2 + 64), .flags = {.pipe_bof = 1,}, .callback = kue_bulk_write_callback, .timeout = 10000, /* 10 seconds */ }, [KUE_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = (MCLBYTES + 2), .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = kue_bulk_read_callback, .timeout = 0, /* no timeout */ }, }; static device_method_t kue_methods[] = { /* Device interface */ DEVMETHOD(device_probe, kue_probe), DEVMETHOD(device_attach, kue_attach), DEVMETHOD(device_detach, kue_detach), DEVMETHOD_END }; static driver_t kue_driver = { .name = "kue", .methods = kue_methods, .size = sizeof(struct kue_softc), }; static devclass_t kue_devclass; DRIVER_MODULE(kue, uhub, kue_driver, kue_devclass, NULL, 0); MODULE_DEPEND(kue, uether, 1, 1, 1); MODULE_DEPEND(kue, usb, 1, 1, 1); MODULE_DEPEND(kue, ether, 1, 1, 1); MODULE_VERSION(kue, 1); static const struct usb_ether_methods kue_ue_methods = { .ue_attach_post = kue_attach_post, .ue_start = kue_start, .ue_init = kue_init, .ue_stop = kue_stop, .ue_setmulti = kue_setmulti, .ue_setpromisc = kue_setpromisc, }; /* * We have a custom do_request function which is almost like the * regular do_request function, except it has a much longer timeout. * Why? Because we need to make requests over the control endpoint * to download the firmware to the device, which can take longer * than the default timeout. */ static int kue_do_request(struct kue_softc *sc, struct usb_device_request *req, void *data) { usb_error_t err; err = uether_do_request(&sc->sc_ue, req, data, 60000); return (err); } static int kue_setword(struct kue_softc *sc, uint8_t breq, uint16_t word) { struct usb_device_request req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = breq; USETW(req.wValue, word); USETW(req.wIndex, 0); USETW(req.wLength, 0); return (kue_do_request(sc, &req, NULL)); } static int kue_ctl(struct kue_softc *sc, uint8_t rw, uint8_t breq, uint16_t val, void *data, int len) { struct usb_device_request req; if (rw == KUE_CTL_WRITE) req.bmRequestType = UT_WRITE_VENDOR_DEVICE; else req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = breq; USETW(req.wValue, val); USETW(req.wIndex, 0); USETW(req.wLength, len); return (kue_do_request(sc, &req, data)); } static int kue_load_fw(struct kue_softc *sc) { struct usb_device_descriptor *dd; uint16_t hwrev; usb_error_t err; dd = usbd_get_device_descriptor(sc->sc_ue.ue_udev); hwrev = UGETW(dd->bcdDevice); /* * First, check if we even need to load the firmware. * If the device was still attached when the system was * rebooted, it may already have firmware loaded in it. * If this is the case, we don't need to do it again. * And in fact, if we try to load it again, we'll hang, * so we have to avoid this condition if we don't want * to look stupid. * * We can test this quickly by checking the bcdRevision * code. The NIC will return a different revision code if * it's probed while the firmware is still loaded and * running. */ if (hwrev == 0x0202) return(0); /* Load code segment */ err = kue_ctl(sc, KUE_CTL_WRITE, KUE_CMD_SEND_SCAN, 0, kue_code_seg, sizeof(kue_code_seg)); if (err) { device_printf(sc->sc_ue.ue_dev, "failed to load code segment: %s\n", usbd_errstr(err)); return(ENXIO); } /* Load fixup segment */ err = kue_ctl(sc, KUE_CTL_WRITE, KUE_CMD_SEND_SCAN, 0, kue_fix_seg, sizeof(kue_fix_seg)); if (err) { device_printf(sc->sc_ue.ue_dev, "failed to load fixup segment: %s\n", usbd_errstr(err)); return(ENXIO); } /* Send trigger command. */ err = kue_ctl(sc, KUE_CTL_WRITE, KUE_CMD_SEND_SCAN, 0, kue_trig_seg, sizeof(kue_trig_seg)); if (err) { device_printf(sc->sc_ue.ue_dev, "failed to load trigger segment: %s\n", usbd_errstr(err)); return(ENXIO); } return (0); } static void kue_setpromisc(struct usb_ether *ue) { struct kue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); KUE_LOCK_ASSERT(sc, MA_OWNED); if (ifp->if_flags & IFF_PROMISC) sc->sc_rxfilt |= KUE_RXFILT_PROMISC; else sc->sc_rxfilt &= ~KUE_RXFILT_PROMISC; kue_setword(sc, KUE_CMD_SET_PKT_FILTER, sc->sc_rxfilt); } static void kue_setmulti(struct usb_ether *ue) { struct kue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); struct ifmultiaddr *ifma; int i = 0; KUE_LOCK_ASSERT(sc, MA_OWNED); if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) { sc->sc_rxfilt |= KUE_RXFILT_ALLMULTI; sc->sc_rxfilt &= ~KUE_RXFILT_MULTICAST; kue_setword(sc, KUE_CMD_SET_PKT_FILTER, sc->sc_rxfilt); return; } sc->sc_rxfilt &= ~KUE_RXFILT_ALLMULTI; if_maddr_rlock(ifp); TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) { if (ifma->ifma_addr->sa_family != AF_LINK) continue; /* * If there are too many addresses for the * internal filter, switch over to allmulti mode. */ if (i == KUE_MCFILTCNT(sc)) break; memcpy(KUE_MCFILT(sc, i), LLADDR((struct sockaddr_dl *)ifma->ifma_addr), ETHER_ADDR_LEN); i++; } if_maddr_runlock(ifp); if (i == KUE_MCFILTCNT(sc)) sc->sc_rxfilt |= KUE_RXFILT_ALLMULTI; else { sc->sc_rxfilt |= KUE_RXFILT_MULTICAST; kue_ctl(sc, KUE_CTL_WRITE, KUE_CMD_SET_MCAST_FILTERS, i, sc->sc_mcfilters, i * ETHER_ADDR_LEN); } kue_setword(sc, KUE_CMD_SET_PKT_FILTER, sc->sc_rxfilt); } /* * Issue a SET_CONFIGURATION command to reset the MAC. This should be * done after the firmware is loaded into the adapter in order to * bring it into proper operation. */ static void kue_reset(struct kue_softc *sc) { struct usb_config_descriptor *cd; usb_error_t err; cd = usbd_get_config_descriptor(sc->sc_ue.ue_udev); err = usbd_req_set_config(sc->sc_ue.ue_udev, &sc->sc_mtx, cd->bConfigurationValue); if (err) DPRINTF("reset failed (ignored)\n"); /* wait a little while for the chip to get its brains in order */ uether_pause(&sc->sc_ue, hz / 100); } static void kue_attach_post(struct usb_ether *ue) { struct kue_softc *sc = uether_getsc(ue); int error; /* load the firmware into the NIC */ error = kue_load_fw(sc); if (error) { device_printf(sc->sc_ue.ue_dev, "could not load firmware\n"); /* ignore the error */ } /* reset the adapter */ kue_reset(sc); /* read ethernet descriptor */ kue_ctl(sc, KUE_CTL_READ, KUE_CMD_GET_ETHER_DESCRIPTOR, 0, &sc->sc_desc, sizeof(sc->sc_desc)); /* copy in ethernet address */ memcpy(ue->ue_eaddr, sc->sc_desc.kue_macaddr, sizeof(ue->ue_eaddr)); } /* * Probe for a KLSI chip. */ static int kue_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != KUE_CONFIG_IDX) return (ENXIO); if (uaa->info.bIfaceIndex != KUE_IFACE_IDX) return (ENXIO); return (usbd_lookup_id_by_uaa(kue_devs, sizeof(kue_devs), uaa)); } /* * Attach the interface. Allocate softc structures, do * setup and ethernet/BPF attach. */ static int kue_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct kue_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; uint8_t iface_index; int error; device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF); iface_index = KUE_IFACE_IDX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, kue_config, KUE_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(dev, "allocating USB transfers failed\n"); goto detach; } sc->sc_mcfilters = malloc(KUE_MCFILTCNT(sc) * ETHER_ADDR_LEN, M_USBDEV, M_WAITOK); if (sc->sc_mcfilters == NULL) { device_printf(dev, "failed allocating USB memory\n"); goto detach; } ue->ue_sc = sc; ue->ue_dev = dev; ue->ue_udev = uaa->device; ue->ue_mtx = &sc->sc_mtx; ue->ue_methods = &kue_ue_methods; error = uether_ifattach(ue); if (error) { device_printf(dev, "could not attach interface\n"); goto detach; } return (0); /* success */ detach: kue_detach(dev); return (ENXIO); /* failure */ } static int kue_detach(device_t dev) { struct kue_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; usbd_transfer_unsetup(sc->sc_xfer, KUE_N_TRANSFER); uether_ifdetach(ue); mtx_destroy(&sc->sc_mtx); free(sc->sc_mcfilters, M_USBDEV); return (0); } /* * A frame has been uploaded: pass the resulting mbuf chain up to * the higher level protocols. */ static void kue_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct kue_softc *sc = usbd_xfer_softc(xfer); struct usb_ether *ue = &sc->sc_ue; struct ifnet *ifp = uether_getifp(ue); struct usb_page_cache *pc; uint8_t buf[2]; int len; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen <= (int)(2 + sizeof(struct ether_header))) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, buf, 2); actlen -= 2; len = buf[0] | (buf[1] << 8); len = min(actlen, len); uether_rxbuf(ue, pc, 2, len); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); uether_rxflush(ue); return; default: /* Error */ DPRINTF("bulk read error, %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void kue_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct kue_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct usb_page_cache *pc; struct mbuf *m; int total_len; int temp_len; uint8_t buf[2]; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(11, "transfer complete\n"); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) return; if (m->m_pkthdr.len > MCLBYTES) m->m_pkthdr.len = MCLBYTES; temp_len = (m->m_pkthdr.len + 2); total_len = (temp_len + (64 - (temp_len % 64))); /* the first two bytes are the frame length */ buf[0] = (uint8_t)(m->m_pkthdr.len); buf[1] = (uint8_t)(m->m_pkthdr.len >> 8); pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, buf, 2); usbd_m_copy_in(pc, 2, m, 0, m->m_pkthdr.len); usbd_frame_zero(pc, temp_len, total_len - temp_len); usbd_xfer_set_frame_len(xfer, 0, total_len); /* * if there's a BPF listener, bounce a copy * of this frame to him: */ BPF_MTAP(ifp, m); m_freem(m); usbd_transfer_submit(xfer); return; default: /* Error */ DPRINTFN(11, "transfer error, %s\n", usbd_errstr(error)); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void kue_start(struct usb_ether *ue) { struct kue_softc *sc = uether_getsc(ue); /* * start the USB transfers, if not already started: */ usbd_transfer_start(sc->sc_xfer[KUE_BULK_DT_RD]); usbd_transfer_start(sc->sc_xfer[KUE_BULK_DT_WR]); } static void kue_init(struct usb_ether *ue) { struct kue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); KUE_LOCK_ASSERT(sc, MA_OWNED); /* set MAC address */ kue_ctl(sc, KUE_CTL_WRITE, KUE_CMD_SET_MAC, 0, IF_LLADDR(ifp), ETHER_ADDR_LEN); /* I'm not sure how to tune these. */ #if 0 /* * Leave this one alone for now; setting it * wrong causes lockups on some machines/controllers. */ kue_setword(sc, KUE_CMD_SET_SOFS, 1); #endif kue_setword(sc, KUE_CMD_SET_URB_SIZE, 64); /* load the multicast filter */ kue_setpromisc(ue); usbd_xfer_set_stall(sc->sc_xfer[KUE_BULK_DT_WR]); ifp->if_drv_flags |= IFF_DRV_RUNNING; kue_start(ue); } static void kue_stop(struct usb_ether *ue) { struct kue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); KUE_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags &= ~IFF_DRV_RUNNING; /* * stop all the transfers, if not already stopped: */ usbd_transfer_stop(sc->sc_xfer[KUE_BULK_DT_WR]); usbd_transfer_stop(sc->sc_xfer[KUE_BULK_DT_RD]); } Index: head/sys/dev/usb/net/if_mos.c =================================================================== --- head/sys/dev/usb/net/if_mos.c (revision 276700) +++ head/sys/dev/usb/net/if_mos.c (revision 276701) @@ -1,1029 +1,1029 @@ /*- * Copyright (c) 2011 Rick van der Zwet * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /*- * Copyright (c) 2008 Johann Christian Rode * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /*- * Copyright (c) 2005, 2006, 2007 Jonathan Gray * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /*- * Copyright (c) 1997, 1998, 1999, 2000-2003 * Bill Paul . All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Bill Paul. * 4. Neither the name of the author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * Moschip MCS7730/MCS7830/MCS7832 USB to Ethernet controller * The datasheet is available at the following URL: * http://www.moschip.com/data/products/MCS7830/Data%20Sheet_7830.pdf */ /* * The FreeBSD if_mos.c driver is based on various different sources: * The vendor provided driver at the following URL: * http://www.moschip.com/data/products/MCS7830/Driver_FreeBSD_7830.tar.gz * * Mixed together with the OpenBSD if_mos.c driver for validation and checking * and the FreeBSD if_reu.c as reference for the USB Ethernet framework. */ #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 "usbdevs.h" #define USB_DEBUG_VAR mos_debug #include #include #include //#include #include "if_mosreg.h" #ifdef USB_DEBUG static int mos_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, mos, CTLFLAG_RW, 0, "USB mos"); -SYSCTL_INT(_hw_usb_mos, OID_AUTO, debug, CTLFLAG_RW, &mos_debug, 0, +SYSCTL_INT(_hw_usb_mos, OID_AUTO, debug, CTLFLAG_RWTUN, &mos_debug, 0, "Debug level"); #endif #define MOS_DPRINTFN(fmt,...) \ DPRINTF("mos: %s: " fmt "\n",__FUNCTION__,## __VA_ARGS__) #define USB_PRODUCT_MOSCHIP_MCS7730 0x7730 #define USB_PRODUCT_SITECOMEU_LN030 0x0021 /* Various supported device vendors/products. */ static const STRUCT_USB_HOST_ID mos_devs[] = { {USB_VPI(USB_VENDOR_MOSCHIP, USB_PRODUCT_MOSCHIP_MCS7730, MCS7730)}, {USB_VPI(USB_VENDOR_MOSCHIP, USB_PRODUCT_MOSCHIP_MCS7830, MCS7830)}, {USB_VPI(USB_VENDOR_MOSCHIP, USB_PRODUCT_MOSCHIP_MCS7832, MCS7832)}, {USB_VPI(USB_VENDOR_SITECOMEU, USB_PRODUCT_SITECOMEU_LN030, MCS7830)}, }; static int mos_probe(device_t dev); static int mos_attach(device_t dev); static void mos_attach_post(struct usb_ether *ue); static int mos_detach(device_t dev); static void mos_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error); static void mos_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error); static void mos_intr_callback(struct usb_xfer *xfer, usb_error_t error); static void mos_tick(struct usb_ether *); static void mos_start(struct usb_ether *); static void mos_init(struct usb_ether *); static void mos_chip_init(struct mos_softc *); static void mos_stop(struct usb_ether *); static int mos_miibus_readreg(device_t, int, int); static int mos_miibus_writereg(device_t, int, int, int); static void mos_miibus_statchg(device_t); static int mos_ifmedia_upd(struct ifnet *); static void mos_ifmedia_sts(struct ifnet *, struct ifmediareq *); static void mos_reset(struct mos_softc *sc); static int mos_reg_read_1(struct mos_softc *, int); static int mos_reg_read_2(struct mos_softc *, int); static int mos_reg_write_1(struct mos_softc *, int, int); static int mos_reg_write_2(struct mos_softc *, int, int); static int mos_readmac(struct mos_softc *, uint8_t *); static int mos_writemac(struct mos_softc *, uint8_t *); static int mos_write_mcast(struct mos_softc *, u_char *); static void mos_setmulti(struct usb_ether *); static void mos_setpromisc(struct usb_ether *); static const struct usb_config mos_config[MOS_ENDPT_MAX] = { [MOS_ENDPT_TX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = (MCLBYTES + 2), .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = mos_bulk_write_callback, .timeout = 10000, }, [MOS_ENDPT_RX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = (MCLBYTES + 4 + ETHER_CRC_LEN), .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = mos_bulk_read_callback, }, [MOS_ENDPT_INTR] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, .callback = mos_intr_callback, }, }; static device_method_t mos_methods[] = { /* Device interface */ DEVMETHOD(device_probe, mos_probe), DEVMETHOD(device_attach, mos_attach), DEVMETHOD(device_detach, mos_detach), /* MII interface */ DEVMETHOD(miibus_readreg, mos_miibus_readreg), DEVMETHOD(miibus_writereg, mos_miibus_writereg), DEVMETHOD(miibus_statchg, mos_miibus_statchg), DEVMETHOD_END }; static driver_t mos_driver = { .name = "mos", .methods = mos_methods, .size = sizeof(struct mos_softc) }; static devclass_t mos_devclass; DRIVER_MODULE(mos, uhub, mos_driver, mos_devclass, NULL, 0); DRIVER_MODULE(miibus, mos, miibus_driver, miibus_devclass, 0, 0); MODULE_DEPEND(mos, uether, 1, 1, 1); MODULE_DEPEND(mos, usb, 1, 1, 1); MODULE_DEPEND(mos, ether, 1, 1, 1); MODULE_DEPEND(mos, miibus, 1, 1, 1); static const struct usb_ether_methods mos_ue_methods = { .ue_attach_post = mos_attach_post, .ue_start = mos_start, .ue_init = mos_init, .ue_stop = mos_stop, .ue_tick = mos_tick, .ue_setmulti = mos_setmulti, .ue_setpromisc = mos_setpromisc, .ue_mii_upd = mos_ifmedia_upd, .ue_mii_sts = mos_ifmedia_sts, }; static int mos_reg_read_1(struct mos_softc *sc, int reg) { struct usb_device_request req; usb_error_t err; uByte val = 0; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = MOS_UR_READREG; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, 1); err = uether_do_request(&sc->sc_ue, &req, &val, 1000); if (err) { MOS_DPRINTFN("mos_reg_read_1 error, reg: %d\n", reg); return (-1); } return (val); } static int mos_reg_read_2(struct mos_softc *sc, int reg) { struct usb_device_request req; usb_error_t err; uWord val; USETW(val, 0); req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = MOS_UR_READREG; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, 2); err = uether_do_request(&sc->sc_ue, &req, &val, 1000); if (err) { MOS_DPRINTFN("mos_reg_read_2 error, reg: %d", reg); return (-1); } return (UGETW(val)); } static int mos_reg_write_1(struct mos_softc *sc, int reg, int aval) { struct usb_device_request req; usb_error_t err; uByte val; val = aval; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = MOS_UR_WRITEREG; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, 1); err = uether_do_request(&sc->sc_ue, &req, &val, 1000); if (err) { MOS_DPRINTFN("mos_reg_write_1 error, reg: %d", reg); return (-1); } return (0); } static int mos_reg_write_2(struct mos_softc *sc, int reg, int aval) { struct usb_device_request req; usb_error_t err; uWord val; USETW(val, aval); req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = MOS_UR_WRITEREG; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, 2); err = uether_do_request(&sc->sc_ue, &req, &val, 1000); if (err) { MOS_DPRINTFN("mos_reg_write_2 error, reg: %d", reg); return (-1); } return (0); } static int mos_readmac(struct mos_softc *sc, u_char *mac) { struct usb_device_request req; usb_error_t err; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = MOS_UR_READREG; USETW(req.wValue, 0); USETW(req.wIndex, MOS_MAC); USETW(req.wLength, ETHER_ADDR_LEN); err = uether_do_request(&sc->sc_ue, &req, mac, 1000); if (err) { return (-1); } return (0); } static int mos_writemac(struct mos_softc *sc, uint8_t *mac) { struct usb_device_request req; usb_error_t err; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = MOS_UR_WRITEREG; USETW(req.wValue, 0); USETW(req.wIndex, MOS_MAC); USETW(req.wLength, ETHER_ADDR_LEN); err = uether_do_request(&sc->sc_ue, &req, mac, 1000); if (err) { MOS_DPRINTFN("mos_writemac error"); return (-1); } return (0); } static int mos_write_mcast(struct mos_softc *sc, u_char *hashtbl) { struct usb_device_request req; usb_error_t err; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = MOS_UR_WRITEREG; USETW(req.wValue, 0); USETW(req.wIndex, MOS_MCAST_TABLE); USETW(req.wLength, 8); err = uether_do_request(&sc->sc_ue, &req, hashtbl, 1000); if (err) { MOS_DPRINTFN("mos_reg_mcast error"); return (-1); } return (0); } static int mos_miibus_readreg(struct device *dev, int phy, int reg) { struct mos_softc *sc = device_get_softc(dev); uWord val; int i, res, locked; USETW(val, 0); locked = mtx_owned(&sc->sc_mtx); if (!locked) MOS_LOCK(sc); mos_reg_write_2(sc, MOS_PHY_DATA, 0); mos_reg_write_1(sc, MOS_PHY_CTL, (phy & MOS_PHYCTL_PHYADDR) | MOS_PHYCTL_READ); mos_reg_write_1(sc, MOS_PHY_STS, (reg & MOS_PHYSTS_PHYREG) | MOS_PHYSTS_PENDING); for (i = 0; i < MOS_TIMEOUT; i++) { if (mos_reg_read_1(sc, MOS_PHY_STS) & MOS_PHYSTS_READY) break; } if (i == MOS_TIMEOUT) { MOS_DPRINTFN("MII read timeout"); } res = mos_reg_read_2(sc, MOS_PHY_DATA); if (!locked) MOS_UNLOCK(sc); return (res); } static int mos_miibus_writereg(device_t dev, int phy, int reg, int val) { struct mos_softc *sc = device_get_softc(dev); int i, locked; locked = mtx_owned(&sc->sc_mtx); if (!locked) MOS_LOCK(sc); mos_reg_write_2(sc, MOS_PHY_DATA, val); mos_reg_write_1(sc, MOS_PHY_CTL, (phy & MOS_PHYCTL_PHYADDR) | MOS_PHYCTL_WRITE); mos_reg_write_1(sc, MOS_PHY_STS, (reg & MOS_PHYSTS_PHYREG) | MOS_PHYSTS_PENDING); for (i = 0; i < MOS_TIMEOUT; i++) { if (mos_reg_read_1(sc, MOS_PHY_STS) & MOS_PHYSTS_READY) break; } if (i == MOS_TIMEOUT) MOS_DPRINTFN("MII write timeout"); if (!locked) MOS_UNLOCK(sc); return 0; } static void mos_miibus_statchg(device_t dev) { struct mos_softc *sc = device_get_softc(dev); struct mii_data *mii = GET_MII(sc); int val, err, locked; locked = mtx_owned(&sc->sc_mtx); if (!locked) MOS_LOCK(sc); /* disable RX, TX prior to changing FDX, SPEEDSEL */ val = mos_reg_read_1(sc, MOS_CTL); val &= ~(MOS_CTL_TX_ENB | MOS_CTL_RX_ENB); mos_reg_write_1(sc, MOS_CTL, val); /* reset register which counts dropped frames */ mos_reg_write_1(sc, MOS_FRAME_DROP_CNT, 0); if ((mii->mii_media_active & IFM_GMASK) == IFM_FDX) val |= MOS_CTL_FDX_ENB; else val &= ~(MOS_CTL_FDX_ENB); switch (IFM_SUBTYPE(mii->mii_media_active)) { case IFM_100_TX: val |= MOS_CTL_SPEEDSEL; break; case IFM_10_T: val &= ~(MOS_CTL_SPEEDSEL); break; } /* re-enable TX, RX */ val |= (MOS_CTL_TX_ENB | MOS_CTL_RX_ENB); err = mos_reg_write_1(sc, MOS_CTL, val); if (err) MOS_DPRINTFN("media change failed"); if (!locked) MOS_UNLOCK(sc); } /* * Set media options. */ static int mos_ifmedia_upd(struct ifnet *ifp) { struct mos_softc *sc = ifp->if_softc; struct mii_data *mii = GET_MII(sc); struct mii_softc *miisc; int error; MOS_LOCK_ASSERT(sc, MA_OWNED); sc->mos_link = 0; LIST_FOREACH(miisc, &mii->mii_phys, mii_list) PHY_RESET(miisc); error = mii_mediachg(mii); return (error); } /* * Report current media status. */ static void mos_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr) { struct mos_softc *sc = ifp->if_softc; struct mii_data *mii = GET_MII(sc); MOS_LOCK(sc); mii_pollstat(mii); ifmr->ifm_active = mii->mii_media_active; ifmr->ifm_status = mii->mii_media_status; MOS_UNLOCK(sc); } static void mos_setpromisc(struct usb_ether *ue) { struct mos_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); uint8_t rxmode; MOS_LOCK_ASSERT(sc, MA_OWNED); rxmode = mos_reg_read_1(sc, MOS_CTL); /* If we want promiscuous mode, set the allframes bit. */ if (ifp->if_flags & IFF_PROMISC) { rxmode |= MOS_CTL_RX_PROMISC; } else { rxmode &= ~MOS_CTL_RX_PROMISC; } mos_reg_write_1(sc, MOS_CTL, rxmode); } static void mos_setmulti(struct usb_ether *ue) { struct mos_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); struct ifmultiaddr *ifma; uint32_t h = 0; uint8_t rxmode; uint8_t hashtbl[8] = {0, 0, 0, 0, 0, 0, 0, 0}; int allmulti = 0; MOS_LOCK_ASSERT(sc, MA_OWNED); rxmode = mos_reg_read_1(sc, MOS_CTL); if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) allmulti = 1; /* get all new ones */ if_maddr_rlock(ifp); TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) { if (ifma->ifma_addr->sa_family != AF_LINK) { allmulti = 1; continue; }; h = ether_crc32_be(LLADDR((struct sockaddr_dl *) ifma->ifma_addr), ETHER_ADDR_LEN) >> 26; hashtbl[h / 8] |= 1 << (h % 8); } if_maddr_runlock(ifp); /* now program new ones */ if (allmulti == 1) { rxmode |= MOS_CTL_ALLMULTI; mos_reg_write_1(sc, MOS_CTL, rxmode); } else { rxmode &= ~MOS_CTL_ALLMULTI; mos_write_mcast(sc, (void *)&hashtbl); mos_reg_write_1(sc, MOS_CTL, rxmode); } } static void mos_reset(struct mos_softc *sc) { uint8_t ctl; ctl = mos_reg_read_1(sc, MOS_CTL); ctl &= ~(MOS_CTL_RX_PROMISC | MOS_CTL_ALLMULTI | MOS_CTL_TX_ENB | MOS_CTL_RX_ENB); /* Disable RX, TX, promiscuous and allmulticast mode */ mos_reg_write_1(sc, MOS_CTL, ctl); /* Reset frame drop counter register to zero */ mos_reg_write_1(sc, MOS_FRAME_DROP_CNT, 0); /* Wait a little while for the chip to get its brains in order. */ usb_pause_mtx(&sc->sc_mtx, hz / 128); return; } static void mos_chip_init(struct mos_softc *sc) { int i; /* * Rev.C devices have a pause threshold register which needs to be set * at startup. */ if (mos_reg_read_1(sc, MOS_PAUSE_TRHD) != -1) { for (i = 0; i < MOS_PAUSE_REWRITES; i++) mos_reg_write_1(sc, MOS_PAUSE_TRHD, 0); } sc->mos_phyaddrs[0] = 1; sc->mos_phyaddrs[1] = 0xFF; } /* * Probe for a MCS7x30 chip. */ static int mos_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); int retval; if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != MOS_CONFIG_IDX) return (ENXIO); if (uaa->info.bIfaceIndex != MOS_IFACE_IDX) return (ENXIO); retval = usbd_lookup_id_by_uaa(mos_devs, sizeof(mos_devs), uaa); return (retval); } /* * Attach the interface. Allocate softc structures, do ifmedia * setup and ethernet/BPF attach. */ static int mos_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct mos_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; uint8_t iface_index; int error; sc->mos_flags = USB_GET_DRIVER_INFO(uaa); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF); iface_index = MOS_IFACE_IDX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, mos_config, MOS_ENDPT_MAX, sc, &sc->sc_mtx); if (error) { device_printf(dev, "allocating USB transfers failed\n"); goto detach; } ue->ue_sc = sc; ue->ue_dev = dev; ue->ue_udev = uaa->device; ue->ue_mtx = &sc->sc_mtx; ue->ue_methods = &mos_ue_methods; if (sc->mos_flags & MCS7730) { MOS_DPRINTFN("model: MCS7730"); } else if (sc->mos_flags & MCS7830) { MOS_DPRINTFN("model: MCS7830"); } else if (sc->mos_flags & MCS7832) { MOS_DPRINTFN("model: MCS7832"); } error = uether_ifattach(ue); if (error) { device_printf(dev, "could not attach interface\n"); goto detach; } return (0); detach: mos_detach(dev); return (ENXIO); } static void mos_attach_post(struct usb_ether *ue) { struct mos_softc *sc = uether_getsc(ue); int err; /* Read MAC address, inform the world. */ err = mos_readmac(sc, ue->ue_eaddr); if (err) MOS_DPRINTFN("couldn't get MAC address"); MOS_DPRINTFN("address: %s", ether_sprintf(ue->ue_eaddr)); mos_chip_init(sc); } static int mos_detach(device_t dev) { struct mos_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; usbd_transfer_unsetup(sc->sc_xfer, MOS_ENDPT_MAX); uether_ifdetach(ue); mtx_destroy(&sc->sc_mtx); return (0); } /* * A frame has been uploaded: pass the resulting mbuf chain up to * the higher level protocols. */ static void mos_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct mos_softc *sc = usbd_xfer_softc(xfer); struct usb_ether *ue = &sc->sc_ue; struct ifnet *ifp = uether_getifp(ue); uint8_t rxstat = 0; uint32_t actlen; uint16_t pktlen = 0; struct usb_page_cache *pc; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); pc = usbd_xfer_get_frame(xfer, 0); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: MOS_DPRINTFN("actlen : %d", actlen); if (actlen <= 1) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } /* evaluate status byte at the end */ usbd_copy_out(pc, actlen - sizeof(rxstat), &rxstat, sizeof(rxstat)); if (rxstat != MOS_RXSTS_VALID) { MOS_DPRINTFN("erroneous frame received"); if (rxstat & MOS_RXSTS_SHORT_FRAME) MOS_DPRINTFN("frame size less than 64 bytes"); if (rxstat & MOS_RXSTS_LARGE_FRAME) { MOS_DPRINTFN("frame size larger than " "1532 bytes"); } if (rxstat & MOS_RXSTS_CRC_ERROR) MOS_DPRINTFN("CRC error"); if (rxstat & MOS_RXSTS_ALIGN_ERROR) MOS_DPRINTFN("alignment error"); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } /* Remember the last byte was used for the status fields */ pktlen = actlen - 1; if (pktlen < sizeof(struct ether_header)) { MOS_DPRINTFN("error: pktlen %d is smaller " "than ether_header %zd", pktlen, sizeof(struct ether_header)); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } uether_rxbuf(ue, pc, 0, actlen); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); uether_rxflush(ue); return; default: MOS_DPRINTFN("bulk read error, %s", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); goto tr_setup; } MOS_DPRINTFN("start rx %i", usbd_xfer_max_len(xfer)); return; } } /* * A frame was downloaded to the chip. It's safe for us to clean up * the list buffers. */ static void mos_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct mos_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct usb_page_cache *pc; struct mbuf *m; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: MOS_DPRINTFN("transfer of complete"); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: /* * XXX: don't send anything if there is no link? */ IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) return; pc = usbd_xfer_get_frame(xfer, 0); usbd_m_copy_in(pc, 0, m, 0, m->m_pkthdr.len); usbd_xfer_set_frame_len(xfer, 0, m->m_pkthdr.len); /* * if there's a BPF listener, bounce a copy * of this frame to him: */ BPF_MTAP(ifp, m); m_freem(m); usbd_transfer_submit(xfer); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); return; default: MOS_DPRINTFN("usb error on tx: %s\n", usbd_errstr(error)); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void mos_tick(struct usb_ether *ue) { struct mos_softc *sc = uether_getsc(ue); struct mii_data *mii = GET_MII(sc); MOS_LOCK_ASSERT(sc, MA_OWNED); mii_tick(mii); if (!sc->mos_link && mii->mii_media_status & IFM_ACTIVE && IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) { MOS_DPRINTFN("got link"); sc->mos_link++; mos_start(ue); } } static void mos_start(struct usb_ether *ue) { struct mos_softc *sc = uether_getsc(ue); /* * start the USB transfers, if not already started: */ usbd_transfer_start(sc->sc_xfer[MOS_ENDPT_TX]); usbd_transfer_start(sc->sc_xfer[MOS_ENDPT_RX]); usbd_transfer_start(sc->sc_xfer[MOS_ENDPT_INTR]); } static void mos_init(struct usb_ether *ue) { struct mos_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); uint8_t rxmode; MOS_LOCK_ASSERT(sc, MA_OWNED); /* Cancel pending I/O and free all RX/TX buffers. */ mos_reset(sc); /* Write MAC address */ mos_writemac(sc, IF_LLADDR(ifp)); /* Read and set transmitter IPG values */ sc->mos_ipgs[0] = mos_reg_read_1(sc, MOS_IPG0); sc->mos_ipgs[1] = mos_reg_read_1(sc, MOS_IPG1); mos_reg_write_1(sc, MOS_IPG0, sc->mos_ipgs[0]); mos_reg_write_1(sc, MOS_IPG1, sc->mos_ipgs[1]); /* * Enable receiver and transmitter, bridge controls speed/duplex * mode */ rxmode = mos_reg_read_1(sc, MOS_CTL); rxmode |= MOS_CTL_RX_ENB | MOS_CTL_TX_ENB | MOS_CTL_BS_ENB; rxmode &= ~(MOS_CTL_SLEEP); mos_setpromisc(ue); /* XXX: broadcast mode? */ mos_reg_write_1(sc, MOS_CTL, rxmode); /* Load the multicast filter. */ mos_setmulti(ue); ifp->if_drv_flags |= IFF_DRV_RUNNING; mos_start(ue); } static void mos_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct mos_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct usb_page_cache *pc; uint32_t pkt; int actlen; if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); MOS_DPRINTFN("actlen %i", actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, &pkt, sizeof(pkt)); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: return; default: if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } /* * Stop the adapter and free any mbufs allocated to the * RX and TX lists. */ static void mos_stop(struct usb_ether *ue) { struct mos_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); mos_reset(sc); MOS_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags &= ~IFF_DRV_RUNNING; /* stop all the transfers, if not already stopped */ usbd_transfer_stop(sc->sc_xfer[MOS_ENDPT_TX]); usbd_transfer_stop(sc->sc_xfer[MOS_ENDPT_RX]); usbd_transfer_stop(sc->sc_xfer[MOS_ENDPT_INTR]); sc->mos_link = 0; } Index: head/sys/dev/usb/net/if_rue.c =================================================================== --- head/sys/dev/usb/net/if_rue.c (revision 276700) +++ head/sys/dev/usb/net/if_rue.c (revision 276701) @@ -1,921 +1,921 @@ /*- * Copyright (c) 2001-2003, Shunsuke Akiyama . * Copyright (c) 1997, 1998, 1999, 2000 Bill Paul . * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /*- * Copyright (c) 1997, 1998, 1999, 2000 * Bill Paul . All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Bill Paul. * 4. Neither the name of the author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * RealTek RTL8150 USB to fast ethernet controller driver. * Datasheet is available from * ftp://ftp.realtek.com.tw/lancard/data_sheet/8150/. */ #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 "usbdevs.h" #define USB_DEBUG_VAR rue_debug #include #include #include #include #ifdef USB_DEBUG static int rue_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, rue, CTLFLAG_RW, 0, "USB rue"); -SYSCTL_INT(_hw_usb_rue, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_rue, OID_AUTO, debug, CTLFLAG_RWTUN, &rue_debug, 0, "Debug level"); #endif /* * Various supported device vendors/products. */ static const STRUCT_USB_HOST_ID rue_devs[] = { {USB_VPI(USB_VENDOR_MELCO, USB_PRODUCT_MELCO_LUAKTX, 0)}, {USB_VPI(USB_VENDOR_REALTEK, USB_PRODUCT_REALTEK_USBKR100, 0)}, {USB_VPI(USB_VENDOR_OQO, USB_PRODUCT_OQO_ETHER01, 0)}, }; /* prototypes */ static device_probe_t rue_probe; static device_attach_t rue_attach; static device_detach_t rue_detach; static miibus_readreg_t rue_miibus_readreg; static miibus_writereg_t rue_miibus_writereg; static miibus_statchg_t rue_miibus_statchg; static usb_callback_t rue_intr_callback; static usb_callback_t rue_bulk_read_callback; static usb_callback_t rue_bulk_write_callback; static uether_fn_t rue_attach_post; static uether_fn_t rue_init; static uether_fn_t rue_stop; static uether_fn_t rue_start; static uether_fn_t rue_tick; static uether_fn_t rue_setmulti; static uether_fn_t rue_setpromisc; static int rue_read_mem(struct rue_softc *, uint16_t, void *, int); static int rue_write_mem(struct rue_softc *, uint16_t, void *, int); static uint8_t rue_csr_read_1(struct rue_softc *, uint16_t); static uint16_t rue_csr_read_2(struct rue_softc *, uint16_t); static int rue_csr_write_1(struct rue_softc *, uint16_t, uint8_t); static int rue_csr_write_2(struct rue_softc *, uint16_t, uint16_t); static int rue_csr_write_4(struct rue_softc *, int, uint32_t); static void rue_reset(struct rue_softc *); static int rue_ifmedia_upd(struct ifnet *); static void rue_ifmedia_sts(struct ifnet *, struct ifmediareq *); static const struct usb_config rue_config[RUE_N_TRANSFER] = { [RUE_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = MCLBYTES, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = rue_bulk_write_callback, .timeout = 10000, /* 10 seconds */ }, [RUE_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = (MCLBYTES + 4), .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = rue_bulk_read_callback, .timeout = 0, /* no timeout */ }, [RUE_INTR_DT_RD] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = rue_intr_callback, }, }; static device_method_t rue_methods[] = { /* Device interface */ DEVMETHOD(device_probe, rue_probe), DEVMETHOD(device_attach, rue_attach), DEVMETHOD(device_detach, rue_detach), /* MII interface */ DEVMETHOD(miibus_readreg, rue_miibus_readreg), DEVMETHOD(miibus_writereg, rue_miibus_writereg), DEVMETHOD(miibus_statchg, rue_miibus_statchg), DEVMETHOD_END }; static driver_t rue_driver = { .name = "rue", .methods = rue_methods, .size = sizeof(struct rue_softc), }; static devclass_t rue_devclass; DRIVER_MODULE_ORDERED(rue, uhub, rue_driver, rue_devclass, NULL, NULL, SI_ORDER_ANY); DRIVER_MODULE(miibus, rue, miibus_driver, miibus_devclass, NULL, NULL); MODULE_DEPEND(rue, uether, 1, 1, 1); MODULE_DEPEND(rue, usb, 1, 1, 1); MODULE_DEPEND(rue, ether, 1, 1, 1); MODULE_DEPEND(rue, miibus, 1, 1, 1); MODULE_VERSION(rue, 1); static const struct usb_ether_methods rue_ue_methods = { .ue_attach_post = rue_attach_post, .ue_start = rue_start, .ue_init = rue_init, .ue_stop = rue_stop, .ue_tick = rue_tick, .ue_setmulti = rue_setmulti, .ue_setpromisc = rue_setpromisc, .ue_mii_upd = rue_ifmedia_upd, .ue_mii_sts = rue_ifmedia_sts, }; #define RUE_SETBIT(sc, reg, x) \ rue_csr_write_1(sc, reg, rue_csr_read_1(sc, reg) | (x)) #define RUE_CLRBIT(sc, reg, x) \ rue_csr_write_1(sc, reg, rue_csr_read_1(sc, reg) & ~(x)) static int rue_read_mem(struct rue_softc *sc, uint16_t addr, void *buf, int len) { struct usb_device_request req; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = UR_SET_ADDRESS; USETW(req.wValue, addr); USETW(req.wIndex, 0); USETW(req.wLength, len); return (uether_do_request(&sc->sc_ue, &req, buf, 1000)); } static int rue_write_mem(struct rue_softc *sc, uint16_t addr, void *buf, int len) { struct usb_device_request req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = UR_SET_ADDRESS; USETW(req.wValue, addr); USETW(req.wIndex, 0); USETW(req.wLength, len); return (uether_do_request(&sc->sc_ue, &req, buf, 1000)); } static uint8_t rue_csr_read_1(struct rue_softc *sc, uint16_t reg) { uint8_t val; rue_read_mem(sc, reg, &val, 1); return (val); } static uint16_t rue_csr_read_2(struct rue_softc *sc, uint16_t reg) { uint8_t val[2]; rue_read_mem(sc, reg, &val, 2); return (UGETW(val)); } static int rue_csr_write_1(struct rue_softc *sc, uint16_t reg, uint8_t val) { return (rue_write_mem(sc, reg, &val, 1)); } static int rue_csr_write_2(struct rue_softc *sc, uint16_t reg, uint16_t val) { uint8_t temp[2]; USETW(temp, val); return (rue_write_mem(sc, reg, &temp, 2)); } static int rue_csr_write_4(struct rue_softc *sc, int reg, uint32_t val) { uint8_t temp[4]; USETDW(temp, val); return (rue_write_mem(sc, reg, &temp, 4)); } static int rue_miibus_readreg(device_t dev, int phy, int reg) { struct rue_softc *sc = device_get_softc(dev); uint16_t rval; uint16_t ruereg; int locked; if (phy != 0) /* RTL8150 supports PHY == 0, only */ return (0); locked = mtx_owned(&sc->sc_mtx); if (!locked) RUE_LOCK(sc); switch (reg) { case MII_BMCR: ruereg = RUE_BMCR; break; case MII_BMSR: ruereg = RUE_BMSR; break; case MII_ANAR: ruereg = RUE_ANAR; break; case MII_ANER: ruereg = RUE_AER; break; case MII_ANLPAR: ruereg = RUE_ANLP; break; case MII_PHYIDR1: case MII_PHYIDR2: rval = 0; goto done; default: if (RUE_REG_MIN <= reg && reg <= RUE_REG_MAX) { rval = rue_csr_read_1(sc, reg); goto done; } device_printf(sc->sc_ue.ue_dev, "bad phy register\n"); rval = 0; goto done; } rval = rue_csr_read_2(sc, ruereg); done: if (!locked) RUE_UNLOCK(sc); return (rval); } static int rue_miibus_writereg(device_t dev, int phy, int reg, int data) { struct rue_softc *sc = device_get_softc(dev); uint16_t ruereg; int locked; if (phy != 0) /* RTL8150 supports PHY == 0, only */ return (0); locked = mtx_owned(&sc->sc_mtx); if (!locked) RUE_LOCK(sc); switch (reg) { case MII_BMCR: ruereg = RUE_BMCR; break; case MII_BMSR: ruereg = RUE_BMSR; break; case MII_ANAR: ruereg = RUE_ANAR; break; case MII_ANER: ruereg = RUE_AER; break; case MII_ANLPAR: ruereg = RUE_ANLP; break; case MII_PHYIDR1: case MII_PHYIDR2: goto done; default: if (RUE_REG_MIN <= reg && reg <= RUE_REG_MAX) { rue_csr_write_1(sc, reg, data); goto done; } device_printf(sc->sc_ue.ue_dev, " bad phy register\n"); goto done; } rue_csr_write_2(sc, ruereg, data); done: if (!locked) RUE_UNLOCK(sc); return (0); } static void rue_miibus_statchg(device_t dev) { /* * When the code below is enabled the card starts doing weird * things after link going from UP to DOWN and back UP. * * Looks like some of register writes below messes up PHY * interface. * * No visible regressions were found after commenting this code * out, so that disable it for good. */ #if 0 struct rue_softc *sc = device_get_softc(dev); struct mii_data *mii = GET_MII(sc); uint16_t bmcr; int locked; locked = mtx_owned(&sc->sc_mtx); if (!locked) RUE_LOCK(sc); RUE_CLRBIT(sc, RUE_CR, (RUE_CR_RE | RUE_CR_TE)); bmcr = rue_csr_read_2(sc, RUE_BMCR); if (IFM_SUBTYPE(mii->mii_media_active) == IFM_100_TX) bmcr |= RUE_BMCR_SPD_SET; else bmcr &= ~RUE_BMCR_SPD_SET; if ((mii->mii_media_active & IFM_GMASK) == IFM_FDX) bmcr |= RUE_BMCR_DUPLEX; else bmcr &= ~RUE_BMCR_DUPLEX; rue_csr_write_2(sc, RUE_BMCR, bmcr); RUE_SETBIT(sc, RUE_CR, (RUE_CR_RE | RUE_CR_TE)); if (!locked) RUE_UNLOCK(sc); #endif } static void rue_setpromisc(struct usb_ether *ue) { struct rue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); RUE_LOCK_ASSERT(sc, MA_OWNED); /* If we want promiscuous mode, set the allframes bit. */ if (ifp->if_flags & IFF_PROMISC) RUE_SETBIT(sc, RUE_RCR, RUE_RCR_AAP); else RUE_CLRBIT(sc, RUE_RCR, RUE_RCR_AAP); } /* * Program the 64-bit multicast hash filter. */ static void rue_setmulti(struct usb_ether *ue) { struct rue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); uint16_t rxcfg; int h = 0; uint32_t hashes[2] = { 0, 0 }; struct ifmultiaddr *ifma; int mcnt = 0; RUE_LOCK_ASSERT(sc, MA_OWNED); rxcfg = rue_csr_read_2(sc, RUE_RCR); if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) { rxcfg |= (RUE_RCR_AAM | RUE_RCR_AAP); rxcfg &= ~RUE_RCR_AM; rue_csr_write_2(sc, RUE_RCR, rxcfg); rue_csr_write_4(sc, RUE_MAR0, 0xFFFFFFFF); rue_csr_write_4(sc, RUE_MAR4, 0xFFFFFFFF); return; } /* first, zot all the existing hash bits */ rue_csr_write_4(sc, RUE_MAR0, 0); rue_csr_write_4(sc, RUE_MAR4, 0); /* now program new ones */ if_maddr_rlock(ifp); TAILQ_FOREACH (ifma, &ifp->if_multiaddrs, ifma_link) { if (ifma->ifma_addr->sa_family != AF_LINK) continue; h = ether_crc32_be(LLADDR((struct sockaddr_dl *) ifma->ifma_addr), ETHER_ADDR_LEN) >> 26; if (h < 32) hashes[0] |= (1 << h); else hashes[1] |= (1 << (h - 32)); mcnt++; } if_maddr_runlock(ifp); if (mcnt) rxcfg |= RUE_RCR_AM; else rxcfg &= ~RUE_RCR_AM; rxcfg &= ~(RUE_RCR_AAM | RUE_RCR_AAP); rue_csr_write_2(sc, RUE_RCR, rxcfg); rue_csr_write_4(sc, RUE_MAR0, hashes[0]); rue_csr_write_4(sc, RUE_MAR4, hashes[1]); } static void rue_reset(struct rue_softc *sc) { int i; rue_csr_write_1(sc, RUE_CR, RUE_CR_SOFT_RST); for (i = 0; i != RUE_TIMEOUT; i++) { if (uether_pause(&sc->sc_ue, hz / 1000)) break; if (!(rue_csr_read_1(sc, RUE_CR) & RUE_CR_SOFT_RST)) break; } if (i == RUE_TIMEOUT) device_printf(sc->sc_ue.ue_dev, "reset never completed\n"); uether_pause(&sc->sc_ue, hz / 100); } static void rue_attach_post(struct usb_ether *ue) { struct rue_softc *sc = uether_getsc(ue); /* reset the adapter */ rue_reset(sc); /* get station address from the EEPROM */ rue_read_mem(sc, RUE_EEPROM_IDR0, ue->ue_eaddr, ETHER_ADDR_LEN); } /* * Probe for a RTL8150 chip. */ static int rue_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != RUE_CONFIG_IDX) return (ENXIO); if (uaa->info.bIfaceIndex != RUE_IFACE_IDX) return (ENXIO); return (usbd_lookup_id_by_uaa(rue_devs, sizeof(rue_devs), uaa)); } /* * Attach the interface. Allocate softc structures, do ifmedia * setup and ethernet/BPF attach. */ static int rue_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct rue_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; uint8_t iface_index; int error; device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF); iface_index = RUE_IFACE_IDX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, rue_config, RUE_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(dev, "allocating USB transfers failed\n"); goto detach; } ue->ue_sc = sc; ue->ue_dev = dev; ue->ue_udev = uaa->device; ue->ue_mtx = &sc->sc_mtx; ue->ue_methods = &rue_ue_methods; error = uether_ifattach(ue); if (error) { device_printf(dev, "could not attach interface\n"); goto detach; } return (0); /* success */ detach: rue_detach(dev); return (ENXIO); /* failure */ } static int rue_detach(device_t dev) { struct rue_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; usbd_transfer_unsetup(sc->sc_xfer, RUE_N_TRANSFER); uether_ifdetach(ue); mtx_destroy(&sc->sc_mtx); return (0); } static void rue_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct rue_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct rue_intrpkt pkt; struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (ifp && (ifp->if_drv_flags & IFF_DRV_RUNNING) && actlen >= (int)sizeof(pkt)) { pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, &pkt, sizeof(pkt)); if_inc_counter(ifp, IFCOUNTER_IERRORS, pkt.rue_rxlost_cnt); if_inc_counter(ifp, IFCOUNTER_IERRORS, pkt.rue_crcerr_cnt); if_inc_counter(ifp, IFCOUNTER_COLLISIONS, pkt.rue_col_cnt); } /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void rue_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct rue_softc *sc = usbd_xfer_softc(xfer); struct usb_ether *ue = &sc->sc_ue; struct ifnet *ifp = uether_getifp(ue); struct usb_page_cache *pc; uint16_t status; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen < 4) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, actlen - 4, &status, sizeof(status)); actlen -= 4; /* check recieve packet was valid or not */ status = le16toh(status); if ((status & RUE_RXSTAT_VALID) == 0) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } uether_rxbuf(ue, pc, 0, actlen); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); uether_rxflush(ue); return; default: /* Error */ DPRINTF("bulk read error, %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void rue_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct rue_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct usb_page_cache *pc; struct mbuf *m; int temp_len; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(11, "transfer complete\n"); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: if ((sc->sc_flags & RUE_FLAG_LINK) == 0) { /* * don't send anything if there is no link ! */ return; } IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) return; if (m->m_pkthdr.len > MCLBYTES) m->m_pkthdr.len = MCLBYTES; temp_len = m->m_pkthdr.len; pc = usbd_xfer_get_frame(xfer, 0); usbd_m_copy_in(pc, 0, m, 0, m->m_pkthdr.len); /* * This is an undocumented behavior. * RTL8150 chip doesn't send frame length smaller than * RUE_MIN_FRAMELEN (60) byte packet. */ if (temp_len < RUE_MIN_FRAMELEN) { usbd_frame_zero(pc, temp_len, RUE_MIN_FRAMELEN - temp_len); temp_len = RUE_MIN_FRAMELEN; } usbd_xfer_set_frame_len(xfer, 0, temp_len); /* * if there's a BPF listener, bounce a copy * of this frame to him: */ BPF_MTAP(ifp, m); m_freem(m); usbd_transfer_submit(xfer); return; default: /* Error */ DPRINTFN(11, "transfer error, %s\n", usbd_errstr(error)); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void rue_tick(struct usb_ether *ue) { struct rue_softc *sc = uether_getsc(ue); struct mii_data *mii = GET_MII(sc); RUE_LOCK_ASSERT(sc, MA_OWNED); mii_tick(mii); if ((sc->sc_flags & RUE_FLAG_LINK) == 0 && mii->mii_media_status & IFM_ACTIVE && IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) { sc->sc_flags |= RUE_FLAG_LINK; rue_start(ue); } } static void rue_start(struct usb_ether *ue) { struct rue_softc *sc = uether_getsc(ue); /* * start the USB transfers, if not already started: */ usbd_transfer_start(sc->sc_xfer[RUE_INTR_DT_RD]); usbd_transfer_start(sc->sc_xfer[RUE_BULK_DT_RD]); usbd_transfer_start(sc->sc_xfer[RUE_BULK_DT_WR]); } static void rue_init(struct usb_ether *ue) { struct rue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); RUE_LOCK_ASSERT(sc, MA_OWNED); /* * Cancel pending I/O */ rue_reset(sc); /* Set MAC address */ rue_write_mem(sc, RUE_IDR0, IF_LLADDR(ifp), ETHER_ADDR_LEN); rue_stop(ue); /* * Set the initial TX and RX configuration. */ rue_csr_write_1(sc, RUE_TCR, RUE_TCR_CONFIG); rue_csr_write_2(sc, RUE_RCR, RUE_RCR_CONFIG|RUE_RCR_AB); /* Load the multicast filter */ rue_setpromisc(ue); /* Load the multicast filter. */ rue_setmulti(ue); /* Enable RX and TX */ rue_csr_write_1(sc, RUE_CR, (RUE_CR_TE | RUE_CR_RE | RUE_CR_EP3CLREN)); usbd_xfer_set_stall(sc->sc_xfer[RUE_BULK_DT_WR]); ifp->if_drv_flags |= IFF_DRV_RUNNING; rue_start(ue); } /* * Set media options. */ static int rue_ifmedia_upd(struct ifnet *ifp) { struct rue_softc *sc = ifp->if_softc; struct mii_data *mii = GET_MII(sc); struct mii_softc *miisc; int error; RUE_LOCK_ASSERT(sc, MA_OWNED); sc->sc_flags &= ~RUE_FLAG_LINK; LIST_FOREACH(miisc, &mii->mii_phys, mii_list) PHY_RESET(miisc); error = mii_mediachg(mii); return (error); } /* * Report current media status. */ static void rue_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr) { struct rue_softc *sc = ifp->if_softc; struct mii_data *mii = GET_MII(sc); RUE_LOCK(sc); mii_pollstat(mii); ifmr->ifm_active = mii->mii_media_active; ifmr->ifm_status = mii->mii_media_status; RUE_UNLOCK(sc); } static void rue_stop(struct usb_ether *ue) { struct rue_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); RUE_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags &= ~IFF_DRV_RUNNING; sc->sc_flags &= ~RUE_FLAG_LINK; /* * stop all the transfers, if not already stopped: */ usbd_transfer_stop(sc->sc_xfer[RUE_BULK_DT_WR]); usbd_transfer_stop(sc->sc_xfer[RUE_BULK_DT_RD]); usbd_transfer_stop(sc->sc_xfer[RUE_INTR_DT_RD]); rue_csr_write_1(sc, RUE_CR, 0x00); rue_reset(sc); } Index: head/sys/dev/usb/net/if_smsc.c =================================================================== --- head/sys/dev/usb/net/if_smsc.c (revision 276700) +++ head/sys/dev/usb/net/if_smsc.c (revision 276701) @@ -1,1860 +1,1860 @@ /*- * Copyright (c) 2012 * Ben Gray . * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * SMSC LAN9xxx devices (http://www.smsc.com/) * * The LAN9500 & LAN9500A devices are stand-alone USB to Ethernet chips that * support USB 2.0 and 10/100 Mbps Ethernet. * * The LAN951x devices are an integrated USB hub and USB to Ethernet adapter. * The driver only covers the Ethernet part, the standard USB hub driver * supports the hub part. * * This driver is closely modelled on the Linux driver written and copyrighted * by SMSC. * * * * * H/W TCP & UDP Checksum Offloading * --------------------------------- * The chip supports both tx and rx offloading of UDP & TCP checksums, this * feature can be dynamically enabled/disabled. * * RX checksuming is performed across bytes after the IPv4 header to the end of * the Ethernet frame, this means if the frame is padded with non-zero values * the H/W checksum will be incorrect, however the rx code compensates for this. * * TX checksuming is more complicated, the device requires a special header to * be prefixed onto the start of the frame which indicates the start and end * positions of the UDP or TCP frame. This requires the driver to manually * go through the packet data and decode the headers prior to sending. * On Linux they generally provide cues to the location of the csum and the * area to calculate it over, on FreeBSD we seem to have to do it all ourselves, * hence this is not as optimal and therefore h/w tX checksum is currently not * implemented. * */ #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 "opt_platform.h" #ifdef FDT #include #include #include #endif #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR smsc_debug #include #include #include #include #ifdef USB_DEBUG static int smsc_debug = 0; SYSCTL_NODE(_hw_usb, OID_AUTO, smsc, CTLFLAG_RW, 0, "USB smsc"); -SYSCTL_INT(_hw_usb_smsc, OID_AUTO, debug, CTLFLAG_RW, &smsc_debug, 0, +SYSCTL_INT(_hw_usb_smsc, OID_AUTO, debug, CTLFLAG_RWTUN, &smsc_debug, 0, "Debug level"); #endif /* * Various supported device vendors/products. */ static const struct usb_device_id smsc_devs[] = { #define SMSC_DEV(p,i) { USB_VPI(USB_VENDOR_SMC2, USB_PRODUCT_SMC2_##p, i) } SMSC_DEV(LAN89530_ETH, 0), SMSC_DEV(LAN9500_ETH, 0), SMSC_DEV(LAN9500_ETH_2, 0), SMSC_DEV(LAN9500A_ETH, 0), SMSC_DEV(LAN9500A_ETH_2, 0), SMSC_DEV(LAN9505_ETH, 0), SMSC_DEV(LAN9505A_ETH, 0), SMSC_DEV(LAN9514_ETH, 0), SMSC_DEV(LAN9514_ETH_2, 0), SMSC_DEV(LAN9530_ETH, 0), SMSC_DEV(LAN9730_ETH, 0), SMSC_DEV(LAN9500_SAL10, 0), SMSC_DEV(LAN9505_SAL10, 0), SMSC_DEV(LAN9500A_SAL10, 0), SMSC_DEV(LAN9505A_SAL10, 0), SMSC_DEV(LAN9514_SAL10, 0), SMSC_DEV(LAN9500A_HAL, 0), SMSC_DEV(LAN9505A_HAL, 0), #undef SMSC_DEV }; #ifdef USB_DEBUG #define smsc_dbg_printf(sc, fmt, args...) \ do { \ if (smsc_debug > 0) \ device_printf((sc)->sc_ue.ue_dev, "debug: " fmt, ##args); \ } while(0) #else #define smsc_dbg_printf(sc, fmt, args...) #endif #define smsc_warn_printf(sc, fmt, args...) \ device_printf((sc)->sc_ue.ue_dev, "warning: " fmt, ##args) #define smsc_err_printf(sc, fmt, args...) \ device_printf((sc)->sc_ue.ue_dev, "error: " fmt, ##args) #define ETHER_IS_ZERO(addr) \ (!(addr[0] | addr[1] | addr[2] | addr[3] | addr[4] | addr[5])) #define ETHER_IS_VALID(addr) \ (!ETHER_IS_MULTICAST(addr) && !ETHER_IS_ZERO(addr)) static device_probe_t smsc_probe; static device_attach_t smsc_attach; static device_detach_t smsc_detach; static usb_callback_t smsc_bulk_read_callback; static usb_callback_t smsc_bulk_write_callback; static miibus_readreg_t smsc_miibus_readreg; static miibus_writereg_t smsc_miibus_writereg; static miibus_statchg_t smsc_miibus_statchg; #if __FreeBSD_version > 1000000 static int smsc_attach_post_sub(struct usb_ether *ue); #endif static uether_fn_t smsc_attach_post; static uether_fn_t smsc_init; static uether_fn_t smsc_stop; static uether_fn_t smsc_start; static uether_fn_t smsc_tick; static uether_fn_t smsc_setmulti; static uether_fn_t smsc_setpromisc; static int smsc_ifmedia_upd(struct ifnet *); static void smsc_ifmedia_sts(struct ifnet *, struct ifmediareq *); static int smsc_chip_init(struct smsc_softc *sc); static int smsc_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data); static const struct usb_config smsc_config[SMSC_N_TRANSFER] = { [SMSC_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .frames = 16, .bufsize = 16 * (MCLBYTES + 16), .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = smsc_bulk_write_callback, .timeout = 10000, /* 10 seconds */ }, [SMSC_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = 20480, /* bytes */ .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = smsc_bulk_read_callback, .timeout = 0, /* no timeout */ }, /* The SMSC chip supports an interrupt endpoints, however they aren't * needed as we poll on the MII status. */ }; static const struct usb_ether_methods smsc_ue_methods = { .ue_attach_post = smsc_attach_post, #if __FreeBSD_version > 1000000 .ue_attach_post_sub = smsc_attach_post_sub, #endif .ue_start = smsc_start, .ue_ioctl = smsc_ioctl, .ue_init = smsc_init, .ue_stop = smsc_stop, .ue_tick = smsc_tick, .ue_setmulti = smsc_setmulti, .ue_setpromisc = smsc_setpromisc, .ue_mii_upd = smsc_ifmedia_upd, .ue_mii_sts = smsc_ifmedia_sts, }; /** * smsc_read_reg - Reads a 32-bit register on the device * @sc: driver soft context * @off: offset of the register * @data: pointer a value that will be populated with the register value * * LOCKING: * The device lock must be held before calling this function. * * RETURNS: * 0 on success, a USB_ERR_?? error code on failure. */ static int smsc_read_reg(struct smsc_softc *sc, uint32_t off, uint32_t *data) { struct usb_device_request req; uint32_t buf; usb_error_t err; SMSC_LOCK_ASSERT(sc, MA_OWNED); req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = SMSC_UR_READ_REG; USETW(req.wValue, 0); USETW(req.wIndex, off); USETW(req.wLength, 4); err = uether_do_request(&sc->sc_ue, &req, &buf, 1000); if (err != 0) smsc_warn_printf(sc, "Failed to read register 0x%0x\n", off); *data = le32toh(buf); return (err); } /** * smsc_write_reg - Writes a 32-bit register on the device * @sc: driver soft context * @off: offset of the register * @data: the 32-bit value to write into the register * * LOCKING: * The device lock must be held before calling this function. * * RETURNS: * 0 on success, a USB_ERR_?? error code on failure. */ static int smsc_write_reg(struct smsc_softc *sc, uint32_t off, uint32_t data) { struct usb_device_request req; uint32_t buf; usb_error_t err; SMSC_LOCK_ASSERT(sc, MA_OWNED); buf = htole32(data); req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = SMSC_UR_WRITE_REG; USETW(req.wValue, 0); USETW(req.wIndex, off); USETW(req.wLength, 4); err = uether_do_request(&sc->sc_ue, &req, &buf, 1000); if (err != 0) smsc_warn_printf(sc, "Failed to write register 0x%0x\n", off); return (err); } /** * smsc_wait_for_bits - Polls on a register value until bits are cleared * @sc: soft context * @reg: offset of the register * @bits: if the bits are clear the function returns * * LOCKING: * The device lock must be held before calling this function. * * RETURNS: * 0 on success, or a USB_ERR_?? error code on failure. */ static int smsc_wait_for_bits(struct smsc_softc *sc, uint32_t reg, uint32_t bits) { usb_ticks_t start_ticks; const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000); uint32_t val; int err; SMSC_LOCK_ASSERT(sc, MA_OWNED); start_ticks = (usb_ticks_t)ticks; do { if ((err = smsc_read_reg(sc, reg, &val)) != 0) return (err); if (!(val & bits)) return (0); uether_pause(&sc->sc_ue, hz / 100); } while (((usb_ticks_t)(ticks - start_ticks)) < max_ticks); return (USB_ERR_TIMEOUT); } /** * smsc_eeprom_read - Reads the attached EEPROM * @sc: soft context * @off: the eeprom address offset * @buf: stores the bytes * @buflen: the number of bytes to read * * Simply reads bytes from an attached eeprom. * * LOCKING: * The function takes and releases the device lock if it is not already held. * * RETURNS: * 0 on success, or a USB_ERR_?? error code on failure. */ static int smsc_eeprom_read(struct smsc_softc *sc, uint16_t off, uint8_t *buf, uint16_t buflen) { usb_ticks_t start_ticks; const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000); int err; int locked; uint32_t val; uint16_t i; locked = mtx_owned(&sc->sc_mtx); if (!locked) SMSC_LOCK(sc); err = smsc_wait_for_bits(sc, SMSC_EEPROM_CMD, SMSC_EEPROM_CMD_BUSY); if (err != 0) { smsc_warn_printf(sc, "eeprom busy, failed to read data\n"); goto done; } /* start reading the bytes, one at a time */ for (i = 0; i < buflen; i++) { val = SMSC_EEPROM_CMD_BUSY | (SMSC_EEPROM_CMD_ADDR_MASK & (off + i)); if ((err = smsc_write_reg(sc, SMSC_EEPROM_CMD, val)) != 0) goto done; start_ticks = (usb_ticks_t)ticks; do { if ((err = smsc_read_reg(sc, SMSC_EEPROM_CMD, &val)) != 0) goto done; if (!(val & SMSC_EEPROM_CMD_BUSY) || (val & SMSC_EEPROM_CMD_TIMEOUT)) break; uether_pause(&sc->sc_ue, hz / 100); } while (((usb_ticks_t)(ticks - start_ticks)) < max_ticks); if (val & (SMSC_EEPROM_CMD_BUSY | SMSC_EEPROM_CMD_TIMEOUT)) { smsc_warn_printf(sc, "eeprom command failed\n"); err = USB_ERR_IOERROR; break; } if ((err = smsc_read_reg(sc, SMSC_EEPROM_DATA, &val)) != 0) goto done; buf[i] = (val & 0xff); } done: if (!locked) SMSC_UNLOCK(sc); return (err); } /** * smsc_miibus_readreg - Reads a MII/MDIO register * @dev: usb ether device * @phy: the number of phy reading from * @reg: the register address * * Attempts to read a phy register over the MII bus. * * LOCKING: * Takes and releases the device mutex lock if not already held. * * RETURNS: * Returns the 16-bits read from the MII register, if this function fails 0 * is returned. */ static int smsc_miibus_readreg(device_t dev, int phy, int reg) { struct smsc_softc *sc = device_get_softc(dev); int locked; uint32_t addr; uint32_t val = 0; locked = mtx_owned(&sc->sc_mtx); if (!locked) SMSC_LOCK(sc); if (smsc_wait_for_bits(sc, SMSC_MII_ADDR, SMSC_MII_BUSY) != 0) { smsc_warn_printf(sc, "MII is busy\n"); goto done; } addr = (phy << 11) | (reg << 6) | SMSC_MII_READ; smsc_write_reg(sc, SMSC_MII_ADDR, addr); if (smsc_wait_for_bits(sc, SMSC_MII_ADDR, SMSC_MII_BUSY) != 0) smsc_warn_printf(sc, "MII read timeout\n"); smsc_read_reg(sc, SMSC_MII_DATA, &val); val = le32toh(val); done: if (!locked) SMSC_UNLOCK(sc); return (val & 0xFFFF); } /** * smsc_miibus_writereg - Writes a MII/MDIO register * @dev: usb ether device * @phy: the number of phy writing to * @reg: the register address * @val: the value to write * * Attempts to write a phy register over the MII bus. * * LOCKING: * Takes and releases the device mutex lock if not already held. * * RETURNS: * Always returns 0 regardless of success or failure. */ static int smsc_miibus_writereg(device_t dev, int phy, int reg, int val) { struct smsc_softc *sc = device_get_softc(dev); int locked; uint32_t addr; if (sc->sc_phyno != phy) return (0); locked = mtx_owned(&sc->sc_mtx); if (!locked) SMSC_LOCK(sc); if (smsc_wait_for_bits(sc, SMSC_MII_ADDR, SMSC_MII_BUSY) != 0) { smsc_warn_printf(sc, "MII is busy\n"); goto done; } val = htole32(val); smsc_write_reg(sc, SMSC_MII_DATA, val); addr = (phy << 11) | (reg << 6) | SMSC_MII_WRITE; smsc_write_reg(sc, SMSC_MII_ADDR, addr); if (smsc_wait_for_bits(sc, SMSC_MII_ADDR, SMSC_MII_BUSY) != 0) smsc_warn_printf(sc, "MII write timeout\n"); done: if (!locked) SMSC_UNLOCK(sc); return (0); } /** * smsc_miibus_statchg - Called to detect phy status change * @dev: usb ether device * * This function is called periodically by the system to poll for status * changes of the link. * * LOCKING: * Takes and releases the device mutex lock if not already held. */ static void smsc_miibus_statchg(device_t dev) { struct smsc_softc *sc = device_get_softc(dev); struct mii_data *mii = uether_getmii(&sc->sc_ue); struct ifnet *ifp; int locked; int err; uint32_t flow; uint32_t afc_cfg; locked = mtx_owned(&sc->sc_mtx); if (!locked) SMSC_LOCK(sc); ifp = uether_getifp(&sc->sc_ue); if (mii == NULL || ifp == NULL || (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) goto done; /* Use the MII status to determine link status */ sc->sc_flags &= ~SMSC_FLAG_LINK; if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) == (IFM_ACTIVE | IFM_AVALID)) { switch (IFM_SUBTYPE(mii->mii_media_active)) { case IFM_10_T: case IFM_100_TX: sc->sc_flags |= SMSC_FLAG_LINK; break; case IFM_1000_T: /* Gigabit ethernet not supported by chipset */ break; default: break; } } /* Lost link, do nothing. */ if ((sc->sc_flags & SMSC_FLAG_LINK) == 0) { smsc_dbg_printf(sc, "link flag not set\n"); goto done; } err = smsc_read_reg(sc, SMSC_AFC_CFG, &afc_cfg); if (err) { smsc_warn_printf(sc, "failed to read initial AFC_CFG, error %d\n", err); goto done; } /* Enable/disable full duplex operation and TX/RX pause */ if ((IFM_OPTIONS(mii->mii_media_active) & IFM_FDX) != 0) { smsc_dbg_printf(sc, "full duplex operation\n"); sc->sc_mac_csr &= ~SMSC_MAC_CSR_RCVOWN; sc->sc_mac_csr |= SMSC_MAC_CSR_FDPX; if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_RXPAUSE) != 0) flow = 0xffff0002; else flow = 0; if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_TXPAUSE) != 0) afc_cfg |= 0xf; else afc_cfg &= ~0xf; } else { smsc_dbg_printf(sc, "half duplex operation\n"); sc->sc_mac_csr &= ~SMSC_MAC_CSR_FDPX; sc->sc_mac_csr |= SMSC_MAC_CSR_RCVOWN; flow = 0; afc_cfg |= 0xf; } err = smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr); err += smsc_write_reg(sc, SMSC_FLOW, flow); err += smsc_write_reg(sc, SMSC_AFC_CFG, afc_cfg); if (err) smsc_warn_printf(sc, "media change failed, error %d\n", err); done: if (!locked) SMSC_UNLOCK(sc); } /** * smsc_ifmedia_upd - Set media options * @ifp: interface pointer * * Basically boilerplate code that simply calls the mii functions to set the * media options. * * LOCKING: * The device lock must be held before this function is called. * * RETURNS: * Returns 0 on success or a negative error code. */ static int smsc_ifmedia_upd(struct ifnet *ifp) { struct smsc_softc *sc = ifp->if_softc; struct mii_data *mii = uether_getmii(&sc->sc_ue); struct mii_softc *miisc; int err; SMSC_LOCK_ASSERT(sc, MA_OWNED); LIST_FOREACH(miisc, &mii->mii_phys, mii_list) PHY_RESET(miisc); err = mii_mediachg(mii); return (err); } /** * smsc_ifmedia_sts - Report current media status * @ifp: inet interface pointer * @ifmr: interface media request * * Basically boilerplate code that simply calls the mii functions to get the * media status. * * LOCKING: * Internally takes and releases the device lock. */ static void smsc_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr) { struct smsc_softc *sc = ifp->if_softc; struct mii_data *mii = uether_getmii(&sc->sc_ue); SMSC_LOCK(sc); mii_pollstat(mii); ifmr->ifm_active = mii->mii_media_active; ifmr->ifm_status = mii->mii_media_status; SMSC_UNLOCK(sc); } /** * smsc_hash - Calculate the hash of a mac address * @addr: The mac address to calculate the hash on * * This function is used when configuring a range of m'cast mac addresses to * filter on. The hash of the mac address is put in the device's mac hash * table. * * RETURNS: * Returns a value from 0-63 value which is the hash of the mac address. */ static inline uint32_t smsc_hash(uint8_t addr[ETHER_ADDR_LEN]) { return (ether_crc32_be(addr, ETHER_ADDR_LEN) >> 26) & 0x3f; } /** * smsc_setmulti - Setup multicast * @ue: usb ethernet device context * * Tells the device to either accept frames with a multicast mac address, a * select group of m'cast mac addresses or just the devices mac address. * * LOCKING: * Should be called with the SMSC lock held. */ static void smsc_setmulti(struct usb_ether *ue) { struct smsc_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); struct ifmultiaddr *ifma; uint32_t hashtbl[2] = { 0, 0 }; uint32_t hash; SMSC_LOCK_ASSERT(sc, MA_OWNED); if (ifp->if_flags & (IFF_ALLMULTI | IFF_PROMISC)) { smsc_dbg_printf(sc, "receive all multicast enabled\n"); sc->sc_mac_csr |= SMSC_MAC_CSR_MCPAS; sc->sc_mac_csr &= ~SMSC_MAC_CSR_HPFILT; } else { /* Take the lock of the mac address list before hashing each of them */ if_maddr_rlock(ifp); if (!TAILQ_EMPTY(&ifp->if_multiaddrs)) { /* We are filtering on a set of address so calculate hashes of each * of the address and set the corresponding bits in the register. */ sc->sc_mac_csr |= SMSC_MAC_CSR_HPFILT; sc->sc_mac_csr &= ~(SMSC_MAC_CSR_PRMS | SMSC_MAC_CSR_MCPAS); TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) { if (ifma->ifma_addr->sa_family != AF_LINK) continue; hash = smsc_hash(LLADDR((struct sockaddr_dl *)ifma->ifma_addr)); hashtbl[hash >> 5] |= 1 << (hash & 0x1F); } } else { /* Only receive packets with destination set to our mac address */ sc->sc_mac_csr &= ~(SMSC_MAC_CSR_MCPAS | SMSC_MAC_CSR_HPFILT); } if_maddr_runlock(ifp); /* Debug */ if (sc->sc_mac_csr & SMSC_MAC_CSR_HPFILT) smsc_dbg_printf(sc, "receive select group of macs\n"); else smsc_dbg_printf(sc, "receive own packets only\n"); } /* Write the hash table and mac control registers */ smsc_write_reg(sc, SMSC_HASHH, hashtbl[1]); smsc_write_reg(sc, SMSC_HASHL, hashtbl[0]); smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr); } /** * smsc_setpromisc - Enables/disables promiscuous mode * @ue: usb ethernet device context * * LOCKING: * Should be called with the SMSC lock held. */ static void smsc_setpromisc(struct usb_ether *ue) { struct smsc_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); smsc_dbg_printf(sc, "promiscuous mode %sabled\n", (ifp->if_flags & IFF_PROMISC) ? "en" : "dis"); SMSC_LOCK_ASSERT(sc, MA_OWNED); if (ifp->if_flags & IFF_PROMISC) sc->sc_mac_csr |= SMSC_MAC_CSR_PRMS; else sc->sc_mac_csr &= ~SMSC_MAC_CSR_PRMS; smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr); } /** * smsc_sethwcsum - Enable or disable H/W UDP and TCP checksumming * @sc: driver soft context * * LOCKING: * Should be called with the SMSC lock held. * * RETURNS: * Returns 0 on success or a negative error code. */ static int smsc_sethwcsum(struct smsc_softc *sc) { struct ifnet *ifp = uether_getifp(&sc->sc_ue); uint32_t val; int err; if (!ifp) return (-EIO); SMSC_LOCK_ASSERT(sc, MA_OWNED); err = smsc_read_reg(sc, SMSC_COE_CTRL, &val); if (err != 0) { smsc_warn_printf(sc, "failed to read SMSC_COE_CTRL (err=%d)\n", err); return (err); } /* Enable/disable the Rx checksum */ if ((ifp->if_capabilities & ifp->if_capenable) & IFCAP_RXCSUM) val |= SMSC_COE_CTRL_RX_EN; else val &= ~SMSC_COE_CTRL_RX_EN; /* Enable/disable the Tx checksum (currently not supported) */ if ((ifp->if_capabilities & ifp->if_capenable) & IFCAP_TXCSUM) val |= SMSC_COE_CTRL_TX_EN; else val &= ~SMSC_COE_CTRL_TX_EN; err = smsc_write_reg(sc, SMSC_COE_CTRL, val); if (err != 0) { smsc_warn_printf(sc, "failed to write SMSC_COE_CTRL (err=%d)\n", err); return (err); } return (0); } /** * smsc_setmacaddress - Sets the mac address in the device * @sc: driver soft context * @addr: pointer to array contain at least 6 bytes of the mac * * Writes the MAC address into the device, usually the MAC is programmed with * values from the EEPROM. * * LOCKING: * Should be called with the SMSC lock held. * * RETURNS: * Returns 0 on success or a negative error code. */ static int smsc_setmacaddress(struct smsc_softc *sc, const uint8_t *addr) { int err; uint32_t val; smsc_dbg_printf(sc, "setting mac address to %02x:%02x:%02x:%02x:%02x:%02x\n", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); SMSC_LOCK_ASSERT(sc, MA_OWNED); val = (addr[3] << 24) | (addr[2] << 16) | (addr[1] << 8) | addr[0]; if ((err = smsc_write_reg(sc, SMSC_MAC_ADDRL, val)) != 0) goto done; val = (addr[5] << 8) | addr[4]; err = smsc_write_reg(sc, SMSC_MAC_ADDRH, val); done: return (err); } /** * smsc_reset - Reset the SMSC chip * @sc: device soft context * * LOCKING: * Should be called with the SMSC lock held. */ static void smsc_reset(struct smsc_softc *sc) { struct usb_config_descriptor *cd; usb_error_t err; cd = usbd_get_config_descriptor(sc->sc_ue.ue_udev); err = usbd_req_set_config(sc->sc_ue.ue_udev, &sc->sc_mtx, cd->bConfigurationValue); if (err) smsc_warn_printf(sc, "reset failed (ignored)\n"); /* Wait a little while for the chip to get its brains in order. */ uether_pause(&sc->sc_ue, hz / 100); /* Reinitialize controller to achieve full reset. */ smsc_chip_init(sc); } /** * smsc_init - Initialises the LAN95xx chip * @ue: USB ether interface * * Called when the interface is brought up (i.e. ifconfig ue0 up), this * initialise the interface and the rx/tx pipes. * * LOCKING: * Should be called with the SMSC lock held. */ static void smsc_init(struct usb_ether *ue) { struct smsc_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); SMSC_LOCK_ASSERT(sc, MA_OWNED); if ((ifp->if_drv_flags & IFF_DRV_RUNNING) != 0) return; /* Cancel pending I/O */ smsc_stop(ue); #if __FreeBSD_version <= 1000000 /* On earlier versions this was the first place we could tell the system * that we supported h/w csuming, however this is only called after the * the interface has been brought up - not ideal. */ if (!(ifp->if_capabilities & IFCAP_RXCSUM)) { ifp->if_capabilities |= IFCAP_RXCSUM; ifp->if_capenable |= IFCAP_RXCSUM; ifp->if_hwassist = 0; } /* TX checksuming is disabled for now ifp->if_capabilities |= IFCAP_TXCSUM; ifp->if_capenable |= IFCAP_TXCSUM; ifp->if_hwassist = CSUM_TCP | CSUM_UDP; */ #endif /* Reset the ethernet interface. */ smsc_reset(sc); /* Load the multicast filter. */ smsc_setmulti(ue); /* TCP/UDP checksum offload engines. */ smsc_sethwcsum(sc); usbd_xfer_set_stall(sc->sc_xfer[SMSC_BULK_DT_WR]); /* Indicate we are up and running. */ ifp->if_drv_flags |= IFF_DRV_RUNNING; /* Switch to selected media. */ smsc_ifmedia_upd(ifp); smsc_start(ue); } /** * smsc_bulk_read_callback - Read callback used to process the USB URB * @xfer: the USB transfer * @error: * * Reads the URB data which can contain one or more ethernet frames, the * frames are copyed into a mbuf and given to the system. * * LOCKING: * No locking required, doesn't access internal driver settings. */ static void smsc_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct smsc_softc *sc = usbd_xfer_softc(xfer); struct usb_ether *ue = &sc->sc_ue; struct ifnet *ifp = uether_getifp(ue); struct mbuf *m; struct usb_page_cache *pc; uint32_t rxhdr; uint16_t pktlen; int off; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); smsc_dbg_printf(sc, "rx : actlen %d\n", actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: /* There is always a zero length frame after bringing the IF up */ if (actlen < (sizeof(rxhdr) + ETHER_CRC_LEN)) goto tr_setup; /* There maybe multiple packets in the USB frame, each will have a * header and each needs to have it's own mbuf allocated and populated * for it. */ pc = usbd_xfer_get_frame(xfer, 0); off = 0; while (off < actlen) { /* The frame header is always aligned on a 4 byte boundary */ off = ((off + 0x3) & ~0x3); usbd_copy_out(pc, off, &rxhdr, sizeof(rxhdr)); off += (sizeof(rxhdr) + ETHER_ALIGN); rxhdr = le32toh(rxhdr); pktlen = (uint16_t)SMSC_RX_STAT_FRM_LENGTH(rxhdr); smsc_dbg_printf(sc, "rx : rxhdr 0x%08x : pktlen %d : actlen %d : " "off %d\n", rxhdr, pktlen, actlen, off); if (rxhdr & SMSC_RX_STAT_ERROR) { smsc_dbg_printf(sc, "rx error (hdr 0x%08x)\n", rxhdr); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); if (rxhdr & SMSC_RX_STAT_COLLISION) if_inc_counter(ifp, IFCOUNTER_COLLISIONS, 1); } else { /* Check if the ethernet frame is too big or too small */ if ((pktlen < ETHER_HDR_LEN) || (pktlen > (actlen - off))) goto tr_setup; /* Create a new mbuf to store the packet in */ m = uether_newbuf(); if (m == NULL) { smsc_warn_printf(sc, "failed to create new mbuf\n"); if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1); goto tr_setup; } usbd_copy_out(pc, off, mtod(m, uint8_t *), pktlen); /* Check if RX TCP/UDP checksumming is being offloaded */ if ((ifp->if_capenable & IFCAP_RXCSUM) != 0) { struct ether_header *eh; eh = mtod(m, struct ether_header *); /* Remove the extra 2 bytes of the csum */ pktlen -= 2; /* The checksum appears to be simplistically calculated * over the udp/tcp header and data up to the end of the * eth frame. Which means if the eth frame is padded * the csum calculation is incorrectly performed over * the padding bytes as well. Therefore to be safe we * ignore the H/W csum on frames less than or equal to * 64 bytes. * * Ignore H/W csum for non-IPv4 packets. */ if ((be16toh(eh->ether_type) == ETHERTYPE_IP) && (pktlen > ETHER_MIN_LEN)) { struct ip *ip; ip = (struct ip *)(eh + 1); if ((ip->ip_v == IPVERSION) && ((ip->ip_p == IPPROTO_TCP) || (ip->ip_p == IPPROTO_UDP))) { /* Indicate the UDP/TCP csum has been calculated */ m->m_pkthdr.csum_flags |= CSUM_DATA_VALID; /* Copy the TCP/UDP checksum from the last 2 bytes * of the transfer and put in the csum_data field. */ usbd_copy_out(pc, (off + pktlen), &m->m_pkthdr.csum_data, 2); /* The data is copied in network order, but the * csum algorithm in the kernel expects it to be * in host network order. */ m->m_pkthdr.csum_data = ntohs(m->m_pkthdr.csum_data); smsc_dbg_printf(sc, "RX checksum offloaded (0x%04x)\n", m->m_pkthdr.csum_data); } } /* Need to adjust the offset as well or we'll be off * by 2 because the csum is removed from the packet * length. */ off += 2; } /* Finally enqueue the mbuf on the receive queue */ /* Remove 4 trailing bytes */ if (pktlen < (4 + ETHER_HDR_LEN)) { m_freem(m); goto tr_setup; } uether_rxmbuf(ue, m, pktlen - 4); } /* Update the offset to move to the next potential packet */ off += pktlen; } /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); uether_rxflush(ue); return; default: if (error != USB_ERR_CANCELLED) { smsc_warn_printf(sc, "bulk read error, %s\n", usbd_errstr(error)); usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } /** * smsc_bulk_write_callback - Write callback used to send ethernet frame(s) * @xfer: the USB transfer * @error: error code if the transfers is in an errored state * * The main write function that pulls ethernet frames off the queue and sends * them out. * * LOCKING: * */ static void smsc_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct smsc_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct usb_page_cache *pc; struct mbuf *m; uint32_t txhdr; uint32_t frm_len = 0; int nframes; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: if ((sc->sc_flags & SMSC_FLAG_LINK) == 0 || (ifp->if_drv_flags & IFF_DRV_OACTIVE) != 0) { /* Don't send anything if there is no link or controller is busy. */ return; } for (nframes = 0; nframes < 16 && !IFQ_DRV_IS_EMPTY(&ifp->if_snd); nframes++) { IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; usbd_xfer_set_frame_offset(xfer, nframes * MCLBYTES, nframes); frm_len = 0; pc = usbd_xfer_get_frame(xfer, nframes); /* Each frame is prefixed with two 32-bit values describing the * length of the packet and buffer. */ txhdr = SMSC_TX_CTRL_0_BUF_SIZE(m->m_pkthdr.len) | SMSC_TX_CTRL_0_FIRST_SEG | SMSC_TX_CTRL_0_LAST_SEG; txhdr = htole32(txhdr); usbd_copy_in(pc, 0, &txhdr, sizeof(txhdr)); txhdr = SMSC_TX_CTRL_1_PKT_LENGTH(m->m_pkthdr.len); txhdr = htole32(txhdr); usbd_copy_in(pc, 4, &txhdr, sizeof(txhdr)); frm_len += 8; /* Next copy in the actual packet */ usbd_m_copy_in(pc, frm_len, m, 0, m->m_pkthdr.len); frm_len += m->m_pkthdr.len; if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* If there's a BPF listener, bounce a copy of this frame to him */ BPF_MTAP(ifp, m); m_freem(m); /* Set frame length. */ usbd_xfer_set_frame_len(xfer, nframes, frm_len); } if (nframes != 0) { usbd_xfer_set_frames(xfer, nframes); usbd_transfer_submit(xfer); ifp->if_drv_flags |= IFF_DRV_OACTIVE; } return; default: if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; if (error != USB_ERR_CANCELLED) { smsc_err_printf(sc, "usb error on tx: %s\n", usbd_errstr(error)); usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } /** * smsc_tick - Called periodically to monitor the state of the LAN95xx chip * @ue: USB ether interface * * Simply calls the mii status functions to check the state of the link. * * LOCKING: * Should be called with the SMSC lock held. */ static void smsc_tick(struct usb_ether *ue) { struct smsc_softc *sc = uether_getsc(ue); struct mii_data *mii = uether_getmii(&sc->sc_ue); SMSC_LOCK_ASSERT(sc, MA_OWNED); mii_tick(mii); if ((sc->sc_flags & SMSC_FLAG_LINK) == 0) { smsc_miibus_statchg(ue->ue_dev); if ((sc->sc_flags & SMSC_FLAG_LINK) != 0) smsc_start(ue); } } /** * smsc_start - Starts communication with the LAN95xx chip * @ue: USB ether interface * * * */ static void smsc_start(struct usb_ether *ue) { struct smsc_softc *sc = uether_getsc(ue); /* * start the USB transfers, if not already started: */ usbd_transfer_start(sc->sc_xfer[SMSC_BULK_DT_RD]); usbd_transfer_start(sc->sc_xfer[SMSC_BULK_DT_WR]); } /** * smsc_stop - Stops communication with the LAN95xx chip * @ue: USB ether interface * * * */ static void smsc_stop(struct usb_ether *ue) { struct smsc_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); SMSC_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); sc->sc_flags &= ~SMSC_FLAG_LINK; /* * stop all the transfers, if not already stopped: */ usbd_transfer_stop(sc->sc_xfer[SMSC_BULK_DT_WR]); usbd_transfer_stop(sc->sc_xfer[SMSC_BULK_DT_RD]); } /** * smsc_phy_init - Initialises the in-built SMSC phy * @sc: driver soft context * * Resets the PHY part of the chip and then initialises it to default * values. The 'link down' and 'auto-negotiation complete' interrupts * from the PHY are also enabled, however we don't monitor the interrupt * endpoints for the moment. * * RETURNS: * Returns 0 on success or EIO if failed to reset the PHY. */ static int smsc_phy_init(struct smsc_softc *sc) { int bmcr; usb_ticks_t start_ticks; const usb_ticks_t max_ticks = USB_MS_TO_TICKS(1000); SMSC_LOCK_ASSERT(sc, MA_OWNED); /* Reset phy and wait for reset to complete */ smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR, BMCR_RESET); start_ticks = ticks; do { uether_pause(&sc->sc_ue, hz / 100); bmcr = smsc_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR); } while ((bmcr & MII_BMCR) && ((ticks - start_ticks) < max_ticks)); if (((usb_ticks_t)(ticks - start_ticks)) >= max_ticks) { smsc_err_printf(sc, "PHY reset timed-out"); return (EIO); } smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_ANAR, ANAR_10 | ANAR_10_FD | ANAR_TX | ANAR_TX_FD | /* all modes */ ANAR_CSMA | ANAR_FC | ANAR_PAUSE_ASYM); /* Setup the phy to interrupt when the link goes down or autoneg completes */ smsc_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, SMSC_PHY_INTR_STAT); smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, SMSC_PHY_INTR_MASK, (SMSC_PHY_INTR_ANEG_COMP | SMSC_PHY_INTR_LINK_DOWN)); /* Restart auto-negotation */ bmcr = smsc_miibus_readreg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR); bmcr |= BMCR_STARTNEG; smsc_miibus_writereg(sc->sc_ue.ue_dev, sc->sc_phyno, MII_BMCR, bmcr); return (0); } /** * smsc_chip_init - Initialises the chip after power on * @sc: driver soft context * * This initialisation sequence is modelled on the procedure in the Linux * driver. * * RETURNS: * Returns 0 on success or an error code on failure. */ static int smsc_chip_init(struct smsc_softc *sc) { int err; int locked; uint32_t reg_val; int burst_cap; locked = mtx_owned(&sc->sc_mtx); if (!locked) SMSC_LOCK(sc); /* Enter H/W config mode */ smsc_write_reg(sc, SMSC_HW_CFG, SMSC_HW_CFG_LRST); if ((err = smsc_wait_for_bits(sc, SMSC_HW_CFG, SMSC_HW_CFG_LRST)) != 0) { smsc_warn_printf(sc, "timed-out waiting for reset to complete\n"); goto init_failed; } /* Reset the PHY */ smsc_write_reg(sc, SMSC_PM_CTRL, SMSC_PM_CTRL_PHY_RST); if ((err = smsc_wait_for_bits(sc, SMSC_PM_CTRL, SMSC_PM_CTRL_PHY_RST) != 0)) { smsc_warn_printf(sc, "timed-out waiting for phy reset to complete\n"); goto init_failed; } /* Set the mac address */ if ((err = smsc_setmacaddress(sc, sc->sc_ue.ue_eaddr)) != 0) { smsc_warn_printf(sc, "failed to set the MAC address\n"); goto init_failed; } /* Don't know what the HW_CFG_BIR bit is, but following the reset sequence * as used in the Linux driver. */ if ((err = smsc_read_reg(sc, SMSC_HW_CFG, ®_val)) != 0) { smsc_warn_printf(sc, "failed to read HW_CFG: %d\n", err); goto init_failed; } reg_val |= SMSC_HW_CFG_BIR; smsc_write_reg(sc, SMSC_HW_CFG, reg_val); /* There is a so called 'turbo mode' that the linux driver supports, it * seems to allow you to jam multiple frames per Rx transaction. By default * this driver supports that and therefore allows multiple frames per URB. * * The xfer buffer size needs to reflect this as well, therefore based on * the calculations in the Linux driver the RX bufsize is set to 18944, * bufsz = (16 * 1024 + 5 * 512) * * Burst capability is the number of URBs that can be in a burst of data/ * ethernet frames. */ if (usbd_get_speed(sc->sc_ue.ue_udev) == USB_SPEED_HIGH) burst_cap = 37; else burst_cap = 128; smsc_write_reg(sc, SMSC_BURST_CAP, burst_cap); /* Set the default bulk in delay (magic value from Linux driver) */ smsc_write_reg(sc, SMSC_BULK_IN_DLY, 0x00002000); /* * Initialise the RX interface */ if ((err = smsc_read_reg(sc, SMSC_HW_CFG, ®_val)) < 0) { smsc_warn_printf(sc, "failed to read HW_CFG: (err = %d)\n", err); goto init_failed; } /* Adjust the packet offset in the buffer (designed to try and align IP * header on 4 byte boundary) */ reg_val &= ~SMSC_HW_CFG_RXDOFF; reg_val |= (ETHER_ALIGN << 9) & SMSC_HW_CFG_RXDOFF; /* The following setings are used for 'turbo mode', a.k.a multiple frames * per Rx transaction (again info taken form Linux driver). */ reg_val |= (SMSC_HW_CFG_MEF | SMSC_HW_CFG_BCE); smsc_write_reg(sc, SMSC_HW_CFG, reg_val); /* Clear the status register ? */ smsc_write_reg(sc, SMSC_INTR_STATUS, 0xffffffff); /* Read and display the revision register */ if ((err = smsc_read_reg(sc, SMSC_ID_REV, &sc->sc_rev_id)) < 0) { smsc_warn_printf(sc, "failed to read ID_REV (err = %d)\n", err); goto init_failed; } device_printf(sc->sc_ue.ue_dev, "chip 0x%04lx, rev. %04lx\n", (sc->sc_rev_id & SMSC_ID_REV_CHIP_ID_MASK) >> 16, (sc->sc_rev_id & SMSC_ID_REV_CHIP_REV_MASK)); /* GPIO/LED setup */ reg_val = SMSC_LED_GPIO_CFG_SPD_LED | SMSC_LED_GPIO_CFG_LNK_LED | SMSC_LED_GPIO_CFG_FDX_LED; smsc_write_reg(sc, SMSC_LED_GPIO_CFG, reg_val); /* * Initialise the TX interface */ smsc_write_reg(sc, SMSC_FLOW, 0); smsc_write_reg(sc, SMSC_AFC_CFG, AFC_CFG_DEFAULT); /* Read the current MAC configuration */ if ((err = smsc_read_reg(sc, SMSC_MAC_CSR, &sc->sc_mac_csr)) < 0) { smsc_warn_printf(sc, "failed to read MAC_CSR (err=%d)\n", err); goto init_failed; } /* Vlan */ smsc_write_reg(sc, SMSC_VLAN1, (uint32_t)ETHERTYPE_VLAN); /* * Initialise the PHY */ if ((err = smsc_phy_init(sc)) != 0) goto init_failed; /* * Start TX */ sc->sc_mac_csr |= SMSC_MAC_CSR_TXEN; smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr); smsc_write_reg(sc, SMSC_TX_CFG, SMSC_TX_CFG_ON); /* * Start RX */ sc->sc_mac_csr |= SMSC_MAC_CSR_RXEN; smsc_write_reg(sc, SMSC_MAC_CSR, sc->sc_mac_csr); if (!locked) SMSC_UNLOCK(sc); return (0); init_failed: if (!locked) SMSC_UNLOCK(sc); smsc_err_printf(sc, "smsc_chip_init failed (err=%d)\n", err); return (err); } /** * smsc_ioctl - ioctl function for the device * @ifp: interface pointer * @cmd: the ioctl command * @data: data passed in the ioctl call, typically a pointer to struct ifreq. * * The ioctl routine is overridden to detect change requests for the H/W * checksum capabilities. * * RETURNS: * 0 on success and an error code on failure. */ static int smsc_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) { struct usb_ether *ue = ifp->if_softc; struct smsc_softc *sc; struct ifreq *ifr; int rc; int mask; int reinit; if (cmd == SIOCSIFCAP) { sc = uether_getsc(ue); ifr = (struct ifreq *)data; SMSC_LOCK(sc); rc = 0; reinit = 0; mask = ifr->ifr_reqcap ^ ifp->if_capenable; /* Modify the RX CSUM enable bits */ if ((mask & IFCAP_RXCSUM) != 0 && (ifp->if_capabilities & IFCAP_RXCSUM) != 0) { ifp->if_capenable ^= IFCAP_RXCSUM; if (ifp->if_drv_flags & IFF_DRV_RUNNING) { ifp->if_drv_flags &= ~IFF_DRV_RUNNING; reinit = 1; } } SMSC_UNLOCK(sc); if (reinit) #if __FreeBSD_version > 1000000 uether_init(ue); #else ifp->if_init(ue); #endif } else { rc = uether_ioctl(ifp, cmd, data); } return (rc); } #ifdef FDT static phandle_t smsc_fdt_find_eth_node(phandle_t start) { phandle_t child, node; /* Traverse through entire tree to find usb ethernet nodes. */ for (node = OF_child(start); node != 0; node = OF_peer(node)) { if (fdt_is_compatible(node, "net,ethernet") && fdt_is_compatible(node, "usb,device")) return (node); child = smsc_fdt_find_eth_node(node); if (child != 0) return (child); } return (0); } /** * Get MAC address from FDT blob. Firmware or loader should fill * mac-address or local-mac-address property. Returns 0 if MAC address * obtained, error code otherwise. */ static int smsc_fdt_find_mac(unsigned char *mac) { phandle_t node, root; int len; root = OF_finddevice("/"); node = smsc_fdt_find_eth_node(root); if (node != 0) { /* Check if there is property */ if ((len = OF_getproplen(node, "local-mac-address")) > 0) { if (len != ETHER_ADDR_LEN) return (EINVAL); OF_getprop(node, "local-mac-address", mac, ETHER_ADDR_LEN); return (0); } if ((len = OF_getproplen(node, "mac-address")) > 0) { if (len != ETHER_ADDR_LEN) return (EINVAL); OF_getprop(node, "mac-address", mac, ETHER_ADDR_LEN); return (0); } } return (ENXIO); } #endif /** * smsc_attach_post - Called after the driver attached to the USB interface * @ue: the USB ethernet device * * This is where the chip is intialised for the first time. This is different * from the smsc_init() function in that that one is designed to setup the * H/W to match the UE settings and can be called after a reset. * * */ static void smsc_attach_post(struct usb_ether *ue) { struct smsc_softc *sc = uether_getsc(ue); uint32_t mac_h, mac_l; int err; smsc_dbg_printf(sc, "smsc_attach_post\n"); /* Setup some of the basics */ sc->sc_phyno = 1; /* Attempt to get the mac address, if an EEPROM is not attached this * will just return FF:FF:FF:FF:FF:FF, so in such cases we invent a MAC * address based on urandom. */ memset(sc->sc_ue.ue_eaddr, 0xff, ETHER_ADDR_LEN); /* Check if there is already a MAC address in the register */ if ((smsc_read_reg(sc, SMSC_MAC_ADDRL, &mac_l) == 0) && (smsc_read_reg(sc, SMSC_MAC_ADDRH, &mac_h) == 0)) { sc->sc_ue.ue_eaddr[5] = (uint8_t)((mac_h >> 8) & 0xff); sc->sc_ue.ue_eaddr[4] = (uint8_t)((mac_h) & 0xff); sc->sc_ue.ue_eaddr[3] = (uint8_t)((mac_l >> 24) & 0xff); sc->sc_ue.ue_eaddr[2] = (uint8_t)((mac_l >> 16) & 0xff); sc->sc_ue.ue_eaddr[1] = (uint8_t)((mac_l >> 8) & 0xff); sc->sc_ue.ue_eaddr[0] = (uint8_t)((mac_l) & 0xff); } /* MAC address is not set so try to read from EEPROM, if that fails generate * a random MAC address. */ if (!ETHER_IS_VALID(sc->sc_ue.ue_eaddr)) { err = smsc_eeprom_read(sc, 0x01, sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN); #ifdef FDT if ((err != 0) || (!ETHER_IS_VALID(sc->sc_ue.ue_eaddr))) err = smsc_fdt_find_mac(sc->sc_ue.ue_eaddr); #endif if ((err != 0) || (!ETHER_IS_VALID(sc->sc_ue.ue_eaddr))) { read_random(sc->sc_ue.ue_eaddr, ETHER_ADDR_LEN); sc->sc_ue.ue_eaddr[0] &= ~0x01; /* unicast */ sc->sc_ue.ue_eaddr[0] |= 0x02; /* locally administered */ } } /* Initialise the chip for the first time */ smsc_chip_init(sc); } /** * smsc_attach_post_sub - Called after the driver attached to the USB interface * @ue: the USB ethernet device * * Most of this is boilerplate code and copied from the base USB ethernet * driver. It has been overriden so that we can indicate to the system that * the chip supports H/W checksumming. * * RETURNS: * Returns 0 on success or a negative error code. */ #if __FreeBSD_version > 1000000 static int smsc_attach_post_sub(struct usb_ether *ue) { struct smsc_softc *sc; struct ifnet *ifp; int error; sc = uether_getsc(ue); ifp = ue->ue_ifp; ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; ifp->if_start = uether_start; ifp->if_ioctl = smsc_ioctl; ifp->if_init = uether_init; IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen); ifp->if_snd.ifq_drv_maxlen = ifqmaxlen; IFQ_SET_READY(&ifp->if_snd); /* The chip supports TCP/UDP checksum offloading on TX and RX paths, however * currently only RX checksum is supported in the driver (see top of file). */ ifp->if_capabilities |= IFCAP_RXCSUM; ifp->if_hwassist = 0; /* TX checksuming is disabled (for now?) ifp->if_capabilities |= IFCAP_TXCSUM; ifp->if_capenable |= IFCAP_TXCSUM; ifp->if_hwassist = CSUM_TCP | CSUM_UDP; */ ifp->if_capenable = ifp->if_capabilities; mtx_lock(&Giant); error = mii_attach(ue->ue_dev, &ue->ue_miibus, ifp, uether_ifmedia_upd, ue->ue_methods->ue_mii_sts, BMSR_DEFCAPMASK, sc->sc_phyno, MII_OFFSET_ANY, 0); mtx_unlock(&Giant); return (error); } #endif /* __FreeBSD_version > 1000000 */ /** * smsc_probe - Probe the interface. * @dev: smsc device handle * * Checks if the device is a match for this driver. * * RETURNS: * Returns 0 on success or an error code on failure. */ static int smsc_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != SMSC_CONFIG_INDEX) return (ENXIO); if (uaa->info.bIfaceIndex != SMSC_IFACE_IDX) return (ENXIO); return (usbd_lookup_id_by_uaa(smsc_devs, sizeof(smsc_devs), uaa)); } /** * smsc_attach - Attach the interface. * @dev: smsc device handle * * Allocate softc structures, do ifmedia setup and ethernet/BPF attach. * * RETURNS: * Returns 0 on success or a negative error code. */ static int smsc_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct smsc_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; uint8_t iface_index; int err; sc->sc_flags = USB_GET_DRIVER_INFO(uaa); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF); /* Setup the endpoints for the SMSC LAN95xx device(s) */ iface_index = SMSC_IFACE_IDX; err = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, smsc_config, SMSC_N_TRANSFER, sc, &sc->sc_mtx); if (err) { device_printf(dev, "error: allocating USB transfers failed\n"); goto detach; } ue->ue_sc = sc; ue->ue_dev = dev; ue->ue_udev = uaa->device; ue->ue_mtx = &sc->sc_mtx; ue->ue_methods = &smsc_ue_methods; err = uether_ifattach(ue); if (err) { device_printf(dev, "error: could not attach interface\n"); goto detach; } return (0); /* success */ detach: smsc_detach(dev); return (ENXIO); /* failure */ } /** * smsc_detach - Detach the interface. * @dev: smsc device handle * * RETURNS: * Returns 0. */ static int smsc_detach(device_t dev) { struct smsc_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; usbd_transfer_unsetup(sc->sc_xfer, SMSC_N_TRANSFER); uether_ifdetach(ue); mtx_destroy(&sc->sc_mtx); return (0); } static device_method_t smsc_methods[] = { /* Device interface */ DEVMETHOD(device_probe, smsc_probe), DEVMETHOD(device_attach, smsc_attach), DEVMETHOD(device_detach, smsc_detach), /* bus interface */ DEVMETHOD(bus_print_child, bus_generic_print_child), DEVMETHOD(bus_driver_added, bus_generic_driver_added), /* MII interface */ DEVMETHOD(miibus_readreg, smsc_miibus_readreg), DEVMETHOD(miibus_writereg, smsc_miibus_writereg), DEVMETHOD(miibus_statchg, smsc_miibus_statchg), DEVMETHOD_END }; static driver_t smsc_driver = { .name = "smsc", .methods = smsc_methods, .size = sizeof(struct smsc_softc), }; static devclass_t smsc_devclass; DRIVER_MODULE(smsc, uhub, smsc_driver, smsc_devclass, NULL, 0); DRIVER_MODULE(miibus, smsc, miibus_driver, miibus_devclass, 0, 0); MODULE_DEPEND(smsc, uether, 1, 1, 1); MODULE_DEPEND(smsc, usb, 1, 1, 1); MODULE_DEPEND(smsc, ether, 1, 1, 1); MODULE_DEPEND(smsc, miibus, 1, 1, 1); MODULE_VERSION(smsc, 1); Index: head/sys/dev/usb/net/if_udav.c =================================================================== --- head/sys/dev/usb/net/if_udav.c (revision 276700) +++ head/sys/dev/usb/net/if_udav.c (revision 276701) @@ -1,880 +1,880 @@ /* $NetBSD: if_udav.c,v 1.2 2003/09/04 15:17:38 tsutsui Exp $ */ /* $nabe: if_udav.c,v 1.3 2003/08/21 16:57:19 nabe Exp $ */ /* $FreeBSD$ */ /*- * Copyright (c) 2003 * Shingo WATANABE . All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ /* * DM9601(DAVICOM USB to Ethernet MAC Controller with Integrated 10/100 PHY) * The spec can be found at the following url. * http://ptm2.cc.utu.fi/ftp/network/cards/DM9601/From_NET/DM9601-DS-P01-930914.pdf */ /* * TODO: * Interrupt Endpoint support * External PHYs */ #include __FBSDID("$FreeBSD$"); #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 "usbdevs.h" #define USB_DEBUG_VAR udav_debug #include #include #include #include /* prototypes */ static device_probe_t udav_probe; static device_attach_t udav_attach; static device_detach_t udav_detach; static usb_callback_t udav_bulk_write_callback; static usb_callback_t udav_bulk_read_callback; static usb_callback_t udav_intr_callback; static uether_fn_t udav_attach_post; static uether_fn_t udav_init; static uether_fn_t udav_stop; static uether_fn_t udav_start; static uether_fn_t udav_tick; static uether_fn_t udav_setmulti; static uether_fn_t udav_setpromisc; static int udav_csr_read(struct udav_softc *, uint16_t, void *, int); static int udav_csr_write(struct udav_softc *, uint16_t, void *, int); static uint8_t udav_csr_read1(struct udav_softc *, uint16_t); static int udav_csr_write1(struct udav_softc *, uint16_t, uint8_t); static void udav_reset(struct udav_softc *); static int udav_ifmedia_upd(struct ifnet *); static void udav_ifmedia_status(struct ifnet *, struct ifmediareq *); static miibus_readreg_t udav_miibus_readreg; static miibus_writereg_t udav_miibus_writereg; static miibus_statchg_t udav_miibus_statchg; static const struct usb_config udav_config[UDAV_N_TRANSFER] = { [UDAV_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = (MCLBYTES + 2), .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = udav_bulk_write_callback, .timeout = 10000, /* 10 seconds */ }, [UDAV_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = (MCLBYTES + 3), .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = udav_bulk_read_callback, .timeout = 0, /* no timeout */ }, [UDAV_INTR_DT_RD] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = udav_intr_callback, }, }; static device_method_t udav_methods[] = { /* Device interface */ DEVMETHOD(device_probe, udav_probe), DEVMETHOD(device_attach, udav_attach), DEVMETHOD(device_detach, udav_detach), /* MII interface */ DEVMETHOD(miibus_readreg, udav_miibus_readreg), DEVMETHOD(miibus_writereg, udav_miibus_writereg), DEVMETHOD(miibus_statchg, udav_miibus_statchg), DEVMETHOD_END }; static driver_t udav_driver = { .name = "udav", .methods = udav_methods, .size = sizeof(struct udav_softc), }; static devclass_t udav_devclass; DRIVER_MODULE(udav, uhub, udav_driver, udav_devclass, NULL, 0); DRIVER_MODULE(miibus, udav, miibus_driver, miibus_devclass, 0, 0); MODULE_DEPEND(udav, uether, 1, 1, 1); MODULE_DEPEND(udav, usb, 1, 1, 1); MODULE_DEPEND(udav, ether, 1, 1, 1); MODULE_DEPEND(udav, miibus, 1, 1, 1); MODULE_VERSION(udav, 1); static const struct usb_ether_methods udav_ue_methods = { .ue_attach_post = udav_attach_post, .ue_start = udav_start, .ue_init = udav_init, .ue_stop = udav_stop, .ue_tick = udav_tick, .ue_setmulti = udav_setmulti, .ue_setpromisc = udav_setpromisc, .ue_mii_upd = udav_ifmedia_upd, .ue_mii_sts = udav_ifmedia_status, }; static const struct usb_ether_methods udav_ue_methods_nophy = { .ue_attach_post = udav_attach_post, .ue_start = udav_start, .ue_init = udav_init, .ue_stop = udav_stop, .ue_setmulti = udav_setmulti, .ue_setpromisc = udav_setpromisc, }; #ifdef USB_DEBUG static int udav_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, udav, CTLFLAG_RW, 0, "USB udav"); -SYSCTL_INT(_hw_usb_udav, OID_AUTO, debug, CTLFLAG_RW, &udav_debug, 0, +SYSCTL_INT(_hw_usb_udav, OID_AUTO, debug, CTLFLAG_RWTUN, &udav_debug, 0, "Debug level"); #endif #define UDAV_SETBIT(sc, reg, x) \ udav_csr_write1(sc, reg, udav_csr_read1(sc, reg) | (x)) #define UDAV_CLRBIT(sc, reg, x) \ udav_csr_write1(sc, reg, udav_csr_read1(sc, reg) & ~(x)) static const STRUCT_USB_HOST_ID udav_devs[] = { /* ShanTou DM9601 USB NIC */ {USB_VPI(USB_VENDOR_SHANTOU, USB_PRODUCT_SHANTOU_DM9601, 0)}, /* ShanTou ST268 USB NIC */ {USB_VPI(USB_VENDOR_SHANTOU, USB_PRODUCT_SHANTOU_ST268, 0)}, /* Corega USB-TXC */ {USB_VPI(USB_VENDOR_COREGA, USB_PRODUCT_COREGA_FETHER_USB_TXC, 0)}, /* ShanTou AMD8515 USB NIC */ {USB_VPI(USB_VENDOR_SHANTOU, USB_PRODUCT_SHANTOU_ADM8515, 0)}, /* Kontron AG USB Ethernet */ {USB_VPI(USB_VENDOR_KONTRON, USB_PRODUCT_KONTRON_DM9601, 0)}, {USB_VPI(USB_VENDOR_KONTRON, USB_PRODUCT_KONTRON_JP1082, UDAV_FLAG_NO_PHY)}, }; static void udav_attach_post(struct usb_ether *ue) { struct udav_softc *sc = uether_getsc(ue); /* reset the adapter */ udav_reset(sc); /* Get Ethernet Address */ udav_csr_read(sc, UDAV_PAR, ue->ue_eaddr, ETHER_ADDR_LEN); } static int udav_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != UDAV_CONFIG_INDEX) return (ENXIO); if (uaa->info.bIfaceIndex != UDAV_IFACE_INDEX) return (ENXIO); return (usbd_lookup_id_by_uaa(udav_devs, sizeof(udav_devs), uaa)); } static int udav_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct udav_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; uint8_t iface_index; int error; sc->sc_flags = USB_GET_DRIVER_INFO(uaa); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF); iface_index = UDAV_IFACE_INDEX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, udav_config, UDAV_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(dev, "allocating USB transfers failed\n"); goto detach; } /* * The JP1082 has an unusable PHY and provides no link information. */ if (sc->sc_flags & UDAV_FLAG_NO_PHY) { ue->ue_methods = &udav_ue_methods_nophy; sc->sc_flags |= UDAV_FLAG_LINK; } else { ue->ue_methods = &udav_ue_methods; } ue->ue_sc = sc; ue->ue_dev = dev; ue->ue_udev = uaa->device; ue->ue_mtx = &sc->sc_mtx; error = uether_ifattach(ue); if (error) { device_printf(dev, "could not attach interface\n"); goto detach; } return (0); /* success */ detach: udav_detach(dev); return (ENXIO); /* failure */ } static int udav_detach(device_t dev) { struct udav_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; usbd_transfer_unsetup(sc->sc_xfer, UDAV_N_TRANSFER); uether_ifdetach(ue); mtx_destroy(&sc->sc_mtx); return (0); } #if 0 static int udav_mem_read(struct udav_softc *sc, uint16_t offset, void *buf, int len) { struct usb_device_request req; len &= 0xff; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = UDAV_REQ_MEM_READ; USETW(req.wValue, 0x0000); USETW(req.wIndex, offset); USETW(req.wLength, len); return (uether_do_request(&sc->sc_ue, &req, buf, 1000)); } static int udav_mem_write(struct udav_softc *sc, uint16_t offset, void *buf, int len) { struct usb_device_request req; len &= 0xff; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = UDAV_REQ_MEM_WRITE; USETW(req.wValue, 0x0000); USETW(req.wIndex, offset); USETW(req.wLength, len); return (uether_do_request(&sc->sc_ue, &req, buf, 1000)); } static int udav_mem_write1(struct udav_softc *sc, uint16_t offset, uint8_t ch) { struct usb_device_request req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = UDAV_REQ_MEM_WRITE1; USETW(req.wValue, ch); USETW(req.wIndex, offset); USETW(req.wLength, 0x0000); return (uether_do_request(&sc->sc_ue, &req, NULL, 1000)); } #endif static int udav_csr_read(struct udav_softc *sc, uint16_t offset, void *buf, int len) { struct usb_device_request req; len &= 0xff; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = UDAV_REQ_REG_READ; USETW(req.wValue, 0x0000); USETW(req.wIndex, offset); USETW(req.wLength, len); return (uether_do_request(&sc->sc_ue, &req, buf, 1000)); } static int udav_csr_write(struct udav_softc *sc, uint16_t offset, void *buf, int len) { struct usb_device_request req; offset &= 0xff; len &= 0xff; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = UDAV_REQ_REG_WRITE; USETW(req.wValue, 0x0000); USETW(req.wIndex, offset); USETW(req.wLength, len); return (uether_do_request(&sc->sc_ue, &req, buf, 1000)); } static uint8_t udav_csr_read1(struct udav_softc *sc, uint16_t offset) { uint8_t val; udav_csr_read(sc, offset, &val, 1); return (val); } static int udav_csr_write1(struct udav_softc *sc, uint16_t offset, uint8_t ch) { struct usb_device_request req; offset &= 0xff; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = UDAV_REQ_REG_WRITE1; USETW(req.wValue, ch); USETW(req.wIndex, offset); USETW(req.wLength, 0x0000); return (uether_do_request(&sc->sc_ue, &req, NULL, 1000)); } static void udav_init(struct usb_ether *ue) { struct udav_softc *sc = ue->ue_sc; struct ifnet *ifp = uether_getifp(&sc->sc_ue); UDAV_LOCK_ASSERT(sc, MA_OWNED); /* * Cancel pending I/O */ udav_stop(ue); /* set MAC address */ udav_csr_write(sc, UDAV_PAR, IF_LLADDR(ifp), ETHER_ADDR_LEN); /* initialize network control register */ /* disable loopback */ UDAV_CLRBIT(sc, UDAV_NCR, UDAV_NCR_LBK0 | UDAV_NCR_LBK1); /* Initialize RX control register */ UDAV_SETBIT(sc, UDAV_RCR, UDAV_RCR_DIS_LONG | UDAV_RCR_DIS_CRC); /* load multicast filter and update promiscious mode bit */ udav_setpromisc(ue); /* enable RX */ UDAV_SETBIT(sc, UDAV_RCR, UDAV_RCR_RXEN); /* clear POWER_DOWN state of internal PHY */ UDAV_SETBIT(sc, UDAV_GPCR, UDAV_GPCR_GEP_CNTL0); UDAV_CLRBIT(sc, UDAV_GPR, UDAV_GPR_GEPIO0); usbd_xfer_set_stall(sc->sc_xfer[UDAV_BULK_DT_WR]); ifp->if_drv_flags |= IFF_DRV_RUNNING; udav_start(ue); } static void udav_reset(struct udav_softc *sc) { int i; /* Select PHY */ #if 1 /* * XXX: force select internal phy. * external phy routines are not tested. */ UDAV_CLRBIT(sc, UDAV_NCR, UDAV_NCR_EXT_PHY); #else if (sc->sc_flags & UDAV_EXT_PHY) UDAV_SETBIT(sc, UDAV_NCR, UDAV_NCR_EXT_PHY); else UDAV_CLRBIT(sc, UDAV_NCR, UDAV_NCR_EXT_PHY); #endif UDAV_SETBIT(sc, UDAV_NCR, UDAV_NCR_RST); for (i = 0; i < UDAV_TX_TIMEOUT; i++) { if (!(udav_csr_read1(sc, UDAV_NCR) & UDAV_NCR_RST)) break; if (uether_pause(&sc->sc_ue, hz / 100)) break; } uether_pause(&sc->sc_ue, hz / 100); } #define UDAV_BITS 6 static void udav_setmulti(struct usb_ether *ue) { struct udav_softc *sc = ue->ue_sc; struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct ifmultiaddr *ifma; uint8_t hashtbl[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; int h = 0; UDAV_LOCK_ASSERT(sc, MA_OWNED); if (ifp->if_flags & IFF_ALLMULTI || ifp->if_flags & IFF_PROMISC) { UDAV_SETBIT(sc, UDAV_RCR, UDAV_RCR_ALL|UDAV_RCR_PRMSC); return; } /* first, zot all the existing hash bits */ memset(hashtbl, 0x00, sizeof(hashtbl)); hashtbl[7] |= 0x80; /* broadcast address */ udav_csr_write(sc, UDAV_MAR, hashtbl, sizeof(hashtbl)); /* now program new ones */ if_maddr_rlock(ifp); TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) { if (ifma->ifma_addr->sa_family != AF_LINK) continue; h = ether_crc32_be(LLADDR((struct sockaddr_dl *) ifma->ifma_addr), ETHER_ADDR_LEN) >> 26; hashtbl[h / 8] |= 1 << (h % 8); } if_maddr_runlock(ifp); /* disable all multicast */ UDAV_CLRBIT(sc, UDAV_RCR, UDAV_RCR_ALL); /* write hash value to the register */ udav_csr_write(sc, UDAV_MAR, hashtbl, sizeof(hashtbl)); } static void udav_setpromisc(struct usb_ether *ue) { struct udav_softc *sc = ue->ue_sc; struct ifnet *ifp = uether_getifp(&sc->sc_ue); uint8_t rxmode; rxmode = udav_csr_read1(sc, UDAV_RCR); rxmode &= ~(UDAV_RCR_ALL | UDAV_RCR_PRMSC); if (ifp->if_flags & IFF_PROMISC) rxmode |= UDAV_RCR_ALL | UDAV_RCR_PRMSC; else if (ifp->if_flags & IFF_ALLMULTI) rxmode |= UDAV_RCR_ALL; /* write new mode bits */ udav_csr_write1(sc, UDAV_RCR, rxmode); } static void udav_start(struct usb_ether *ue) { struct udav_softc *sc = ue->ue_sc; /* * start the USB transfers, if not already started: */ usbd_transfer_start(sc->sc_xfer[UDAV_INTR_DT_RD]); usbd_transfer_start(sc->sc_xfer[UDAV_BULK_DT_RD]); usbd_transfer_start(sc->sc_xfer[UDAV_BULK_DT_WR]); } static void udav_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct udav_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct usb_page_cache *pc; struct mbuf *m; int extra_len; int temp_len; uint8_t buf[2]; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(11, "transfer complete\n"); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: if ((sc->sc_flags & UDAV_FLAG_LINK) == 0) { /* * don't send anything if there is no link ! */ return; } IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) return; if (m->m_pkthdr.len > MCLBYTES) m->m_pkthdr.len = MCLBYTES; if (m->m_pkthdr.len < UDAV_MIN_FRAME_LEN) { extra_len = UDAV_MIN_FRAME_LEN - m->m_pkthdr.len; } else { extra_len = 0; } temp_len = (m->m_pkthdr.len + extra_len); /* * the frame length is specified in the first 2 bytes of the * buffer */ buf[0] = (uint8_t)(temp_len); buf[1] = (uint8_t)(temp_len >> 8); temp_len += 2; pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, buf, 2); usbd_m_copy_in(pc, 2, m, 0, m->m_pkthdr.len); if (extra_len) usbd_frame_zero(pc, temp_len - extra_len, extra_len); /* * if there's a BPF listener, bounce a copy * of this frame to him: */ BPF_MTAP(ifp, m); m_freem(m); usbd_xfer_set_frame_len(xfer, 0, temp_len); usbd_transfer_submit(xfer); return; default: /* Error */ DPRINTFN(11, "transfer error, %s\n", usbd_errstr(error)); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void udav_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct udav_softc *sc = usbd_xfer_softc(xfer); struct usb_ether *ue = &sc->sc_ue; struct ifnet *ifp = uether_getifp(ue); struct usb_page_cache *pc; struct udav_rxpkt stat; int len; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen < (int)(sizeof(stat) + ETHER_CRC_LEN)) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, &stat, sizeof(stat)); actlen -= sizeof(stat); len = min(actlen, le16toh(stat.pktlen)); len -= ETHER_CRC_LEN; if (stat.rxstat & UDAV_RSR_LCS) { if_inc_counter(ifp, IFCOUNTER_COLLISIONS, 1); goto tr_setup; } if (stat.rxstat & UDAV_RSR_ERR) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } uether_rxbuf(ue, pc, sizeof(stat), len); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); uether_rxflush(ue); return; default: /* Error */ DPRINTF("bulk read error, %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void udav_intr_callback(struct usb_xfer *xfer, usb_error_t error) { switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void udav_stop(struct usb_ether *ue) { struct udav_softc *sc = ue->ue_sc; struct ifnet *ifp = uether_getifp(&sc->sc_ue); UDAV_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags &= ~IFF_DRV_RUNNING; if (!(sc->sc_flags & UDAV_FLAG_NO_PHY)) sc->sc_flags &= ~UDAV_FLAG_LINK; /* * stop all the transfers, if not already stopped: */ usbd_transfer_stop(sc->sc_xfer[UDAV_BULK_DT_WR]); usbd_transfer_stop(sc->sc_xfer[UDAV_BULK_DT_RD]); usbd_transfer_stop(sc->sc_xfer[UDAV_INTR_DT_RD]); udav_reset(sc); } static int udav_ifmedia_upd(struct ifnet *ifp) { struct udav_softc *sc = ifp->if_softc; struct mii_data *mii = GET_MII(sc); struct mii_softc *miisc; int error; UDAV_LOCK_ASSERT(sc, MA_OWNED); sc->sc_flags &= ~UDAV_FLAG_LINK; LIST_FOREACH(miisc, &mii->mii_phys, mii_list) PHY_RESET(miisc); error = mii_mediachg(mii); return (error); } static void udav_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr) { struct udav_softc *sc = ifp->if_softc; struct mii_data *mii = GET_MII(sc); UDAV_LOCK(sc); mii_pollstat(mii); ifmr->ifm_active = mii->mii_media_active; ifmr->ifm_status = mii->mii_media_status; UDAV_UNLOCK(sc); } static void udav_tick(struct usb_ether *ue) { struct udav_softc *sc = ue->ue_sc; struct mii_data *mii = GET_MII(sc); UDAV_LOCK_ASSERT(sc, MA_OWNED); mii_tick(mii); if ((sc->sc_flags & UDAV_FLAG_LINK) == 0 && mii->mii_media_status & IFM_ACTIVE && IFM_SUBTYPE(mii->mii_media_active) != IFM_NONE) { sc->sc_flags |= UDAV_FLAG_LINK; udav_start(ue); } } static int udav_miibus_readreg(device_t dev, int phy, int reg) { struct udav_softc *sc = device_get_softc(dev); uint16_t data16; uint8_t val[2]; int locked; /* XXX: one PHY only for the internal PHY */ if (phy != 0) return (0); locked = mtx_owned(&sc->sc_mtx); if (!locked) UDAV_LOCK(sc); /* select internal PHY and set PHY register address */ udav_csr_write1(sc, UDAV_EPAR, UDAV_EPAR_PHY_ADR0 | (reg & UDAV_EPAR_EROA_MASK)); /* select PHY operation and start read command */ udav_csr_write1(sc, UDAV_EPCR, UDAV_EPCR_EPOS | UDAV_EPCR_ERPRR); /* XXX: should we wait? */ /* end read command */ UDAV_CLRBIT(sc, UDAV_EPCR, UDAV_EPCR_ERPRR); /* retrieve the result from data registers */ udav_csr_read(sc, UDAV_EPDRL, val, 2); data16 = (val[0] | (val[1] << 8)); DPRINTFN(11, "phy=%d reg=0x%04x => 0x%04x\n", phy, reg, data16); if (!locked) UDAV_UNLOCK(sc); return (data16); } static int udav_miibus_writereg(device_t dev, int phy, int reg, int data) { struct udav_softc *sc = device_get_softc(dev); uint8_t val[2]; int locked; /* XXX: one PHY only for the internal PHY */ if (phy != 0) return (0); locked = mtx_owned(&sc->sc_mtx); if (!locked) UDAV_LOCK(sc); /* select internal PHY and set PHY register address */ udav_csr_write1(sc, UDAV_EPAR, UDAV_EPAR_PHY_ADR0 | (reg & UDAV_EPAR_EROA_MASK)); /* put the value to the data registers */ val[0] = (data & 0xff); val[1] = (data >> 8) & 0xff; udav_csr_write(sc, UDAV_EPDRL, val, 2); /* select PHY operation and start write command */ udav_csr_write1(sc, UDAV_EPCR, UDAV_EPCR_EPOS | UDAV_EPCR_ERPRW); /* XXX: should we wait? */ /* end write command */ UDAV_CLRBIT(sc, UDAV_EPCR, UDAV_EPCR_ERPRW); if (!locked) UDAV_UNLOCK(sc); return (0); } static void udav_miibus_statchg(device_t dev) { /* nothing to do */ } Index: head/sys/dev/usb/net/if_urndis.c =================================================================== --- head/sys/dev/usb/net/if_urndis.c (revision 276700) +++ head/sys/dev/usb/net/if_urndis.c (revision 276701) @@ -1,1016 +1,1016 @@ /* $OpenBSD: if_urndis.c,v 1.46 2013/12/09 15:45:29 pirofti Exp $ */ /* * Copyright (c) 2010 Jonathan Armani * Copyright (c) 2010 Fabien Romano * Copyright (c) 2010 Michael Knudsen * Copyright (c) 2014 Hans Petter Selasky * All rights reserved. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include __FBSDID("$FreeBSD$"); #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 "usbdevs.h" #define USB_DEBUG_VAR urndis_debug #include #include #include "usb_if.h" #include #include #include static device_probe_t urndis_probe; static device_attach_t urndis_attach; static device_detach_t urndis_detach; static device_suspend_t urndis_suspend; static device_resume_t urndis_resume; static usb_callback_t urndis_bulk_write_callback; static usb_callback_t urndis_bulk_read_callback; static usb_callback_t urndis_intr_read_callback; static uether_fn_t urndis_attach_post; static uether_fn_t urndis_init; static uether_fn_t urndis_stop; static uether_fn_t urndis_start; static uether_fn_t urndis_setmulti; static uether_fn_t urndis_setpromisc; static uint32_t urndis_ctrl_query(struct urndis_softc *, uint32_t, const void **, uint16_t *); static uint32_t urndis_ctrl_set(struct urndis_softc *, uint32_t, struct urndis_set_req *, uint16_t); static uint32_t urndis_ctrl_handle_init(struct urndis_softc *, const struct urndis_comp_hdr *); static uint32_t urndis_ctrl_handle_query(struct urndis_softc *, const struct urndis_comp_hdr *, const void **, uint16_t *); static uint32_t urndis_ctrl_handle_reset(struct urndis_softc *, const struct urndis_comp_hdr *); static uint32_t urndis_ctrl_init(struct urndis_softc *); #ifdef USB_DEBUG static int urndis_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, urndis, CTLFLAG_RW, 0, "USB RNDIS-Ethernet"); -SYSCTL_INT(_hw_usb_urndis, OID_AUTO, debug, CTLFLAG_RW, &urndis_debug, 0, +SYSCTL_INT(_hw_usb_urndis, OID_AUTO, debug, CTLFLAG_RWTUN, &urndis_debug, 0, "Debug level"); #endif static const struct usb_config urndis_config[URNDIS_N_TRANSFER] = { [URNDIS_BULK_RX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_RX, .if_index = 0, .frames = 1, .bufsize = RNDIS_RX_MAXLEN, .flags = {.short_xfer_ok = 1,}, .callback = urndis_bulk_read_callback, .timeout = 0, /* no timeout */ .usb_mode = USB_MODE_HOST, }, [URNDIS_BULK_TX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_TX, .if_index = 0, .frames = RNDIS_TX_FRAMES_MAX, .bufsize = (RNDIS_TX_FRAMES_MAX * RNDIS_TX_MAXLEN), .flags = { .force_short_xfer = 1, }, .callback = urndis_bulk_write_callback, .timeout = 10000, /* 10 seconds */ .usb_mode = USB_MODE_HOST, }, [URNDIS_INTR_RX] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_RX, .if_index = 1, .bufsize = 0, /* use wMaxPacketSize */ .flags = {.short_xfer_ok = 1,.no_pipe_ok = 1,}, .callback = urndis_intr_read_callback, .timeout = 0, .usb_mode = USB_MODE_HOST, }, }; static device_method_t urndis_methods[] = { /* Device interface */ DEVMETHOD(device_probe, urndis_probe), DEVMETHOD(device_attach, urndis_attach), DEVMETHOD(device_detach, urndis_detach), DEVMETHOD(device_suspend, urndis_suspend), DEVMETHOD(device_resume, urndis_resume), DEVMETHOD_END }; static driver_t urndis_driver = { .name = "urndis", .methods = urndis_methods, .size = sizeof(struct urndis_softc), }; static devclass_t urndis_devclass; DRIVER_MODULE(urndis, uhub, urndis_driver, urndis_devclass, NULL, 0); MODULE_VERSION(urndis, 1); MODULE_DEPEND(urndis, uether, 1, 1, 1); MODULE_DEPEND(urndis, usb, 1, 1, 1); MODULE_DEPEND(urndis, ether, 1, 1, 1); static const struct usb_ether_methods urndis_ue_methods = { .ue_attach_post = urndis_attach_post, .ue_start = urndis_start, .ue_init = urndis_init, .ue_stop = urndis_stop, .ue_setmulti = urndis_setmulti, .ue_setpromisc = urndis_setpromisc, }; static const STRUCT_USB_HOST_ID urndis_host_devs[] = { /* Generic RNDIS class match */ {USB_IFACE_CLASS(UICLASS_WIRELESS), USB_IFACE_SUBCLASS(UISUBCLASS_RF), USB_IFACE_PROTOCOL(UIPROTO_RNDIS)}, {USB_IFACE_CLASS(UICLASS_IAD), USB_IFACE_SUBCLASS(UISUBCLASS_SYNC), USB_IFACE_PROTOCOL(UIPROTO_ACTIVESYNC)}, /* HP-WebOS */ {USB_VENDOR(USB_VENDOR_PALM), USB_IFACE_CLASS(UICLASS_CDC), USB_IFACE_SUBCLASS(UISUBCLASS_ABSTRACT_CONTROL_MODEL), USB_IFACE_PROTOCOL(0xff)}, }; static int urndis_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); return (usbd_lookup_id_by_uaa(urndis_host_devs, sizeof(urndis_host_devs), uaa)); } static void urndis_attach_post(struct usb_ether *ue) { /* no-op */ return; } static int urndis_attach(device_t dev) { struct urndis_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; struct usb_attach_arg *uaa = device_get_ivars(dev); struct usb_cdc_cm_descriptor *cmd; struct { struct urndis_set_req hdr; uint32_t filter; } msg_filter; const void *buf; uint16_t bufsz; uint8_t iface_index[2] = { uaa->info.bIfaceIndex + 1, uaa->info.bIfaceIndex }; int error; uint8_t i; sc->sc_ue.ue_udev = uaa->device; sc->sc_ifaceno_ctl = uaa->info.bIfaceNum; cmd = usbd_find_descriptor(uaa->device, NULL, uaa->info.bIfaceIndex, UDESC_CS_INTERFACE, 0xFF, UDESCSUB_CDC_CM, 0xFF); if (cmd != 0) { DPRINTF("Call Mode Descriptor found, dataif=%d\n", cmd->bDataInterface); iface_index[0] = cmd->bDataInterface; } device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF); /* scan the alternate settings looking for a valid one */ for (i = 0; i != 32; i++) { error = usbd_set_alt_interface_index(uaa->device, iface_index[0], i); if (error != 0) break; error = usbd_transfer_setup(uaa->device, iface_index, sc->sc_xfer, urndis_config, URNDIS_N_TRANSFER, sc, &sc->sc_mtx); if (error == 0) break; } if ((error != 0) || (i == 32)) { device_printf(dev, "No valid alternate " "setting found\n"); goto detach; } URNDIS_LOCK(sc); error = urndis_ctrl_query(sc, OID_802_3_PERMANENT_ADDRESS, &buf, &bufsz); URNDIS_UNLOCK(sc); if (error != (int)RNDIS_STATUS_SUCCESS) { device_printf(dev, "Unable to get hardware address\n"); goto detach; } if (bufsz != ETHER_ADDR_LEN) { device_printf(dev, "Invalid address length: %d bytes\n", bufsz); goto detach; } memcpy(&sc->sc_ue.ue_eaddr, buf, ETHER_ADDR_LEN); /* Initialize packet filter */ sc->sc_filter = RNDIS_PACKET_TYPE_BROADCAST | RNDIS_PACKET_TYPE_ALL_MULTICAST; msg_filter.filter = htole32(sc->sc_filter); URNDIS_LOCK(sc); error = urndis_ctrl_set(sc, OID_GEN_CURRENT_PACKET_FILTER, &msg_filter.hdr, sizeof(msg_filter)); URNDIS_UNLOCK(sc); if (error != (int)RNDIS_STATUS_SUCCESS) { device_printf(dev, "Unable to set data filters\n"); goto detach; } ue->ue_sc = sc; ue->ue_dev = dev; ue->ue_udev = uaa->device; ue->ue_mtx = &sc->sc_mtx; ue->ue_methods = &urndis_ue_methods; error = uether_ifattach(ue); if (error) { device_printf(dev, "Could not attach interface\n"); goto detach; } URNDIS_LOCK(sc); /* start interrupt endpoint, if any */ usbd_transfer_start(sc->sc_xfer[URNDIS_INTR_RX]); URNDIS_UNLOCK(sc); return (0); /* success */ detach: urndis_detach(dev); return (ENXIO); /* failure */ } static int urndis_detach(device_t dev) { struct urndis_softc *sc = device_get_softc(dev); struct usb_ether *ue = &sc->sc_ue; /* stop all USB transfers first */ usbd_transfer_unsetup(sc->sc_xfer, URNDIS_N_TRANSFER); uether_ifdetach(ue); mtx_destroy(&sc->sc_mtx); return (0); } static void urndis_start(struct usb_ether *ue) { struct urndis_softc *sc = uether_getsc(ue); /* * Start the USB transfers, if not already started: */ usbd_transfer_start(sc->sc_xfer[URNDIS_BULK_TX]); usbd_transfer_start(sc->sc_xfer[URNDIS_BULK_RX]); } static void urndis_init(struct usb_ether *ue) { struct urndis_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); URNDIS_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags |= IFF_DRV_RUNNING; urndis_ctrl_init(sc); /* stall data write direction, which depends on USB mode */ usbd_xfer_set_stall(sc->sc_xfer[URNDIS_BULK_TX]); /* start data transfers */ urndis_start(ue); } static void urndis_stop(struct usb_ether *ue) { struct urndis_softc *sc = uether_getsc(ue); struct ifnet *ifp = uether_getifp(ue); URNDIS_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags &= ~IFF_DRV_RUNNING; /* * stop all the transfers, if not already stopped: */ usbd_transfer_stop(sc->sc_xfer[URNDIS_BULK_RX]); usbd_transfer_stop(sc->sc_xfer[URNDIS_BULK_TX]); } static void urndis_setmulti(struct usb_ether *ue) { /* no-op */ return; } static void urndis_setpromisc(struct usb_ether *ue) { /* no-op */ return; } static int urndis_suspend(device_t dev) { device_printf(dev, "Suspending\n"); return (0); } static int urndis_resume(device_t dev) { device_printf(dev, "Resuming\n"); return (0); } static usb_error_t urndis_ctrl_msg(struct urndis_softc *sc, uint8_t rt, uint8_t r, uint16_t index, uint16_t value, void *buf, uint16_t buflen) { usb_device_request_t req; req.bmRequestType = rt; req.bRequest = r; USETW(req.wValue, value); USETW(req.wIndex, index); USETW(req.wLength, buflen); return (usbd_do_request_flags(sc->sc_ue.ue_udev, &sc->sc_mtx, &req, buf, (rt & UT_READ) ? USB_SHORT_XFER_OK : 0, NULL, 2000 /* ms */ )); } static usb_error_t urndis_ctrl_send(struct urndis_softc *sc, void *buf, uint16_t len) { usb_error_t err; err = urndis_ctrl_msg(sc, UT_WRITE_CLASS_INTERFACE, UR_GET_STATUS, sc->sc_ifaceno_ctl, 0, buf, len); DPRINTF("%s\n", usbd_errstr(err)); return (err); } static struct urndis_comp_hdr * urndis_ctrl_recv(struct urndis_softc *sc) { struct urndis_comp_hdr *hdr; usb_error_t err; err = urndis_ctrl_msg(sc, UT_READ_CLASS_INTERFACE, UR_CLEAR_FEATURE, sc->sc_ifaceno_ctl, 0, sc->sc_response_buf, RNDIS_RESPONSE_LEN); if (err != USB_ERR_NORMAL_COMPLETION) return (NULL); hdr = (struct urndis_comp_hdr *)sc->sc_response_buf; DPRINTF("type 0x%x len %u\n", le32toh(hdr->rm_type), le32toh(hdr->rm_len)); if (le32toh(hdr->rm_len) > RNDIS_RESPONSE_LEN) { DPRINTF("ctrl message error: wrong size %u > %u\n", le32toh(hdr->rm_len), RNDIS_RESPONSE_LEN); return (NULL); } return (hdr); } static uint32_t urndis_ctrl_handle(struct urndis_softc *sc, struct urndis_comp_hdr *hdr, const void **buf, uint16_t *bufsz) { uint32_t rval; DPRINTF("\n"); if (buf != NULL && bufsz != NULL) { *buf = NULL; *bufsz = 0; } switch (le32toh(hdr->rm_type)) { case REMOTE_NDIS_INITIALIZE_CMPLT: rval = urndis_ctrl_handle_init(sc, hdr); break; case REMOTE_NDIS_QUERY_CMPLT: rval = urndis_ctrl_handle_query(sc, hdr, buf, bufsz); break; case REMOTE_NDIS_RESET_CMPLT: rval = urndis_ctrl_handle_reset(sc, hdr); break; case REMOTE_NDIS_KEEPALIVE_CMPLT: case REMOTE_NDIS_SET_CMPLT: rval = le32toh(hdr->rm_status); break; default: DPRINTF("ctrl message error: unknown event 0x%x\n", le32toh(hdr->rm_type)); rval = RNDIS_STATUS_FAILURE; break; } return (rval); } static uint32_t urndis_ctrl_handle_init(struct urndis_softc *sc, const struct urndis_comp_hdr *hdr) { const struct urndis_init_comp *msg; msg = (const struct urndis_init_comp *)hdr; DPRINTF("len %u rid %u status 0x%x " "ver_major %u ver_minor %u devflags 0x%x medium 0x%x pktmaxcnt %u " "pktmaxsz %u align %u aflistoffset %u aflistsz %u\n", le32toh(msg->rm_len), le32toh(msg->rm_rid), le32toh(msg->rm_status), le32toh(msg->rm_ver_major), le32toh(msg->rm_ver_minor), le32toh(msg->rm_devflags), le32toh(msg->rm_medium), le32toh(msg->rm_pktmaxcnt), le32toh(msg->rm_pktmaxsz), le32toh(msg->rm_align), le32toh(msg->rm_aflistoffset), le32toh(msg->rm_aflistsz)); if (le32toh(msg->rm_status) != RNDIS_STATUS_SUCCESS) { DPRINTF("init failed 0x%x\n", le32toh(msg->rm_status)); return (le32toh(msg->rm_status)); } if (le32toh(msg->rm_devflags) != RNDIS_DF_CONNECTIONLESS) { DPRINTF("wrong device type (current type: 0x%x)\n", le32toh(msg->rm_devflags)); return (RNDIS_STATUS_FAILURE); } if (le32toh(msg->rm_medium) != RNDIS_MEDIUM_802_3) { DPRINTF("medium not 802.3 (current medium: 0x%x)\n", le32toh(msg->rm_medium)); return (RNDIS_STATUS_FAILURE); } sc->sc_lim_pktsz = le32toh(msg->rm_pktmaxsz); return (le32toh(msg->rm_status)); } static uint32_t urndis_ctrl_handle_query(struct urndis_softc *sc, const struct urndis_comp_hdr *hdr, const void **buf, uint16_t *bufsz) { const struct urndis_query_comp *msg; uint64_t limit; msg = (const struct urndis_query_comp *)hdr; DPRINTF("len %u rid %u status 0x%x " "buflen %u bufoff %u\n", le32toh(msg->rm_len), le32toh(msg->rm_rid), le32toh(msg->rm_status), le32toh(msg->rm_infobuflen), le32toh(msg->rm_infobufoffset)); if (buf != NULL && bufsz != NULL) { *buf = NULL; *bufsz = 0; } if (le32toh(msg->rm_status) != RNDIS_STATUS_SUCCESS) { DPRINTF("query failed 0x%x\n", le32toh(msg->rm_status)); return (le32toh(msg->rm_status)); } limit = le32toh(msg->rm_infobuflen); limit += le32toh(msg->rm_infobufoffset); limit += RNDIS_HEADER_OFFSET; if (limit > (uint64_t)le32toh(msg->rm_len)) { DPRINTF("ctrl message error: invalid query info " "len/offset/end_position(%u/%u/%u) -> " "go out of buffer limit %u\n", le32toh(msg->rm_infobuflen), le32toh(msg->rm_infobufoffset), le32toh(msg->rm_infobuflen) + le32toh(msg->rm_infobufoffset) + RNDIS_HEADER_OFFSET, le32toh(msg->rm_len)); return (RNDIS_STATUS_FAILURE); } if (buf != NULL && bufsz != NULL) { *buf = ((const uint8_t *)msg) + RNDIS_HEADER_OFFSET + le32toh(msg->rm_infobufoffset); *bufsz = le32toh(msg->rm_infobuflen); } return (le32toh(msg->rm_status)); } static uint32_t urndis_ctrl_handle_reset(struct urndis_softc *sc, const struct urndis_comp_hdr *hdr) { const struct urndis_reset_comp *msg; uint32_t rval; msg = (const struct urndis_reset_comp *)hdr; rval = le32toh(msg->rm_status); DPRINTF("len %u status 0x%x " "adrreset %u\n", le32toh(msg->rm_len), rval, le32toh(msg->rm_adrreset)); if (rval != RNDIS_STATUS_SUCCESS) { DPRINTF("reset failed 0x%x\n", rval); return (rval); } if (msg->rm_adrreset != 0) { struct { struct urndis_set_req hdr; uint32_t filter; } msg_filter; msg_filter.filter = htole32(sc->sc_filter); rval = urndis_ctrl_set(sc, OID_GEN_CURRENT_PACKET_FILTER, &msg_filter.hdr, sizeof(msg_filter)); if (rval != RNDIS_STATUS_SUCCESS) { DPRINTF("unable to reset data filters\n"); return (rval); } } return (rval); } static uint32_t urndis_ctrl_init(struct urndis_softc *sc) { struct urndis_init_req msg; struct urndis_comp_hdr *hdr; uint32_t rval; msg.rm_type = htole32(REMOTE_NDIS_INITIALIZE_MSG); msg.rm_len = htole32(sizeof(msg)); msg.rm_rid = htole32(0); msg.rm_ver_major = htole32(1); msg.rm_ver_minor = htole32(1); msg.rm_max_xfersz = htole32(RNDIS_RX_MAXLEN); DPRINTF("type %u len %u rid %u ver_major %u " "ver_minor %u max_xfersz %u\n", le32toh(msg.rm_type), le32toh(msg.rm_len), le32toh(msg.rm_rid), le32toh(msg.rm_ver_major), le32toh(msg.rm_ver_minor), le32toh(msg.rm_max_xfersz)); rval = urndis_ctrl_send(sc, &msg, sizeof(msg)); if (rval != RNDIS_STATUS_SUCCESS) { DPRINTF("init failed\n"); return (rval); } if ((hdr = urndis_ctrl_recv(sc)) == NULL) { DPRINTF("unable to get init response\n"); return (RNDIS_STATUS_FAILURE); } rval = urndis_ctrl_handle(sc, hdr, NULL, NULL); return (rval); } #if 0 static uint32_t urndis_ctrl_halt(struct urndis_softc *sc) { struct urndis_halt_req msg; uint32_t rval; msg.rm_type = htole32(REMOTE_NDIS_HALT_MSG); msg.rm_len = htole32(sizeof(msg)); msg.rm_rid = 0; DPRINTF("type %u len %u rid %u\n", le32toh(msg.rm_type), le32toh(msg.rm_len), le32toh(msg.rm_rid)); rval = urndis_ctrl_send(sc, &msg, sizeof(msg)); if (rval != RNDIS_STATUS_SUCCESS) printf("halt failed\n"); return (rval); } #endif static uint32_t urndis_ctrl_query(struct urndis_softc *sc, uint32_t oid, const void **rbuf, uint16_t *rbufsz) { struct urndis_query_req msg; uint32_t rval; struct urndis_comp_hdr *hdr; msg.rm_type = htole32(REMOTE_NDIS_QUERY_MSG); msg.rm_len = htole32(sizeof(msg)); msg.rm_rid = 0; /* XXX */ msg.rm_oid = htole32(oid); msg.rm_infobuflen = htole32(0); msg.rm_infobufoffset = 0; msg.rm_devicevchdl = 0; DPRINTF("type %u len %u rid %u oid 0x%x " "infobuflen %u infobufoffset %u devicevchdl %u\n", le32toh(msg.rm_type), le32toh(msg.rm_len), le32toh(msg.rm_rid), le32toh(msg.rm_oid), le32toh(msg.rm_infobuflen), le32toh(msg.rm_infobufoffset), le32toh(msg.rm_devicevchdl)); rval = urndis_ctrl_send(sc, &msg, sizeof(msg)); if (rval != RNDIS_STATUS_SUCCESS) { DPRINTF("query failed\n"); return (rval); } if ((hdr = urndis_ctrl_recv(sc)) == NULL) { DPRINTF("unable to get query response\n"); return (RNDIS_STATUS_FAILURE); } rval = urndis_ctrl_handle(sc, hdr, rbuf, rbufsz); return (rval); } static uint32_t urndis_ctrl_set(struct urndis_softc *sc, uint32_t oid, struct urndis_set_req *msg, uint16_t len) { struct urndis_comp_hdr *hdr; uint32_t rval; uint32_t datalen = len - sizeof(*msg); msg->rm_type = htole32(REMOTE_NDIS_SET_MSG); msg->rm_len = htole32(len); msg->rm_rid = 0; /* XXX */ msg->rm_oid = htole32(oid); msg->rm_infobuflen = htole32(datalen); if (datalen != 0) { msg->rm_infobufoffset = htole32(sizeof(*msg) - RNDIS_HEADER_OFFSET); } else { msg->rm_infobufoffset = 0; } msg->rm_devicevchdl = 0; DPRINTF("type %u len %u rid %u oid 0x%x " "infobuflen %u infobufoffset %u devicevchdl %u\n", le32toh(msg->rm_type), le32toh(msg->rm_len), le32toh(msg->rm_rid), le32toh(msg->rm_oid), le32toh(msg->rm_infobuflen), le32toh(msg->rm_infobufoffset), le32toh(msg->rm_devicevchdl)); rval = urndis_ctrl_send(sc, msg, len); if (rval != RNDIS_STATUS_SUCCESS) { DPRINTF("set failed\n"); return (rval); } if ((hdr = urndis_ctrl_recv(sc)) == NULL) { DPRINTF("unable to get set response\n"); return (RNDIS_STATUS_FAILURE); } rval = urndis_ctrl_handle(sc, hdr, NULL, NULL); if (rval != RNDIS_STATUS_SUCCESS) DPRINTF("set failed 0x%x\n", rval); return (rval); } static void urndis_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct urndis_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc = usbd_xfer_get_frame(xfer, 0); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct urndis_packet_msg msg; struct mbuf *m; int actlen; int aframes; int offset; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL); DPRINTFN(1, "received %u bytes in %u frames\n", actlen, aframes); for (offset = 0; actlen >= (uint32_t)sizeof(msg);) { /* copy out header */ usbd_copy_out(pc, offset, &msg, sizeof(msg)); if (le32toh(0x1234567U) != 0x1234567U) { /* swap endianness */ msg.rm_type = le32toh(msg.rm_type); msg.rm_len = le32toh(msg.rm_len); msg.rm_dataoffset = le32toh(msg.rm_dataoffset); msg.rm_datalen = le32toh(msg.rm_datalen); msg.rm_oobdataoffset = le32toh(msg.rm_oobdataoffset); msg.rm_oobdatalen = le32toh(msg.rm_oobdatalen); msg.rm_oobdataelements = le32toh(msg.rm_oobdataelements); msg.rm_pktinfooffset = le32toh(msg.rm_pktinfooffset); msg.rm_pktinfolen = le32toh(msg.rm_pktinfolen); msg.rm_vchandle = le32toh(msg.rm_vchandle); msg.rm_reserved = le32toh(msg.rm_reserved); } DPRINTF("len %u data(off:%u len:%u) " "oobdata(off:%u len:%u nb:%u) perpacket(off:%u len:%u)\n", msg.rm_len, msg.rm_dataoffset, msg.rm_datalen, msg.rm_oobdataoffset, msg.rm_oobdatalen, msg.rm_oobdataelements, msg.rm_pktinfooffset, msg.rm_pktinfooffset); /* sanity check the RNDIS header */ if (msg.rm_type != REMOTE_NDIS_PACKET_MSG) { DPRINTF("invalid type 0x%x != 0x%x\n", msg.rm_type, REMOTE_NDIS_PACKET_MSG); goto tr_setup; } else if (msg.rm_len < (uint32_t)sizeof(msg)) { DPRINTF("invalid msg len %u < %u\n", msg.rm_len, (unsigned)sizeof(msg)); goto tr_setup; } else if (msg.rm_len > (uint32_t)actlen) { DPRINTF("invalid msg len %u > buffer " "len %u\n", msg.rm_len, actlen); goto tr_setup; } else if (msg.rm_dataoffset >= (uint32_t)actlen) { DPRINTF("invalid msg dataoffset %u > buffer " "dataoffset %u\n", msg.rm_dataoffset, actlen); goto tr_setup; } else if (msg.rm_datalen > (uint32_t)actlen) { DPRINTF("invalid msg datalen %u > buffer " "datalen %u\n", msg.rm_datalen, actlen); goto tr_setup; } else if ((msg.rm_dataoffset + msg.rm_datalen + (uint32_t)__offsetof(struct urndis_packet_msg, rm_dataoffset)) > (uint32_t)actlen) { DPRINTF("invalid dataoffset %u larger than %u\n", msg.rm_dataoffset + msg.rm_datalen + (uint32_t)__offsetof(struct urndis_packet_msg, rm_dataoffset), actlen); goto tr_setup; } else if (msg.rm_datalen < (uint32_t)sizeof(struct ether_header)) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); DPRINTF("invalid ethernet size " "%u < %u\n", msg.rm_datalen, (unsigned)sizeof(struct ether_header)); goto tr_setup; } else if (msg.rm_datalen > (uint32_t)MCLBYTES) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); DPRINTF("invalid ethernet size " "%u > %u\n", msg.rm_datalen, (unsigned)MCLBYTES); goto tr_setup; } else if (msg.rm_datalen > (uint32_t)(MHLEN - ETHER_ALIGN)) { m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); } else { m = m_gethdr(M_NOWAIT, MT_DATA); } /* check if we have a buffer */ if (m != NULL) { m_adj(m, ETHER_ALIGN); usbd_copy_out(pc, offset + msg.rm_dataoffset + __offsetof(struct urndis_packet_msg, rm_dataoffset), m->m_data, msg.rm_datalen); /* enqueue */ uether_rxmbuf(&sc->sc_ue, m, msg.rm_datalen); } else { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); } offset += msg.rm_len; actlen -= msg.rm_len; } case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, RNDIS_RX_MAXLEN); usbd_xfer_set_frames(xfer, 1); usbd_transfer_submit(xfer); uether_rxflush(&sc->sc_ue); /* must be last */ break; default: /* Error */ DPRINTFN(1, "error = %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); usbd_xfer_set_frames(xfer, 0); usbd_transfer_submit(xfer); } break; } } static void urndis_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct urndis_packet_msg msg; struct urndis_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = uether_getifp(&sc->sc_ue); struct mbuf *m; unsigned x; int actlen; int aframes; usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL); DPRINTFN(1, "\n"); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(11, "%u bytes in %u frames\n", actlen, aframes); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: memset(&msg, 0, sizeof(msg)); for (x = 0; x != RNDIS_TX_FRAMES_MAX; x++) { struct usb_page_cache *pc = usbd_xfer_get_frame(xfer, x); usbd_xfer_set_frame_offset(xfer, x * RNDIS_TX_MAXLEN, x); next_pkt: IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; if ((m->m_pkthdr.len + sizeof(msg)) > RNDIS_TX_MAXLEN) { DPRINTF("Too big packet\n"); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); /* Free buffer */ m_freem(m); goto next_pkt; } msg.rm_type = htole32(REMOTE_NDIS_PACKET_MSG); msg.rm_len = htole32(sizeof(msg) + m->m_pkthdr.len); msg.rm_dataoffset = htole32(RNDIS_DATA_OFFSET); msg.rm_datalen = htole32(m->m_pkthdr.len); /* copy in all data */ usbd_copy_in(pc, 0, &msg, sizeof(msg)); usbd_m_copy_in(pc, sizeof(msg), m, 0, m->m_pkthdr.len); usbd_xfer_set_frame_len(xfer, x, sizeof(msg) + m->m_pkthdr.len); /* * If there's a BPF listener, bounce a copy of * this frame to him: */ BPF_MTAP(ifp, m); /* Free buffer */ m_freem(m); } if (x != 0) { usbd_xfer_set_frames(xfer, x); usbd_transfer_submit(xfer); } break; default: /* Error */ DPRINTFN(11, "transfer error, %s\n", usbd_errstr(error)); /* count output errors */ if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void urndis_intr_read_callback(struct usb_xfer *xfer, usb_error_t error) { int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTF("Received %d bytes\n", actlen); /* TODO: decode some indications */ /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* start clear stall */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } Index: head/sys/dev/usb/net/if_usie.c =================================================================== --- head/sys/dev/usb/net/if_usie.c (revision 276700) +++ head/sys/dev/usb/net/if_usie.c (revision 276701) @@ -1,1614 +1,1614 @@ /*- * Copyright (c) 2011 Anybots Inc * written by Akinori Furukoshi * - ucom part is based on u3g.c * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #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 #include #include "usbdevs.h" #define USB_DEBUG_VAR usie_debug #include #include #include #include #include #ifdef USB_DEBUG static int usie_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, usie, CTLFLAG_RW, 0, "sierra USB modem"); -SYSCTL_INT(_hw_usb_usie, OID_AUTO, debug, CTLFLAG_RW, &usie_debug, 0, +SYSCTL_INT(_hw_usb_usie, OID_AUTO, debug, CTLFLAG_RWTUN, &usie_debug, 0, "usie debug level"); #endif /* Sierra Wireless Direct IP modems */ static const STRUCT_USB_HOST_ID usie_devs[] = { #define USIE_DEV(v, d) { \ USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##d) } USIE_DEV(SIERRA, MC8700), USIE_DEV(SIERRA, TRUINSTALL), USIE_DEV(AIRPRIME, USB308), #undef USIE_DEV }; static device_probe_t usie_probe; static device_attach_t usie_attach; static device_detach_t usie_detach; static void usie_free_softc(struct usie_softc *); static void usie_free(struct ucom_softc *); static void usie_uc_update_line_state(struct ucom_softc *, uint8_t); static void usie_uc_cfg_get_status(struct ucom_softc *, uint8_t *, uint8_t *); static void usie_uc_cfg_set_dtr(struct ucom_softc *, uint8_t); static void usie_uc_cfg_set_rts(struct ucom_softc *, uint8_t); static void usie_uc_cfg_open(struct ucom_softc *); static void usie_uc_cfg_close(struct ucom_softc *); static void usie_uc_start_read(struct ucom_softc *); static void usie_uc_stop_read(struct ucom_softc *); static void usie_uc_start_write(struct ucom_softc *); static void usie_uc_stop_write(struct ucom_softc *); static usb_callback_t usie_uc_tx_callback; static usb_callback_t usie_uc_rx_callback; static usb_callback_t usie_uc_status_callback; static usb_callback_t usie_if_tx_callback; static usb_callback_t usie_if_rx_callback; static usb_callback_t usie_if_status_callback; static void usie_if_sync_to(void *); static void usie_if_sync_cb(void *, int); static void usie_if_status_cb(void *, int); static void usie_if_start(struct ifnet *); static int usie_if_output(struct ifnet *, struct mbuf *, const struct sockaddr *, struct route *); static void usie_if_init(void *); static void usie_if_stop(struct usie_softc *); static int usie_if_ioctl(struct ifnet *, u_long, caddr_t); static int usie_do_request(struct usie_softc *, struct usb_device_request *, void *); static int usie_if_cmd(struct usie_softc *, uint8_t); static void usie_cns_req(struct usie_softc *, uint32_t, uint16_t); static void usie_cns_rsp(struct usie_softc *, struct usie_cns *); static void usie_hip_rsp(struct usie_softc *, uint8_t *, uint32_t); static int usie_driver_loaded(struct module *, int, void *); static const struct usb_config usie_uc_config[USIE_UC_N_XFER] = { [USIE_UC_STATUS] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = 0, /* use wMaxPacketSize */ .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &usie_uc_status_callback, }, [USIE_UC_RX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = USIE_BUFSIZE, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,.proxy_buffer = 1,}, .callback = &usie_uc_rx_callback, }, [USIE_UC_TX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = USIE_BUFSIZE, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = &usie_uc_tx_callback, } }; static const struct usb_config usie_if_config[USIE_IF_N_XFER] = { [USIE_IF_STATUS] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = 0, /* use wMaxPacketSize */ .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &usie_if_status_callback, }, [USIE_IF_RX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = USIE_BUFSIZE, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &usie_if_rx_callback, }, [USIE_IF_TX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = MAX(USIE_BUFSIZE, MCLBYTES), .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = &usie_if_tx_callback, } }; static device_method_t usie_methods[] = { DEVMETHOD(device_probe, usie_probe), DEVMETHOD(device_attach, usie_attach), DEVMETHOD(device_detach, usie_detach), DEVMETHOD_END }; static driver_t usie_driver = { .name = "usie", .methods = usie_methods, .size = sizeof(struct usie_softc), }; static devclass_t usie_devclass; static eventhandler_tag usie_etag; DRIVER_MODULE(usie, uhub, usie_driver, usie_devclass, usie_driver_loaded, 0); MODULE_DEPEND(usie, ucom, 1, 1, 1); MODULE_DEPEND(usie, usb, 1, 1, 1); MODULE_VERSION(usie, 1); static const struct ucom_callback usie_uc_callback = { .ucom_cfg_get_status = &usie_uc_cfg_get_status, .ucom_cfg_set_dtr = &usie_uc_cfg_set_dtr, .ucom_cfg_set_rts = &usie_uc_cfg_set_rts, .ucom_cfg_open = &usie_uc_cfg_open, .ucom_cfg_close = &usie_uc_cfg_close, .ucom_start_read = &usie_uc_start_read, .ucom_stop_read = &usie_uc_stop_read, .ucom_start_write = &usie_uc_start_write, .ucom_stop_write = &usie_uc_stop_write, .ucom_free = &usie_free, }; static void usie_autoinst(void *arg, struct usb_device *udev, struct usb_attach_arg *uaa) { struct usb_interface *iface; struct usb_interface_descriptor *id; struct usb_device_request req; int err; if (uaa->dev_state != UAA_DEV_READY) return; iface = usbd_get_iface(udev, 0); if (iface == NULL) return; id = iface->idesc; if (id == NULL || id->bInterfaceClass != UICLASS_MASS) return; if (usbd_lookup_id_by_uaa(usie_devs, sizeof(usie_devs), uaa) != 0) return; /* no device match */ if (bootverbose) { DPRINTF("Ejecting %s %s\n", usb_get_manufacturer(udev), usb_get_product(udev)); } req.bmRequestType = UT_VENDOR; req.bRequest = UR_SET_INTERFACE; USETW(req.wValue, UF_DEVICE_REMOTE_WAKEUP); USETW(req.wIndex, UHF_PORT_CONNECTION); USETW(req.wLength, 0); /* at this moment there is no mutex */ err = usbd_do_request_flags(udev, NULL, &req, NULL, 0, NULL, 250 /* ms */ ); /* success, mark the udev as disappearing */ if (err == 0) uaa->dev_state = UAA_DEV_EJECTING; } static int usie_probe(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != USIE_CNFG_INDEX) return (ENXIO); if (uaa->info.bIfaceIndex != USIE_IFACE_INDEX) return (ENXIO); if (uaa->info.bInterfaceClass != UICLASS_VENDOR) return (ENXIO); return (usbd_lookup_id_by_uaa(usie_devs, sizeof(usie_devs), uaa)); } static int usie_attach(device_t self) { struct usie_softc *sc = device_get_softc(self); struct usb_attach_arg *uaa = device_get_ivars(self); struct ifnet *ifp; struct usb_interface *iface; struct usb_interface_descriptor *id; struct usb_device_request req; int err; uint16_t fwattr; uint8_t iface_index; uint8_t ifidx; uint8_t start; device_set_usb_desc(self); sc->sc_udev = uaa->device; sc->sc_dev = self; mtx_init(&sc->sc_mtx, "usie", MTX_NETWORK_LOCK, MTX_DEF); ucom_ref(&sc->sc_super_ucom); TASK_INIT(&sc->sc_if_status_task, 0, usie_if_status_cb, sc); TASK_INIT(&sc->sc_if_sync_task, 0, usie_if_sync_cb, sc); usb_callout_init_mtx(&sc->sc_if_sync_ch, &sc->sc_mtx, 0); mtx_lock(&sc->sc_mtx); /* set power mode to D0 */ req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = USIE_POWER; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, 0); if (usie_do_request(sc, &req, NULL)) { mtx_unlock(&sc->sc_mtx); goto detach; } /* read fw attr */ fwattr = 0; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = USIE_FW_ATTR; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, sizeof(fwattr)); if (usie_do_request(sc, &req, &fwattr)) { mtx_unlock(&sc->sc_mtx); goto detach; } mtx_unlock(&sc->sc_mtx); /* check DHCP supports */ DPRINTF("fwattr=%x\n", fwattr); if (!(fwattr & USIE_FW_DHCP)) { device_printf(self, "DHCP is not supported. A firmware upgrade might be needed.\n"); } /* find available interfaces */ sc->sc_nucom = 0; for (ifidx = 0; ifidx < USIE_IFACE_MAX; ifidx++) { iface = usbd_get_iface(uaa->device, ifidx); if (iface == NULL) break; id = usbd_get_interface_descriptor(iface); if ((id == NULL) || (id->bInterfaceClass != UICLASS_VENDOR)) continue; /* setup Direct IP transfer */ if (id->bInterfaceNumber >= 7 && id->bNumEndpoints == 3) { sc->sc_if_ifnum = id->bInterfaceNumber; iface_index = ifidx; DPRINTF("ifnum=%d, ifidx=%d\n", sc->sc_if_ifnum, ifidx); err = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_if_xfer, usie_if_config, USIE_IF_N_XFER, sc, &sc->sc_mtx); if (err == 0) continue; device_printf(self, "could not allocate USB transfers on " "iface_index=%d, err=%s\n", iface_index, usbd_errstr(err)); goto detach; } /* setup ucom */ if (sc->sc_nucom >= USIE_UCOM_MAX) continue; usbd_set_parent_iface(uaa->device, ifidx, uaa->info.bIfaceIndex); DPRINTF("NumEndpoints=%d bInterfaceNumber=%d\n", id->bNumEndpoints, id->bInterfaceNumber); if (id->bNumEndpoints == 2) { sc->sc_uc_xfer[sc->sc_nucom][0] = NULL; start = 1; } else start = 0; err = usbd_transfer_setup(uaa->device, &ifidx, sc->sc_uc_xfer[sc->sc_nucom] + start, usie_uc_config + start, USIE_UC_N_XFER - start, &sc->sc_ucom[sc->sc_nucom], &sc->sc_mtx); if (err != 0) { DPRINTF("usbd_transfer_setup error=%s\n", usbd_errstr(err)); continue; } mtx_lock(&sc->sc_mtx); for (; start < USIE_UC_N_XFER; start++) usbd_xfer_set_stall(sc->sc_uc_xfer[sc->sc_nucom][start]); mtx_unlock(&sc->sc_mtx); sc->sc_uc_ifnum[sc->sc_nucom] = id->bInterfaceNumber; sc->sc_nucom++; /* found a port */ } if (sc->sc_nucom == 0) { device_printf(self, "no comports found\n"); goto detach; } err = ucom_attach(&sc->sc_super_ucom, sc->sc_ucom, sc->sc_nucom, sc, &usie_uc_callback, &sc->sc_mtx); if (err != 0) { DPRINTF("ucom_attach failed\n"); goto detach; } DPRINTF("Found %d interfaces.\n", sc->sc_nucom); /* setup ifnet (Direct IP) */ sc->sc_ifp = ifp = if_alloc(IFT_OTHER); if (ifp == NULL) { device_printf(self, "Could not allocate a network interface\n"); goto detach; } if_initname(ifp, "usie", device_get_unit(self)); ifp->if_softc = sc; ifp->if_mtu = USIE_MTU_MAX; ifp->if_flags |= IFF_NOARP; ifp->if_init = usie_if_init; ifp->if_ioctl = usie_if_ioctl; ifp->if_start = usie_if_start; ifp->if_output = usie_if_output; IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen); ifp->if_snd.ifq_drv_maxlen = ifqmaxlen; IFQ_SET_READY(&ifp->if_snd); if_attach(ifp); bpfattach(ifp, DLT_RAW, 0); if (fwattr & USIE_PM_AUTO) { usbd_set_power_mode(uaa->device, USB_POWER_MODE_SAVE); DPRINTF("enabling automatic suspend and resume\n"); } else { usbd_set_power_mode(uaa->device, USB_POWER_MODE_ON); DPRINTF("USB power is always ON\n"); } DPRINTF("device attached\n"); return (0); detach: usie_detach(self); return (ENOMEM); } static int usie_detach(device_t self) { struct usie_softc *sc = device_get_softc(self); uint8_t x; /* detach ifnet */ if (sc->sc_ifp != NULL) { usie_if_stop(sc); usbd_transfer_unsetup(sc->sc_if_xfer, USIE_IF_N_XFER); bpfdetach(sc->sc_ifp); if_detach(sc->sc_ifp); if_free(sc->sc_ifp); sc->sc_ifp = NULL; } /* detach ucom */ if (sc->sc_nucom > 0) ucom_detach(&sc->sc_super_ucom, sc->sc_ucom); /* stop all USB transfers */ usbd_transfer_unsetup(sc->sc_if_xfer, USIE_IF_N_XFER); for (x = 0; x != USIE_UCOM_MAX; x++) usbd_transfer_unsetup(sc->sc_uc_xfer[x], USIE_UC_N_XFER); device_claim_softc(self); usie_free_softc(sc); return (0); } UCOM_UNLOAD_DRAIN(usie); static void usie_free_softc(struct usie_softc *sc) { if (ucom_unref(&sc->sc_super_ucom)) { mtx_destroy(&sc->sc_mtx); device_free_softc(sc); } } static void usie_free(struct ucom_softc *ucom) { usie_free_softc(ucom->sc_parent); } static void usie_uc_update_line_state(struct ucom_softc *ucom, uint8_t ls) { struct usie_softc *sc = ucom->sc_parent; struct usb_device_request req; if (sc->sc_uc_xfer[ucom->sc_subunit][USIE_UC_STATUS] == NULL) return; req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = USIE_LINK_STATE; USETW(req.wValue, ls); USETW(req.wIndex, sc->sc_uc_ifnum[ucom->sc_subunit]); USETW(req.wLength, 0); DPRINTF("sc_uc_ifnum=%d\n", sc->sc_uc_ifnum[ucom->sc_subunit]); usie_do_request(sc, &req, NULL); } static void usie_uc_cfg_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr) { struct usie_softc *sc = ucom->sc_parent; *msr = sc->sc_msr; *lsr = sc->sc_lsr; } static void usie_uc_cfg_set_dtr(struct ucom_softc *ucom, uint8_t flag) { uint8_t dtr; dtr = flag ? USIE_LS_DTR : 0; usie_uc_update_line_state(ucom, dtr); } static void usie_uc_cfg_set_rts(struct ucom_softc *ucom, uint8_t flag) { uint8_t rts; rts = flag ? USIE_LS_RTS : 0; usie_uc_update_line_state(ucom, rts); } static void usie_uc_cfg_open(struct ucom_softc *ucom) { struct usie_softc *sc = ucom->sc_parent; /* usbd_transfer_start() is NULL safe */ usbd_transfer_start(sc->sc_uc_xfer[ucom->sc_subunit][USIE_UC_STATUS]); } static void usie_uc_cfg_close(struct ucom_softc *ucom) { struct usie_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_uc_xfer[ucom->sc_subunit][USIE_UC_STATUS]); } static void usie_uc_start_read(struct ucom_softc *ucom) { struct usie_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_uc_xfer[ucom->sc_subunit][USIE_UC_RX]); } static void usie_uc_stop_read(struct ucom_softc *ucom) { struct usie_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_uc_xfer[ucom->sc_subunit][USIE_UC_RX]); } static void usie_uc_start_write(struct ucom_softc *ucom) { struct usie_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_uc_xfer[ucom->sc_subunit][USIE_UC_TX]); } static void usie_uc_stop_write(struct ucom_softc *ucom) { struct usie_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_uc_xfer[ucom->sc_subunit][USIE_UC_TX]); } static void usie_uc_rx_callback(struct usb_xfer *xfer, usb_error_t error) { struct ucom_softc *ucom = usbd_xfer_softc(xfer); struct usie_softc *sc = ucom->sc_parent; struct usb_page_cache *pc; uint32_t actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); /* handle CnS response */ if (ucom == sc->sc_ucom && actlen >= USIE_HIPCNS_MIN) { DPRINTF("transferred=%u\n", actlen); /* check if it is really CnS reply */ usbd_copy_out(pc, 0, sc->sc_resp_temp, 1); if (sc->sc_resp_temp[0] == USIE_HIP_FRM_CHR) { /* verify actlen */ if (actlen > USIE_BUFSIZE) actlen = USIE_BUFSIZE; /* get complete message */ usbd_copy_out(pc, 0, sc->sc_resp_temp, actlen); usie_hip_rsp(sc, sc->sc_resp_temp, actlen); /* need to fall though */ goto tr_setup; } /* else call ucom_put_data() */ } /* standard ucom transfer */ ucom_put_data(ucom, pc, 0, actlen); /* fall though */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: /* Error */ if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void usie_uc_tx_callback(struct usb_xfer *xfer, usb_error_t error) { struct ucom_softc *ucom = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint32_t actlen; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: case USB_ST_SETUP: tr_setup: pc = usbd_xfer_get_frame(xfer, 0); /* handle CnS request */ struct mbuf *m = usbd_xfer_get_priv(xfer); if (m != NULL) { usbd_m_copy_in(pc, 0, m, 0, m->m_pkthdr.len); usbd_xfer_set_frame_len(xfer, 0, m->m_pkthdr.len); usbd_xfer_set_priv(xfer, NULL); usbd_transfer_submit(xfer); m_freem(m); break; } /* standard ucom transfer */ if (ucom_get_data(ucom, pc, 0, USIE_BUFSIZE, &actlen)) { usbd_xfer_set_frame_len(xfer, 0, actlen); usbd_transfer_submit(xfer); } break; default: /* Error */ if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void usie_uc_status_callback(struct usb_xfer *xfer, usb_error_t error) { struct usb_page_cache *pc; struct { struct usb_device_request req; uint16_t param; } st; uint32_t actlen; uint16_t param; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(4, "info received, actlen=%u\n", actlen); if (actlen < sizeof(st)) { DPRINTF("data too short actlen=%u\n", actlen); goto tr_setup; } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, &st, sizeof(st)); if (st.req.bmRequestType == 0xa1 && st.req.bRequest == 0x20) { struct ucom_softc *ucom = usbd_xfer_softc(xfer); struct usie_softc *sc = ucom->sc_parent; param = le16toh(st.param); DPRINTF("param=%x\n", param); sc->sc_msr = sc->sc_lsr = 0; sc->sc_msr |= (param & USIE_DCD) ? SER_DCD : 0; sc->sc_msr |= (param & USIE_DSR) ? SER_DSR : 0; sc->sc_msr |= (param & USIE_RI) ? SER_RI : 0; sc->sc_msr |= (param & USIE_CTS) ? 0 : SER_CTS; sc->sc_msr |= (param & USIE_RTS) ? SER_RTS : 0; sc->sc_msr |= (param & USIE_DTR) ? SER_DTR : 0; } /* fall though */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: /* Error */ DPRINTF("USB transfer error, %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void usie_if_rx_callback(struct usb_xfer *xfer, usb_error_t error) { struct usie_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct mbuf *m0; struct mbuf *m = NULL; struct usie_desc *rxd; uint32_t actlen; uint16_t err; uint16_t pkt; uint16_t ipl; uint16_t len; uint16_t diff; uint8_t pad; uint8_t ipv; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(15, "rx done, actlen=%u\n", actlen); if (actlen < sizeof(struct usie_hip)) { DPRINTF("data too short %u\n", actlen); goto tr_setup; } m = sc->sc_rxm; sc->sc_rxm = NULL; /* fall though */ case USB_ST_SETUP: tr_setup: if (sc->sc_rxm == NULL) { sc->sc_rxm = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE /* could be bigger than MCLBYTES */ ); } if (sc->sc_rxm == NULL) { DPRINTF("could not allocate Rx mbuf\n"); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); usbd_xfer_set_stall(xfer); usbd_xfer_set_frames(xfer, 0); } else { /* * Directly loading a mbuf cluster into DMA to * save some data copying. This works because * there is only one cluster. */ usbd_xfer_set_frame_data(xfer, 0, mtod(sc->sc_rxm, caddr_t), MIN(MJUMPAGESIZE, USIE_RXSZ_MAX)); usbd_xfer_set_frames(xfer, 1); } usbd_transfer_submit(xfer); break; default: /* Error */ DPRINTF("USB transfer error, %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } if (sc->sc_rxm != NULL) { m_freem(sc->sc_rxm); sc->sc_rxm = NULL; } break; } if (m == NULL) return; mtx_unlock(&sc->sc_mtx); m->m_pkthdr.len = m->m_len = actlen; err = pkt = 0; /* HW can aggregate multiple frames in a single USB xfer */ for (;;) { rxd = mtod(m, struct usie_desc *); len = be16toh(rxd->hip.len) & USIE_HIP_IP_LEN_MASK; pad = (rxd->hip.id & USIE_HIP_PAD) ? 1 : 0; ipl = (len - pad - ETHER_HDR_LEN); if (ipl >= len) { DPRINTF("Corrupt frame\n"); m_freem(m); break; } diff = sizeof(struct usie_desc) + ipl + pad; if (((rxd->hip.id & USIE_HIP_MASK) != USIE_HIP_IP) || (be16toh(rxd->desc_type) & USIE_TYPE_MASK) != USIE_IP_RX) { DPRINTF("received wrong type of packet\n"); m->m_data += diff; m->m_pkthdr.len = (m->m_len -= diff); err++; if (m->m_pkthdr.len > 0) continue; m_freem(m); break; } switch (be16toh(rxd->ethhdr.ether_type)) { case ETHERTYPE_IP: ipv = NETISR_IP; break; #ifdef INET6 case ETHERTYPE_IPV6: ipv = NETISR_IPV6; break; #endif default: DPRINTF("unsupported ether type\n"); err++; break; } /* the last packet */ if (m->m_pkthdr.len <= diff) { m->m_data += (sizeof(struct usie_desc) + pad); m->m_pkthdr.len = m->m_len = ipl; m->m_pkthdr.rcvif = ifp; BPF_MTAP(sc->sc_ifp, m); netisr_dispatch(ipv, m); break; } /* copy aggregated frames to another mbuf */ m0 = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); if (__predict_false(m0 == NULL)) { DPRINTF("could not allocate mbuf\n"); err++; m_freem(m); break; } m_copydata(m, sizeof(struct usie_desc) + pad, ipl, mtod(m0, caddr_t)); m0->m_pkthdr.rcvif = ifp; m0->m_pkthdr.len = m0->m_len = ipl; BPF_MTAP(sc->sc_ifp, m0); netisr_dispatch(ipv, m0); m->m_data += diff; m->m_pkthdr.len = (m->m_len -= diff); } mtx_lock(&sc->sc_mtx); if_inc_counter(ifp, IFCOUNTER_IERRORS, err); if_inc_counter(ifp, IFCOUNTER_IPACKETS, pkt); } static void usie_if_tx_callback(struct usb_xfer *xfer, usb_error_t error) { struct usie_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; struct ifnet *ifp = sc->sc_ifp; struct mbuf *m; uint16_t size; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(11, "transfer complete\n"); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* fall though */ case USB_ST_SETUP: tr_setup: if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) break; IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; if (m->m_pkthdr.len > (int)(MCLBYTES - ETHER_HDR_LEN + ETHER_CRC_LEN - sizeof(sc->sc_txd))) { DPRINTF("packet len is too big: %d\n", m->m_pkthdr.len); break; } pc = usbd_xfer_get_frame(xfer, 0); sc->sc_txd.hip.len = htobe16(m->m_pkthdr.len + ETHER_HDR_LEN + ETHER_CRC_LEN); size = sizeof(sc->sc_txd); usbd_copy_in(pc, 0, &sc->sc_txd, size); usbd_m_copy_in(pc, size, m, 0, m->m_pkthdr.len); usbd_xfer_set_frame_len(xfer, 0, m->m_pkthdr.len + size + ETHER_CRC_LEN); BPF_MTAP(ifp, m); m_freem(m); usbd_transfer_submit(xfer); break; default: /* Error */ DPRINTF("USB transfer error, %s\n", usbd_errstr(error)); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } break; } } static void usie_if_status_callback(struct usb_xfer *xfer, usb_error_t error) { struct usie_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; struct usb_cdc_notification cdc; uint32_t actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(4, "info received, actlen=%d\n", actlen); /* usb_cdc_notification - .data[16] */ if (actlen < (sizeof(cdc) - 16)) { DPRINTF("data too short %d\n", actlen); goto tr_setup; } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, &cdc, (sizeof(cdc) - 16)); DPRINTFN(4, "bNotification=%x\n", cdc.bNotification); if (cdc.bNotification & UCDC_N_RESPONSE_AVAILABLE) { taskqueue_enqueue(taskqueue_thread, &sc->sc_if_status_task); } /* fall though */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: /* Error */ DPRINTF("USB transfer error, %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void usie_if_sync_to(void *arg) { struct usie_softc *sc = arg; taskqueue_enqueue(taskqueue_thread, &sc->sc_if_sync_task); } static void usie_if_sync_cb(void *arg, int pending) { struct usie_softc *sc = arg; mtx_lock(&sc->sc_mtx); /* call twice */ usie_if_cmd(sc, USIE_HIP_SYNC2M); usie_if_cmd(sc, USIE_HIP_SYNC2M); usb_callout_reset(&sc->sc_if_sync_ch, 2 * hz, usie_if_sync_to, sc); mtx_unlock(&sc->sc_mtx); } static void usie_if_status_cb(void *arg, int pending) { struct usie_softc *sc = arg; struct ifnet *ifp = sc->sc_ifp; struct usb_device_request req; struct usie_hip *hip; struct usie_lsi *lsi; uint16_t actlen; uint8_t ntries; uint8_t pad; mtx_lock(&sc->sc_mtx); req.bmRequestType = UT_READ_CLASS_INTERFACE; req.bRequest = UCDC_GET_ENCAPSULATED_RESPONSE; USETW(req.wValue, 0); USETW(req.wIndex, sc->sc_if_ifnum); USETW(req.wLength, sizeof(sc->sc_status_temp)); for (ntries = 0; ntries != 10; ntries++) { int err; err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx, &req, sc->sc_status_temp, USB_SHORT_XFER_OK, &actlen, USB_DEFAULT_TIMEOUT); if (err == 0) break; DPRINTF("Control request failed: %s %d/10\n", usbd_errstr(err), ntries); usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(10)); } if (ntries == 10) { mtx_unlock(&sc->sc_mtx); DPRINTF("Timeout\n"); return; } hip = (struct usie_hip *)sc->sc_status_temp; pad = (hip->id & USIE_HIP_PAD) ? 1 : 0; DPRINTF("hip.id=%x hip.len=%d actlen=%u pad=%d\n", hip->id, be16toh(hip->len), actlen, pad); switch (hip->id & USIE_HIP_MASK) { case USIE_HIP_SYNC2H: usie_if_cmd(sc, USIE_HIP_SYNC2M); break; case USIE_HIP_RESTR: usb_callout_stop(&sc->sc_if_sync_ch); break; case USIE_HIP_UMTS: lsi = (struct usie_lsi *)( sc->sc_status_temp + sizeof(struct usie_hip) + pad); DPRINTF("lsi.proto=%x lsi.len=%d\n", lsi->proto, be16toh(lsi->len)); if (lsi->proto != USIE_LSI_UMTS) break; if (lsi->area == USIE_LSI_AREA_NO || lsi->area == USIE_LSI_AREA_NODATA) { device_printf(sc->sc_dev, "no service available\n"); break; } if (lsi->state == USIE_LSI_STATE_IDLE) { DPRINTF("lsi.state=%x\n", lsi->state); break; } DPRINTF("ctx=%x\n", hip->param); sc->sc_txd.hip.param = hip->param; sc->sc_net.addr_len = lsi->pdp_addr_len; memcpy(&sc->sc_net.dns1_addr, &lsi->dns1_addr, 16); memcpy(&sc->sc_net.dns2_addr, &lsi->dns2_addr, 16); memcpy(sc->sc_net.pdp_addr, lsi->pdp_addr, 16); memcpy(sc->sc_net.gw_addr, lsi->gw_addr, 16); ifp->if_flags |= IFF_UP; ifp->if_drv_flags |= IFF_DRV_RUNNING; device_printf(sc->sc_dev, "IP Addr=%d.%d.%d.%d\n", *lsi->pdp_addr, *(lsi->pdp_addr + 1), *(lsi->pdp_addr + 2), *(lsi->pdp_addr + 3)); device_printf(sc->sc_dev, "Gateway Addr=%d.%d.%d.%d\n", *lsi->gw_addr, *(lsi->gw_addr + 1), *(lsi->gw_addr + 2), *(lsi->gw_addr + 3)); device_printf(sc->sc_dev, "Prim NS Addr=%d.%d.%d.%d\n", *lsi->dns1_addr, *(lsi->dns1_addr + 1), *(lsi->dns1_addr + 2), *(lsi->dns1_addr + 3)); device_printf(sc->sc_dev, "Scnd NS Addr=%d.%d.%d.%d\n", *lsi->dns2_addr, *(lsi->dns2_addr + 1), *(lsi->dns2_addr + 2), *(lsi->dns2_addr + 3)); usie_cns_req(sc, USIE_CNS_ID_RSSI, USIE_CNS_OB_RSSI); break; case USIE_HIP_RCGI: /* ignore, workaround for sloppy windows */ break; default: DPRINTF("undefined msgid: %x\n", hip->id); break; } mtx_unlock(&sc->sc_mtx); } static void usie_if_start(struct ifnet *ifp) { struct usie_softc *sc = ifp->if_softc; if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) { DPRINTF("Not running\n"); return; } mtx_lock(&sc->sc_mtx); usbd_transfer_start(sc->sc_if_xfer[USIE_IF_TX]); mtx_unlock(&sc->sc_mtx); DPRINTFN(3, "interface started\n"); } static int usie_if_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst, struct route *ro) { int err; DPRINTF("proto=%x\n", dst->sa_family); switch (dst->sa_family) { #ifdef INET6 case AF_INET6; /* fall though */ #endif case AF_INET: break; /* silently drop dhclient packets */ case AF_UNSPEC: m_freem(m); return (0); /* drop other packet types */ default: m_freem(m); return (EAFNOSUPPORT); } err = (ifp->if_transmit)(ifp, m); if (err) { if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); return (ENOBUFS); } if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); return (0); } static void usie_if_init(void *arg) { struct usie_softc *sc = arg; struct ifnet *ifp = sc->sc_ifp; uint8_t i; mtx_lock(&sc->sc_mtx); /* write tx descriptor */ sc->sc_txd.hip.id = USIE_HIP_CTX; sc->sc_txd.hip.param = 0; /* init value */ sc->sc_txd.desc_type = htobe16(USIE_IP_TX); for (i = 0; i != USIE_IF_N_XFER; i++) usbd_xfer_set_stall(sc->sc_if_xfer[i]); usbd_transfer_start(sc->sc_uc_xfer[USIE_HIP_IF][USIE_UC_RX]); usbd_transfer_start(sc->sc_if_xfer[USIE_IF_STATUS]); usbd_transfer_start(sc->sc_if_xfer[USIE_IF_RX]); /* if not running, initiate the modem */ if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) usie_cns_req(sc, USIE_CNS_ID_INIT, USIE_CNS_OB_LINK_UPDATE); mtx_unlock(&sc->sc_mtx); DPRINTF("ifnet initialized\n"); } static void usie_if_stop(struct usie_softc *sc) { usb_callout_drain(&sc->sc_if_sync_ch); mtx_lock(&sc->sc_mtx); /* usie_cns_req() clears IFF_* flags */ usie_cns_req(sc, USIE_CNS_ID_STOP, USIE_CNS_OB_LINK_UPDATE); usbd_transfer_stop(sc->sc_if_xfer[USIE_IF_TX]); usbd_transfer_stop(sc->sc_if_xfer[USIE_IF_RX]); usbd_transfer_stop(sc->sc_if_xfer[USIE_IF_STATUS]); /* shutdown device */ usie_if_cmd(sc, USIE_HIP_DOWN); mtx_unlock(&sc->sc_mtx); } static int usie_if_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) { struct usie_softc *sc = ifp->if_softc; struct ieee80211req *ireq; struct ieee80211req_sta_info si; struct ifmediareq *ifmr; switch (cmd) { case SIOCSIFFLAGS: if (ifp->if_flags & IFF_UP) { if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) usie_if_init(sc); } else { if (ifp->if_drv_flags & IFF_DRV_RUNNING) usie_if_stop(sc); } break; case SIOCSIFCAP: if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) { device_printf(sc->sc_dev, "Connect to the network first.\n"); break; } mtx_lock(&sc->sc_mtx); usie_cns_req(sc, USIE_CNS_ID_RSSI, USIE_CNS_OB_RSSI); mtx_unlock(&sc->sc_mtx); break; case SIOCG80211: ireq = (struct ieee80211req *)data; if (ireq->i_type != IEEE80211_IOC_STA_INFO) break; memset(&si, 0, sizeof(si)); si.isi_len = sizeof(si); /* * ifconfig expects RSSI in 0.5dBm units * relative to the noise floor. */ si.isi_rssi = 2 * sc->sc_rssi; if (copyout(&si, (uint8_t *)ireq->i_data + 8, sizeof(struct ieee80211req_sta_info))) DPRINTF("copyout failed\n"); DPRINTF("80211\n"); break; case SIOCGIFMEDIA: /* to fool ifconfig */ ifmr = (struct ifmediareq *)data; ifmr->ifm_count = 1; DPRINTF("media\n"); break; case SIOCSIFADDR: break; default: return (EINVAL); } return (0); } static int usie_do_request(struct usie_softc *sc, struct usb_device_request *req, void *data) { int err = 0; int ntries; mtx_assert(&sc->sc_mtx, MA_OWNED); for (ntries = 0; ntries != 10; ntries++) { err = usbd_do_request(sc->sc_udev, &sc->sc_mtx, req, data); if (err == 0) break; DPRINTF("Control request failed: %s %d/10\n", usbd_errstr(err), ntries); usb_pause_mtx(&sc->sc_mtx, USB_MS_TO_TICKS(10)); } return (err); } static int usie_if_cmd(struct usie_softc *sc, uint8_t cmd) { struct usb_device_request req; struct usie_hip msg; msg.len = 0; msg.id = cmd; msg.param = 0; req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SEND_ENCAPSULATED_COMMAND; USETW(req.wValue, 0); USETW(req.wIndex, sc->sc_if_ifnum); USETW(req.wLength, sizeof(msg)); DPRINTF("cmd=%x\n", cmd); return (usie_do_request(sc, &req, &msg)); } static void usie_cns_req(struct usie_softc *sc, uint32_t id, uint16_t obj) { struct ifnet *ifp = sc->sc_ifp; struct mbuf *m; struct usb_xfer *xfer; struct usie_hip *hip; struct usie_cns *cns; uint8_t *param; uint8_t *tmp; uint8_t cns_len; m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); if (__predict_false(m == NULL)) { DPRINTF("could not allocate mbuf\n"); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); return; } /* to align usie_hip{} on 32 bit */ m->m_data += 3; param = mtod(m, uint8_t *); *param++ = USIE_HIP_FRM_CHR; hip = (struct usie_hip *)param; cns = (struct usie_cns *)(hip + 1); tmp = param + USIE_HIPCNS_MIN - 2; switch (obj) { case USIE_CNS_OB_LINK_UPDATE: cns_len = 2; cns->op = USIE_CNS_OP_SET; *tmp++ = 1; /* profile ID, always use 1 for now */ *tmp++ = id == USIE_CNS_ID_INIT ? 1 : 0; break; case USIE_CNS_OB_PROF_WRITE: cns_len = 245; cns->op = USIE_CNS_OP_SET; *tmp++ = 1; /* profile ID, always use 1 for now */ *tmp++ = 2; memcpy(tmp, &sc->sc_net, 34); memset(tmp + 35, 0, 245 - 36); tmp += 243; break; case USIE_CNS_OB_RSSI: cns_len = 0; cns->op = USIE_CNS_OP_REQ; break; default: DPRINTF("unsupported CnS object type\n"); return; } *tmp = USIE_HIP_FRM_CHR; hip->len = htobe16(sizeof(struct usie_cns) + cns_len); hip->id = USIE_HIP_CNS2M; hip->param = 0; /* none for CnS */ cns->obj = htobe16(obj); cns->id = htobe32(id); cns->len = cns_len; cns->rsv0 = cns->rsv1 = 0; /* always '0' */ param = (uint8_t *)(cns + 1); DPRINTF("param: %16D\n", param, ":"); m->m_pkthdr.len = m->m_len = USIE_HIPCNS_MIN + cns_len + 2; xfer = sc->sc_uc_xfer[USIE_HIP_IF][USIE_UC_TX]; if (usbd_xfer_get_priv(xfer) == NULL) { usbd_xfer_set_priv(xfer, m); usbd_transfer_start(xfer); } else { DPRINTF("Dropped CNS event\n"); m_freem(m); } } static void usie_cns_rsp(struct usie_softc *sc, struct usie_cns *cns) { struct ifnet *ifp = sc->sc_ifp; DPRINTF("received CnS\n"); switch (be16toh(cns->obj)) { case USIE_CNS_OB_LINK_UPDATE: if (be32toh(cns->id) & USIE_CNS_ID_INIT) usie_if_sync_to(sc); else if (be32toh(cns->id) & USIE_CNS_ID_STOP) { ifp->if_flags &= ~IFF_UP; ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); } else DPRINTF("undefined link update\n"); break; case USIE_CNS_OB_RSSI: sc->sc_rssi = be16toh(*(int16_t *)(cns + 1)); if (sc->sc_rssi <= 0) device_printf(sc->sc_dev, "No signal\n"); else { device_printf(sc->sc_dev, "RSSI=%ddBm\n", sc->sc_rssi - 110); } break; case USIE_CNS_OB_PROF_WRITE: break; case USIE_CNS_OB_PDP_READ: break; default: DPRINTF("undefined CnS\n"); break; } } static void usie_hip_rsp(struct usie_softc *sc, uint8_t *rsp, uint32_t len) { struct usie_hip *hip; struct usie_cns *cns; uint32_t i; uint32_t j; uint32_t off; uint8_t tmp[USIE_HIPCNS_MAX] __aligned(4); for (off = 0; (off + USIE_HIPCNS_MIN) <= len; off++) { uint8_t pad; while ((off < len) && (rsp[off] == USIE_HIP_FRM_CHR)) off++; /* Unstuff the bytes */ for (i = j = 0; ((i + off) < len) && (j < USIE_HIPCNS_MAX); i++) { if (rsp[i + off] == USIE_HIP_FRM_CHR) break; if (rsp[i + off] == USIE_HIP_ESC_CHR) { if ((i + off + 1) >= len) break; tmp[j++] = rsp[i++ + off + 1] ^ 0x20; } else { tmp[j++] = rsp[i + off]; } } off += i; DPRINTF("frame len=%d\n", j); if (j < sizeof(struct usie_hip)) { DPRINTF("too little data\n"); break; } /* * Make sure we are not reading the stack if something * is wrong. */ memset(tmp + j, 0, sizeof(tmp) - j); hip = (struct usie_hip *)tmp; DPRINTF("hip: len=%d msgID=%02x, param=%02x\n", be16toh(hip->len), hip->id, hip->param); pad = (hip->id & USIE_HIP_PAD) ? 1 : 0; if ((hip->id & USIE_HIP_MASK) == USIE_HIP_CNS2H) { cns = (struct usie_cns *)(((uint8_t *)(hip + 1)) + pad); if (j < (sizeof(struct usie_cns) + sizeof(struct usie_hip) + pad)) { DPRINTF("too little data\n"); break; } DPRINTF("cns: obj=%04x, op=%02x, rsv0=%02x, " "app=%08x, rsv1=%02x, len=%d\n", be16toh(cns->obj), cns->op, cns->rsv0, be32toh(cns->id), cns->rsv1, cns->len); if (cns->op & USIE_CNS_OP_ERR) DPRINTF("CnS error response\n"); else usie_cns_rsp(sc, cns); i = sizeof(struct usie_hip) + pad + sizeof(struct usie_cns); j = cns->len; } else { i = sizeof(struct usie_hip) + pad; j = be16toh(hip->len); } #ifdef USB_DEBUG if (usie_debug == 0) continue; while (i < USIE_HIPCNS_MAX && j > 0) { DPRINTF("param[0x%02x] = 0x%02x\n", i, tmp[i]); i++; j--; } #endif } } static int usie_driver_loaded(struct module *mod, int what, void *arg) { switch (what) { case MOD_LOAD: /* register autoinstall handler */ usie_etag = EVENTHANDLER_REGISTER(usb_dev_configured, usie_autoinst, NULL, EVENTHANDLER_PRI_ANY); break; case MOD_UNLOAD: EVENTHANDLER_DEREGISTER(usb_dev_configured, usie_etag); break; default: return (EOPNOTSUPP); } return (0); } Index: head/sys/dev/usb/net/uhso.c =================================================================== --- head/sys/dev/usb/net/uhso.c (revision 276700) +++ head/sys/dev/usb/net/uhso.c (revision 276701) @@ -1,1932 +1,1932 @@ /*- * Copyright (c) 2010 Fredrik Lindberg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include __FBSDID("$FreeBSD$"); #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 "usbdevs.h" #define USB_DEBUG_VAR uhso_debug #include #include #include #include #include struct uhso_tty { struct uhso_softc *ht_sc; struct usb_xfer *ht_xfer[3]; int ht_muxport; /* Mux. port no */ int ht_open; char ht_name[32]; }; struct uhso_softc { device_t sc_dev; struct usb_device *sc_udev; struct mtx sc_mtx; uint32_t sc_type; /* Interface definition */ int sc_radio; struct usb_xfer *sc_xfer[3]; uint8_t sc_iface_no; uint8_t sc_iface_index; /* Control pipe */ struct usb_xfer * sc_ctrl_xfer[2]; uint8_t sc_ctrl_iface_no; /* Network */ struct usb_xfer *sc_if_xfer[2]; struct ifnet *sc_ifp; struct mbuf *sc_mwait; /* Partial packet */ size_t sc_waitlen; /* No. of outstanding bytes */ struct ifqueue sc_rxq; struct callout sc_c; /* TTY related structures */ struct ucom_super_softc sc_super_ucom; int sc_ttys; struct uhso_tty *sc_tty; struct ucom_softc *sc_ucom; int sc_msr; int sc_lsr; int sc_line; }; #define UHSO_MAX_MTU 2048 /* * There are mainly two type of cards floating around. * The first one has 2,3 or 4 interfaces with a multiplexed serial port * and packet interface on the first interface and bulk serial ports * on the others. * The second type of card has several other interfaces, their purpose * can be detected during run-time. */ #define UHSO_IFACE_SPEC(usb_type, port, port_type) \ (((usb_type) << 24) | ((port) << 16) | (port_type)) #define UHSO_IFACE_USB_TYPE(x) ((x >> 24) & 0xff) #define UHSO_IFACE_PORT(x) ((x >> 16) & 0xff) #define UHSO_IFACE_PORT_TYPE(x) (x & 0xff) /* * USB interface types */ #define UHSO_IF_NET 0x01 /* Network packet interface */ #define UHSO_IF_MUX 0x02 /* Multiplexed serial port */ #define UHSO_IF_BULK 0x04 /* Bulk interface */ /* * Port types */ #define UHSO_PORT_UNKNOWN 0x00 #define UHSO_PORT_SERIAL 0x01 /* Serial port */ #define UHSO_PORT_NETWORK 0x02 /* Network packet interface */ /* * Multiplexed serial port destination sub-port names */ #define UHSO_MPORT_TYPE_CTL 0x00 /* Control port */ #define UHSO_MPORT_TYPE_APP 0x01 /* Application */ #define UHSO_MPORT_TYPE_PCSC 0x02 #define UHSO_MPORT_TYPE_GPS 0x03 #define UHSO_MPORT_TYPE_APP2 0x04 /* Secondary application */ #define UHSO_MPORT_TYPE_MAX UHSO_MPORT_TYPE_APP2 #define UHSO_MPORT_TYPE_NOMAX 8 /* Max number of mux ports */ /* * Port definitions * Note that these definitions are arbitrary and do not match the values * returned by the auto config descriptor. */ #define UHSO_PORT_TYPE_UNKNOWN 0x00 #define UHSO_PORT_TYPE_CTL 0x01 #define UHSO_PORT_TYPE_APP 0x02 #define UHSO_PORT_TYPE_APP2 0x03 #define UHSO_PORT_TYPE_MODEM 0x04 #define UHSO_PORT_TYPE_NETWORK 0x05 #define UHSO_PORT_TYPE_DIAG 0x06 #define UHSO_PORT_TYPE_DIAG2 0x07 #define UHSO_PORT_TYPE_GPS 0x08 #define UHSO_PORT_TYPE_GPSCTL 0x09 #define UHSO_PORT_TYPE_PCSC 0x0a #define UHSO_PORT_TYPE_MSD 0x0b #define UHSO_PORT_TYPE_VOICE 0x0c #define UHSO_PORT_TYPE_MAX 0x0c static eventhandler_tag uhso_etag; /* Overall port type */ static char *uhso_port[] = { "Unknown", "Serial", "Network", "Network/Serial" }; /* * Map between interface port type read from device and description type. * The position in this array is a direct map to the auto config * descriptor values. */ static unsigned char uhso_port_map[] = { UHSO_PORT_TYPE_UNKNOWN, UHSO_PORT_TYPE_DIAG, UHSO_PORT_TYPE_GPS, UHSO_PORT_TYPE_GPSCTL, UHSO_PORT_TYPE_APP, UHSO_PORT_TYPE_APP2, UHSO_PORT_TYPE_CTL, UHSO_PORT_TYPE_NETWORK, UHSO_PORT_TYPE_MODEM, UHSO_PORT_TYPE_MSD, UHSO_PORT_TYPE_PCSC, UHSO_PORT_TYPE_VOICE }; static char uhso_port_map_max = sizeof(uhso_port_map) / sizeof(char); static unsigned char uhso_mux_port_map[] = { UHSO_PORT_TYPE_CTL, UHSO_PORT_TYPE_APP, UHSO_PORT_TYPE_PCSC, UHSO_PORT_TYPE_GPS, UHSO_PORT_TYPE_APP2 }; static char *uhso_port_type[] = { "Unknown", /* Not a valid port */ "Control", "Application", "Application (Secondary)", "Modem", "Network", "Diagnostic", "Diagnostic (Secondary)", "GPS", "GPS Control", "PC Smartcard", "MSD", "Voice", }; static char *uhso_port_type_sysctl[] = { "unknown", "control", "application", "application", "modem", "network", "diagnostic", "diagnostic", "gps", "gps_control", "pcsc", "msd", "voice", }; #define UHSO_STATIC_IFACE 0x01 #define UHSO_AUTO_IFACE 0x02 /* ifnet device unit allocations */ static struct unrhdr *uhso_ifnet_unit = NULL; static const STRUCT_USB_HOST_ID uhso_devs[] = { #define UHSO_DEV(v,p,i) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, i) } /* Option GlobeTrotter MAX 7.2 with upgraded firmware */ UHSO_DEV(OPTION, GTMAX72, UHSO_STATIC_IFACE), /* Option GlobeSurfer iCON 7.2 */ UHSO_DEV(OPTION, GSICON72, UHSO_STATIC_IFACE), /* Option iCON 225 */ UHSO_DEV(OPTION, GTHSDPA, UHSO_STATIC_IFACE), /* Option GlobeSurfer iCON HSUPA */ UHSO_DEV(OPTION, GSICONHSUPA, UHSO_STATIC_IFACE), /* Option GlobeTrotter HSUPA */ UHSO_DEV(OPTION, GTHSUPA, UHSO_STATIC_IFACE), /* GE40x */ UHSO_DEV(OPTION, GE40X, UHSO_AUTO_IFACE), UHSO_DEV(OPTION, GE40X_1, UHSO_AUTO_IFACE), UHSO_DEV(OPTION, GE40X_2, UHSO_AUTO_IFACE), UHSO_DEV(OPTION, GE40X_3, UHSO_AUTO_IFACE), /* Option GlobeSurfer iCON 401 */ UHSO_DEV(OPTION, ICON401, UHSO_AUTO_IFACE), /* Option GlobeTrotter Module 382 */ UHSO_DEV(OPTION, GMT382, UHSO_AUTO_IFACE), /* Option GTM661W */ UHSO_DEV(OPTION, GTM661W, UHSO_AUTO_IFACE), /* Option iCON EDGE */ UHSO_DEV(OPTION, ICONEDGE, UHSO_STATIC_IFACE), /* Option Module HSxPA */ UHSO_DEV(OPTION, MODHSXPA, UHSO_STATIC_IFACE), /* Option iCON 321 */ UHSO_DEV(OPTION, ICON321, UHSO_STATIC_IFACE), /* Option iCON 322 */ UHSO_DEV(OPTION, GTICON322, UHSO_STATIC_IFACE), /* Option iCON 505 */ UHSO_DEV(OPTION, ICON505, UHSO_AUTO_IFACE), /* Option iCON 452 */ UHSO_DEV(OPTION, ICON505, UHSO_AUTO_IFACE), #undef UHSO_DEV }; static SYSCTL_NODE(_hw_usb, OID_AUTO, uhso, CTLFLAG_RW, 0, "USB uhso"); static int uhso_autoswitch = 1; -SYSCTL_INT(_hw_usb_uhso, OID_AUTO, auto_switch, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_uhso, OID_AUTO, auto_switch, CTLFLAG_RWTUN, &uhso_autoswitch, 0, "Automatically switch to modem mode"); #ifdef USB_DEBUG #ifdef UHSO_DEBUG static int uhso_debug = UHSO_DEBUG; #else static int uhso_debug = -1; #endif -SYSCTL_INT(_hw_usb_uhso, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_uhso, OID_AUTO, debug, CTLFLAG_RWTUN, &uhso_debug, 0, "Debug level"); #define UHSO_DPRINTF(n, x, ...) {\ if (uhso_debug >= n) {\ printf("%s: " x, __func__, ##__VA_ARGS__);\ }\ } #else #define UHSO_DPRINTF(n, x, ...) #endif #ifdef UHSO_DEBUG_HEXDUMP # define UHSO_HEXDUMP(_buf, _len) do { \ { \ size_t __tmp; \ const char *__buf = (const char *)_buf; \ for (__tmp = 0; __tmp < _len; __tmp++) \ printf("%02hhx ", *__buf++); \ printf("\n"); \ } \ } while(0) #else # define UHSO_HEXDUMP(_buf, _len) #endif enum { UHSO_MUX_ENDPT_INTR = 0, UHSO_MUX_ENDPT_MAX }; enum { UHSO_CTRL_READ = 0, UHSO_CTRL_WRITE, UHSO_CTRL_MAX }; enum { UHSO_IFNET_READ = 0, UHSO_IFNET_WRITE, UHSO_IFNET_MAX }; enum { UHSO_BULK_ENDPT_READ = 0, UHSO_BULK_ENDPT_WRITE, UHSO_BULK_ENDPT_INTR, UHSO_BULK_ENDPT_MAX }; static usb_callback_t uhso_mux_intr_callback; static usb_callback_t uhso_mux_read_callback; static usb_callback_t uhso_mux_write_callback; static usb_callback_t uhso_bs_read_callback; static usb_callback_t uhso_bs_write_callback; static usb_callback_t uhso_bs_intr_callback; static usb_callback_t uhso_ifnet_read_callback; static usb_callback_t uhso_ifnet_write_callback; /* Config used for the default control pipes */ static const struct usb_config uhso_ctrl_config[UHSO_CTRL_MAX] = { [UHSO_CTRL_READ] = { .type = UE_CONTROL, .endpoint = 0x00, .direction = UE_DIR_ANY, .flags = { .pipe_bof = 1, .short_xfer_ok = 1 }, .bufsize = sizeof(struct usb_device_request) + 1024, .callback = &uhso_mux_read_callback }, [UHSO_CTRL_WRITE] = { .type = UE_CONTROL, .endpoint = 0x00, .direction = UE_DIR_ANY, .flags = { .pipe_bof = 1, .force_short_xfer = 1 }, .bufsize = sizeof(struct usb_device_request) + 1024, .timeout = 1000, .callback = &uhso_mux_write_callback } }; /* Config for the multiplexed serial ports */ static const struct usb_config uhso_mux_config[UHSO_MUX_ENDPT_MAX] = { [UHSO_MUX_ENDPT_INTR] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = { .short_xfer_ok = 1 }, .bufsize = 0, .callback = &uhso_mux_intr_callback, } }; /* Config for the raw IP-packet interface */ static const struct usb_config uhso_ifnet_config[UHSO_IFNET_MAX] = { [UHSO_IFNET_READ] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = { .pipe_bof = 1, .short_xfer_ok = 1 }, .bufsize = MCLBYTES, .callback = &uhso_ifnet_read_callback }, [UHSO_IFNET_WRITE] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .flags = { .pipe_bof = 1, .force_short_xfer = 1 }, .bufsize = MCLBYTES, .timeout = 5 * USB_MS_HZ, .callback = &uhso_ifnet_write_callback } }; /* Config for interfaces with normal bulk serial ports */ static const struct usb_config uhso_bs_config[UHSO_BULK_ENDPT_MAX] = { [UHSO_BULK_ENDPT_READ] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = { .pipe_bof = 1, .short_xfer_ok = 1 }, .bufsize = 4096, .callback = &uhso_bs_read_callback }, [UHSO_BULK_ENDPT_WRITE] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .flags = { .pipe_bof = 1, .force_short_xfer = 1 }, .bufsize = 8192, .callback = &uhso_bs_write_callback }, [UHSO_BULK_ENDPT_INTR] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = { .short_xfer_ok = 1 }, .bufsize = 0, .callback = &uhso_bs_intr_callback, } }; static int uhso_probe_iface(struct uhso_softc *, int, int (*probe)(struct usb_device *, int)); static int uhso_probe_iface_auto(struct usb_device *, int); static int uhso_probe_iface_static(struct usb_device *, int); static int uhso_attach_muxserial(struct uhso_softc *, struct usb_interface *, int type); static int uhso_attach_bulkserial(struct uhso_softc *, struct usb_interface *, int type); static int uhso_attach_ifnet(struct uhso_softc *, struct usb_interface *, int type); static void uhso_test_autoinst(void *, struct usb_device *, struct usb_attach_arg *); static int uhso_driver_loaded(struct module *, int, void *); static int uhso_radio_sysctl(SYSCTL_HANDLER_ARGS); static int uhso_radio_ctrl(struct uhso_softc *, int); static void uhso_free(struct ucom_softc *); static void uhso_ucom_start_read(struct ucom_softc *); static void uhso_ucom_stop_read(struct ucom_softc *); static void uhso_ucom_start_write(struct ucom_softc *); static void uhso_ucom_stop_write(struct ucom_softc *); static void uhso_ucom_cfg_get_status(struct ucom_softc *, uint8_t *, uint8_t *); static void uhso_ucom_cfg_set_dtr(struct ucom_softc *, uint8_t); static void uhso_ucom_cfg_set_rts(struct ucom_softc *, uint8_t); static void uhso_if_init(void *); static void uhso_if_start(struct ifnet *); static void uhso_if_stop(struct uhso_softc *); static int uhso_if_ioctl(struct ifnet *, u_long, caddr_t); static int uhso_if_output(struct ifnet *, struct mbuf *, const struct sockaddr *, struct route *); static void uhso_if_rxflush(void *); static device_probe_t uhso_probe; static device_attach_t uhso_attach; static device_detach_t uhso_detach; static void uhso_free_softc(struct uhso_softc *); static device_method_t uhso_methods[] = { DEVMETHOD(device_probe, uhso_probe), DEVMETHOD(device_attach, uhso_attach), DEVMETHOD(device_detach, uhso_detach), { 0, 0 } }; static driver_t uhso_driver = { .name = "uhso", .methods = uhso_methods, .size = sizeof(struct uhso_softc) }; static devclass_t uhso_devclass; DRIVER_MODULE(uhso, uhub, uhso_driver, uhso_devclass, uhso_driver_loaded, 0); MODULE_DEPEND(uhso, ucom, 1, 1, 1); MODULE_DEPEND(uhso, usb, 1, 1, 1); MODULE_VERSION(uhso, 1); static struct ucom_callback uhso_ucom_callback = { .ucom_cfg_get_status = &uhso_ucom_cfg_get_status, .ucom_cfg_set_dtr = &uhso_ucom_cfg_set_dtr, .ucom_cfg_set_rts = &uhso_ucom_cfg_set_rts, .ucom_start_read = uhso_ucom_start_read, .ucom_stop_read = uhso_ucom_stop_read, .ucom_start_write = uhso_ucom_start_write, .ucom_stop_write = uhso_ucom_stop_write, .ucom_free = &uhso_free, }; static int uhso_probe(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); int error; if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != 0) return (ENXIO); if (uaa->info.bDeviceClass != 0xff) return (ENXIO); error = usbd_lookup_id_by_uaa(uhso_devs, sizeof(uhso_devs), uaa); if (error != 0) return (error); /* * Probe device to see if we are able to attach * to this interface or not. */ if (USB_GET_DRIVER_INFO(uaa) == UHSO_AUTO_IFACE) { if (uhso_probe_iface_auto(uaa->device, uaa->info.bIfaceNum) == 0) return (ENXIO); } return (error); } static int uhso_attach(device_t self) { struct uhso_softc *sc = device_get_softc(self); struct usb_attach_arg *uaa = device_get_ivars(self); struct usb_interface_descriptor *id; struct sysctl_ctx_list *sctx; struct sysctl_oid *soid; struct sysctl_oid *tree = NULL, *tty_node; struct ucom_softc *ucom; struct uhso_tty *ht; int i, error, port; void *probe_f; usb_error_t uerr; char *desc; sc->sc_dev = self; sc->sc_udev = uaa->device; mtx_init(&sc->sc_mtx, "uhso", NULL, MTX_DEF); ucom_ref(&sc->sc_super_ucom); sc->sc_radio = 1; id = usbd_get_interface_descriptor(uaa->iface); sc->sc_ctrl_iface_no = id->bInterfaceNumber; sc->sc_iface_no = uaa->info.bIfaceNum; sc->sc_iface_index = uaa->info.bIfaceIndex; /* Setup control pipe */ uerr = usbd_transfer_setup(uaa->device, &sc->sc_iface_index, sc->sc_ctrl_xfer, uhso_ctrl_config, UHSO_CTRL_MAX, sc, &sc->sc_mtx); if (uerr) { device_printf(self, "Failed to setup control pipe: %s\n", usbd_errstr(uerr)); goto out; } if (USB_GET_DRIVER_INFO(uaa) == UHSO_STATIC_IFACE) probe_f = uhso_probe_iface_static; else if (USB_GET_DRIVER_INFO(uaa) == UHSO_AUTO_IFACE) probe_f = uhso_probe_iface_auto; else goto out; error = uhso_probe_iface(sc, uaa->info.bIfaceNum, probe_f); if (error != 0) goto out; sctx = device_get_sysctl_ctx(sc->sc_dev); soid = device_get_sysctl_tree(sc->sc_dev); SYSCTL_ADD_STRING(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "type", CTLFLAG_RD, uhso_port[UHSO_IFACE_PORT(sc->sc_type)], 0, "Port available at this interface"); SYSCTL_ADD_PROC(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "radio", - CTLTYPE_INT | CTLFLAG_RW, sc, 0, uhso_radio_sysctl, "I", "Enable radio"); + CTLTYPE_INT | CTLFLAG_RWTUN, sc, 0, uhso_radio_sysctl, "I", "Enable radio"); /* * The default interface description on most Option devices isn't * very helpful. So we skip device_set_usb_desc and set the * device description manually. */ device_set_desc_copy(self, uhso_port_type[UHSO_IFACE_PORT_TYPE(sc->sc_type)]); /* Announce device */ device_printf(self, "<%s port> at <%s %s> on %s\n", uhso_port_type[UHSO_IFACE_PORT_TYPE(sc->sc_type)], usb_get_manufacturer(uaa->device), usb_get_product(uaa->device), device_get_nameunit(device_get_parent(self))); if (sc->sc_ttys > 0) { SYSCTL_ADD_INT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "ports", CTLFLAG_RD, &sc->sc_ttys, 0, "Number of attached serial ports"); tree = SYSCTL_ADD_NODE(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "port", CTLFLAG_RD, NULL, "Serial ports"); } /* * Loop through the number of found TTYs and create sysctl * nodes for them. */ for (i = 0; i < sc->sc_ttys; i++) { ht = &sc->sc_tty[i]; ucom = &sc->sc_ucom[i]; if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_MUX) port = uhso_mux_port_map[ht->ht_muxport]; else port = UHSO_IFACE_PORT_TYPE(sc->sc_type); desc = uhso_port_type_sysctl[port]; tty_node = SYSCTL_ADD_NODE(sctx, SYSCTL_CHILDREN(tree), OID_AUTO, desc, CTLFLAG_RD, NULL, ""); ht->ht_name[0] = 0; if (sc->sc_ttys == 1) snprintf(ht->ht_name, 32, "cuaU%d", ucom->sc_super->sc_unit); else { snprintf(ht->ht_name, 32, "cuaU%d.%d", ucom->sc_super->sc_unit, ucom->sc_subunit); } desc = uhso_port_type[port]; SYSCTL_ADD_STRING(sctx, SYSCTL_CHILDREN(tty_node), OID_AUTO, "tty", CTLFLAG_RD, ht->ht_name, 0, ""); SYSCTL_ADD_STRING(sctx, SYSCTL_CHILDREN(tty_node), OID_AUTO, "desc", CTLFLAG_RD, desc, 0, ""); if (bootverbose) device_printf(sc->sc_dev, "\"%s\" port at %s\n", desc, ht->ht_name); } return (0); out: uhso_detach(sc->sc_dev); return (ENXIO); } static int uhso_detach(device_t self) { struct uhso_softc *sc = device_get_softc(self); int i; usbd_transfer_unsetup(sc->sc_xfer, 3); usbd_transfer_unsetup(sc->sc_ctrl_xfer, UHSO_CTRL_MAX); if (sc->sc_ttys > 0) { ucom_detach(&sc->sc_super_ucom, sc->sc_ucom); for (i = 0; i < sc->sc_ttys; i++) { if (sc->sc_tty[i].ht_muxport != -1) { usbd_transfer_unsetup(sc->sc_tty[i].ht_xfer, UHSO_CTRL_MAX); } } } if (sc->sc_ifp != NULL) { callout_drain(&sc->sc_c); free_unr(uhso_ifnet_unit, sc->sc_ifp->if_dunit); mtx_lock(&sc->sc_mtx); uhso_if_stop(sc); bpfdetach(sc->sc_ifp); if_detach(sc->sc_ifp); if_free(sc->sc_ifp); mtx_unlock(&sc->sc_mtx); usbd_transfer_unsetup(sc->sc_if_xfer, UHSO_IFNET_MAX); } device_claim_softc(self); uhso_free_softc(sc); return (0); } UCOM_UNLOAD_DRAIN(uhso); static void uhso_free_softc(struct uhso_softc *sc) { if (ucom_unref(&sc->sc_super_ucom)) { free(sc->sc_tty, M_USBDEV); free(sc->sc_ucom, M_USBDEV); mtx_destroy(&sc->sc_mtx); device_free_softc(sc); } } static void uhso_free(struct ucom_softc *ucom) { uhso_free_softc(ucom->sc_parent); } static void uhso_test_autoinst(void *arg, struct usb_device *udev, struct usb_attach_arg *uaa) { struct usb_interface *iface; struct usb_interface_descriptor *id; if (uaa->dev_state != UAA_DEV_READY || !uhso_autoswitch) return; iface = usbd_get_iface(udev, 0); if (iface == NULL) return; id = iface->idesc; if (id == NULL || id->bInterfaceClass != UICLASS_MASS) return; if (usbd_lookup_id_by_uaa(uhso_devs, sizeof(uhso_devs), uaa)) return; /* no device match */ if (usb_msc_eject(udev, 0, MSC_EJECT_REZERO) == 0) { /* success, mark the udev as disappearing */ uaa->dev_state = UAA_DEV_EJECTING; } } static int uhso_driver_loaded(struct module *mod, int what, void *arg) { switch (what) { case MOD_LOAD: /* register our autoinstall handler */ uhso_etag = EVENTHANDLER_REGISTER(usb_dev_configured, uhso_test_autoinst, NULL, EVENTHANDLER_PRI_ANY); /* create our unit allocator for inet devs */ uhso_ifnet_unit = new_unrhdr(0, INT_MAX, NULL); break; case MOD_UNLOAD: EVENTHANDLER_DEREGISTER(usb_dev_configured, uhso_etag); delete_unrhdr(uhso_ifnet_unit); break; default: return (EOPNOTSUPP); } return (0); } /* * Probe the interface type by querying the device. The elements * of an array indicates the capabilities of a particular interface. * Returns a bit mask with the interface capabilities. */ static int uhso_probe_iface_auto(struct usb_device *udev, int index) { struct usb_device_request req; usb_error_t uerr; uint16_t actlen = 0; char port; char buf[17] = {0}; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = 0x86; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, 17); uerr = usbd_do_request_flags(udev, NULL, &req, buf, 0, &actlen, USB_MS_HZ); if (uerr != 0) { printf("%s: usbd_do_request_flags failed, %s\n", __func__, usbd_errstr(uerr)); return (0); } UHSO_DPRINTF(1, "actlen=%d\n", actlen); UHSO_HEXDUMP(buf, 17); if (index < 0 || index > 16) { UHSO_DPRINTF(0, "Index %d out of range\n", index); return (0); } UHSO_DPRINTF(1, "index=%d, type=%x[%s]\n", index, buf[index], uhso_port_type[(int)uhso_port_map[(int)buf[index]]]); if (buf[index] >= uhso_port_map_max) port = 0; else port = uhso_port_map[(int)buf[index]]; switch (port) { case UHSO_PORT_TYPE_NETWORK: return (UHSO_IFACE_SPEC(UHSO_IF_NET | UHSO_IF_MUX, UHSO_PORT_SERIAL | UHSO_PORT_NETWORK, port)); case UHSO_PORT_TYPE_DIAG: case UHSO_PORT_TYPE_DIAG2: case UHSO_PORT_TYPE_GPS: case UHSO_PORT_TYPE_GPSCTL: case UHSO_PORT_TYPE_CTL: case UHSO_PORT_TYPE_APP: case UHSO_PORT_TYPE_APP2: case UHSO_PORT_TYPE_MODEM: return (UHSO_IFACE_SPEC(UHSO_IF_BULK, UHSO_PORT_SERIAL, port)); case UHSO_PORT_TYPE_MSD: return (0); case UHSO_PORT_TYPE_UNKNOWN: default: return (0); } return (0); } /* * Returns the capabilities of interfaces for devices that don't * support the automatic query. * Returns a bit mask with the interface capabilities. */ static int uhso_probe_iface_static(struct usb_device *udev, int index) { struct usb_config_descriptor *cd; cd = usbd_get_config_descriptor(udev); if (cd->bNumInterface <= 3) { /* Cards with 3 or less interfaces */ switch (index) { case 0: return UHSO_IFACE_SPEC(UHSO_IF_NET | UHSO_IF_MUX, UHSO_PORT_SERIAL | UHSO_PORT_NETWORK, UHSO_PORT_TYPE_NETWORK); case 1: return UHSO_IFACE_SPEC(UHSO_IF_BULK, UHSO_PORT_SERIAL, UHSO_PORT_TYPE_DIAG); case 2: return UHSO_IFACE_SPEC(UHSO_IF_BULK, UHSO_PORT_SERIAL, UHSO_PORT_TYPE_MODEM); } } else { /* Cards with 4 interfaces */ switch (index) { case 0: return UHSO_IFACE_SPEC(UHSO_IF_NET | UHSO_IF_MUX, UHSO_PORT_SERIAL | UHSO_PORT_NETWORK, UHSO_PORT_TYPE_NETWORK); case 1: return UHSO_IFACE_SPEC(UHSO_IF_BULK, UHSO_PORT_SERIAL, UHSO_PORT_TYPE_DIAG2); case 2: return UHSO_IFACE_SPEC(UHSO_IF_BULK, UHSO_PORT_SERIAL, UHSO_PORT_TYPE_MODEM); case 3: return UHSO_IFACE_SPEC(UHSO_IF_BULK, UHSO_PORT_SERIAL, UHSO_PORT_TYPE_DIAG); } } return (0); } /* * Probes an interface for its particular capabilities and attaches if * it's a supported interface. */ static int uhso_probe_iface(struct uhso_softc *sc, int index, int (*probe)(struct usb_device *, int)) { struct usb_interface *iface; int type, error; UHSO_DPRINTF(1, "Probing for interface %d, probe_func=%p\n", index, probe); type = probe(sc->sc_udev, index); UHSO_DPRINTF(1, "Probe result %x\n", type); if (type <= 0) return (ENXIO); sc->sc_type = type; iface = usbd_get_iface(sc->sc_udev, index); if (UHSO_IFACE_PORT_TYPE(type) == UHSO_PORT_TYPE_NETWORK) { error = uhso_attach_ifnet(sc, iface, type); if (error) { UHSO_DPRINTF(1, "uhso_attach_ifnet failed"); return (ENXIO); } /* * If there is an additional interrupt endpoint on this * interface then we most likely have a multiplexed serial port * available. */ if (iface->idesc->bNumEndpoints < 3) { sc->sc_type = UHSO_IFACE_SPEC( UHSO_IFACE_USB_TYPE(type) & ~UHSO_IF_MUX, UHSO_IFACE_PORT(type) & ~UHSO_PORT_SERIAL, UHSO_IFACE_PORT_TYPE(type)); return (0); } UHSO_DPRINTF(1, "Trying to attach mux. serial\n"); error = uhso_attach_muxserial(sc, iface, type); if (error == 0 && sc->sc_ttys > 0) { error = ucom_attach(&sc->sc_super_ucom, sc->sc_ucom, sc->sc_ttys, sc, &uhso_ucom_callback, &sc->sc_mtx); if (error) { device_printf(sc->sc_dev, "ucom_attach failed\n"); return (ENXIO); } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, sc->sc_dev); mtx_lock(&sc->sc_mtx); usbd_transfer_start(sc->sc_xfer[UHSO_MUX_ENDPT_INTR]); mtx_unlock(&sc->sc_mtx); } } else if ((UHSO_IFACE_USB_TYPE(type) & UHSO_IF_BULK) && UHSO_IFACE_PORT(type) & UHSO_PORT_SERIAL) { error = uhso_attach_bulkserial(sc, iface, type); if (error) return (ENXIO); error = ucom_attach(&sc->sc_super_ucom, sc->sc_ucom, sc->sc_ttys, sc, &uhso_ucom_callback, &sc->sc_mtx); if (error) { device_printf(sc->sc_dev, "ucom_attach failed\n"); return (ENXIO); } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, sc->sc_dev); } else { UHSO_DPRINTF(0, "Unknown type %x\n", type); return (ENXIO); } return (0); } static int uhso_radio_ctrl(struct uhso_softc *sc, int onoff) { struct usb_device_request req; usb_error_t uerr; req.bmRequestType = UT_VENDOR; req.bRequest = onoff ? 0x82 : 0x81; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, 0); uerr = usbd_do_request(sc->sc_udev, NULL, &req, NULL); if (uerr != 0) { device_printf(sc->sc_dev, "usbd_do_request_flags failed: %s\n", usbd_errstr(uerr)); return (-1); } return (onoff); } static int uhso_radio_sysctl(SYSCTL_HANDLER_ARGS) { struct uhso_softc *sc = arg1; int error, radio; radio = sc->sc_radio; error = sysctl_handle_int(oidp, &radio, 0, req); if (error) return (error); if (radio != sc->sc_radio) { radio = radio != 0 ? 1 : 0; error = uhso_radio_ctrl(sc, radio); if (error != -1) sc->sc_radio = radio; } return (0); } /* * Expands allocated memory to fit an additional TTY. * Two arrays are kept with matching indexes, one for ucom and one * for our private data. */ static int uhso_alloc_tty(struct uhso_softc *sc) { sc->sc_ttys++; sc->sc_tty = reallocf(sc->sc_tty, sizeof(struct uhso_tty) * sc->sc_ttys, M_USBDEV, M_WAITOK | M_ZERO); if (sc->sc_tty == NULL) return (-1); sc->sc_ucom = reallocf(sc->sc_ucom, sizeof(struct ucom_softc) * sc->sc_ttys, M_USBDEV, M_WAITOK | M_ZERO); if (sc->sc_ucom == NULL) return (-1); sc->sc_tty[sc->sc_ttys - 1].ht_sc = sc; UHSO_DPRINTF(1, "Allocated TTY %d\n", sc->sc_ttys - 1); return (sc->sc_ttys - 1); } /* * Attach a multiplexed serial port * Data is read/written with requests on the default control pipe. An interrupt * endpoint returns when there is new data to be read. */ static int uhso_attach_muxserial(struct uhso_softc *sc, struct usb_interface *iface, int type) { struct usb_descriptor *desc; int i, port, tty; usb_error_t uerr; /* * The class specific interface (type 0x24) descriptor subtype field * contains a bitmask that specifies which (and how many) ports that * are available through this multiplexed serial port. */ desc = usbd_find_descriptor(sc->sc_udev, NULL, iface->idesc->bInterfaceNumber, UDESC_CS_INTERFACE, 0xff, 0, 0); if (desc == NULL) { UHSO_DPRINTF(0, "Failed to find UDESC_CS_INTERFACE\n"); return (ENXIO); } UHSO_DPRINTF(1, "Mux port mask %x\n", desc->bDescriptorSubtype); if (desc->bDescriptorSubtype == 0) return (ENXIO); /* * The bitmask is one octet, loop through the number of * bits that are set and create a TTY for each. */ for (i = 0; i < 8; i++) { port = (1 << i); if ((port & desc->bDescriptorSubtype) == port) { UHSO_DPRINTF(2, "Found mux port %x (%d)\n", port, i); tty = uhso_alloc_tty(sc); if (tty < 0) return (ENOMEM); sc->sc_tty[tty].ht_muxport = i; uerr = usbd_transfer_setup(sc->sc_udev, &sc->sc_iface_index, sc->sc_tty[tty].ht_xfer, uhso_ctrl_config, UHSO_CTRL_MAX, sc, &sc->sc_mtx); if (uerr) { device_printf(sc->sc_dev, "Failed to setup control pipe: %s\n", usbd_errstr(uerr)); return (ENXIO); } } } /* Setup the intr. endpoint */ uerr = usbd_transfer_setup(sc->sc_udev, &iface->idesc->bInterfaceNumber, sc->sc_xfer, uhso_mux_config, 1, sc, &sc->sc_mtx); if (uerr) return (ENXIO); return (0); } /* * Interrupt callback for the multiplexed serial port. Indicates * which serial port has data waiting. */ static void uhso_mux_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct usb_page_cache *pc; struct usb_page_search res; struct uhso_softc *sc = usbd_xfer_softc(xfer); unsigned int i, mux; UHSO_DPRINTF(3, "status %d\n", USB_GET_STATE(xfer)); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: /* * The multiplexed port number can be found at the first byte. * It contains a bit mask, we transform this in to an integer. */ pc = usbd_xfer_get_frame(xfer, 0); usbd_get_page(pc, 0, &res); i = *((unsigned char *)res.buffer); mux = 0; while (i >>= 1) { mux++; } UHSO_DPRINTF(3, "mux port %d (%d)\n", mux, i); if (mux > UHSO_MPORT_TYPE_NOMAX) break; /* Issue a read for this serial port */ usbd_xfer_set_priv( sc->sc_tty[mux].ht_xfer[UHSO_CTRL_READ], &sc->sc_tty[mux]); usbd_transfer_start(sc->sc_tty[mux].ht_xfer[UHSO_CTRL_READ]); break; case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: UHSO_DPRINTF(0, "error: %s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) break; usbd_xfer_set_stall(xfer); goto tr_setup; } } static void uhso_mux_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhso_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; struct usb_device_request req; struct uhso_tty *ht; int actlen, len; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); UHSO_DPRINTF(3, "status %d\n", USB_GET_STATE(xfer)); ht = usbd_xfer_get_priv(xfer); UHSO_DPRINTF(3, "ht=%p open=%d\n", ht, ht->ht_open); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: /* Got data, send to ucom */ pc = usbd_xfer_get_frame(xfer, 1); len = usbd_xfer_frame_len(xfer, 1); UHSO_DPRINTF(3, "got %d bytes on mux port %d\n", len, ht->ht_muxport); if (len <= 0) { usbd_transfer_start(sc->sc_xfer[UHSO_MUX_ENDPT_INTR]); break; } /* Deliver data if the TTY is open, discard otherwise */ if (ht->ht_open) ucom_put_data(&sc->sc_ucom[ht->ht_muxport], pc, 0, len); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: memset(&req, 0, sizeof(struct usb_device_request)); req.bmRequestType = UT_READ_CLASS_INTERFACE; req.bRequest = UCDC_GET_ENCAPSULATED_RESPONSE; USETW(req.wValue, 0); USETW(req.wIndex, ht->ht_muxport); USETW(req.wLength, 1024); pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, &req, sizeof(req)); usbd_xfer_set_frame_len(xfer, 0, sizeof(req)); usbd_xfer_set_frame_len(xfer, 1, 1024); usbd_xfer_set_frames(xfer, 2); usbd_transfer_submit(xfer); break; default: UHSO_DPRINTF(0, "error: %s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) break; usbd_xfer_set_stall(xfer); goto tr_setup; } } static void uhso_mux_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhso_softc *sc = usbd_xfer_softc(xfer); struct uhso_tty *ht; struct usb_page_cache *pc; struct usb_device_request req; int actlen; struct usb_page_search res; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); ht = usbd_xfer_get_priv(xfer); UHSO_DPRINTF(3, "status=%d, using mux port %d\n", USB_GET_STATE(xfer), ht->ht_muxport); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: UHSO_DPRINTF(3, "wrote %zd data bytes to muxport %d\n", actlen - sizeof(struct usb_device_request) , ht->ht_muxport); /* FALLTHROUGH */ case USB_ST_SETUP: pc = usbd_xfer_get_frame(xfer, 1); if (ucom_get_data(&sc->sc_ucom[ht->ht_muxport], pc, 0, 32, &actlen)) { usbd_get_page(pc, 0, &res); memset(&req, 0, sizeof(struct usb_device_request)); req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SEND_ENCAPSULATED_COMMAND; USETW(req.wValue, 0); USETW(req.wIndex, ht->ht_muxport); USETW(req.wLength, actlen); pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, &req, sizeof(req)); usbd_xfer_set_frame_len(xfer, 0, sizeof(req)); usbd_xfer_set_frame_len(xfer, 1, actlen); usbd_xfer_set_frames(xfer, 2); UHSO_DPRINTF(3, "Prepared %d bytes for transmit " "on muxport %d\n", actlen, ht->ht_muxport); usbd_transfer_submit(xfer); } break; default: UHSO_DPRINTF(0, "error: %s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) break; break; } } static int uhso_attach_bulkserial(struct uhso_softc *sc, struct usb_interface *iface, int type) { usb_error_t uerr; int tty; /* Try attaching RD/WR/INTR first */ uerr = usbd_transfer_setup(sc->sc_udev, &iface->idesc->bInterfaceNumber, sc->sc_xfer, uhso_bs_config, UHSO_BULK_ENDPT_MAX, sc, &sc->sc_mtx); if (uerr) { /* Try only RD/WR */ uerr = usbd_transfer_setup(sc->sc_udev, &iface->idesc->bInterfaceNumber, sc->sc_xfer, uhso_bs_config, UHSO_BULK_ENDPT_MAX - 1, sc, &sc->sc_mtx); } if (uerr) { UHSO_DPRINTF(0, "usbd_transfer_setup failed"); return (-1); } tty = uhso_alloc_tty(sc); if (tty < 0) { usbd_transfer_unsetup(sc->sc_xfer, UHSO_BULK_ENDPT_MAX); return (ENOMEM); } sc->sc_tty[tty].ht_muxport = -1; return (0); } static void uhso_bs_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhso_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); UHSO_DPRINTF(3, "status %d, actlen=%d\n", USB_GET_STATE(xfer), actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); ucom_put_data(&sc->sc_ucom[0], pc, 0, actlen); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: UHSO_DPRINTF(0, "error: %s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) break; usbd_xfer_set_stall(xfer); goto tr_setup; } } static void uhso_bs_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhso_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); UHSO_DPRINTF(3, "status %d, actlen=%d\n", USB_GET_STATE(xfer), actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: case USB_ST_SETUP: tr_setup: pc = usbd_xfer_get_frame(xfer, 0); if (ucom_get_data(&sc->sc_ucom[0], pc, 0, 8192, &actlen)) { usbd_xfer_set_frame_len(xfer, 0, actlen); usbd_transfer_submit(xfer); } break; break; default: UHSO_DPRINTF(0, "error: %s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) break; usbd_xfer_set_stall(xfer); goto tr_setup; } } static void uhso_bs_cfg(struct uhso_softc *sc) { struct usb_device_request req; usb_error_t uerr; if (!(UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_BULK)) return; req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SET_CONTROL_LINE_STATE; USETW(req.wValue, sc->sc_line); USETW(req.wIndex, sc->sc_iface_no); USETW(req.wLength, 0); uerr = ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom[0], &req, NULL, 0, 1000); if (uerr != 0) { device_printf(sc->sc_dev, "failed to set ctrl line state to " "0x%02x: %s\n", sc->sc_line, usbd_errstr(uerr)); } } static void uhso_bs_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhso_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; struct usb_cdc_notification cdc; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); UHSO_DPRINTF(3, "status %d, actlen=%d\n", USB_GET_STATE(xfer), actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen < UCDC_NOTIFICATION_LENGTH) { UHSO_DPRINTF(0, "UCDC notification too short: %d\n", actlen); goto tr_setup; } else if (actlen > (int)sizeof(struct usb_cdc_notification)) { UHSO_DPRINTF(0, "UCDC notification too large: %d\n", actlen); actlen = sizeof(struct usb_cdc_notification); } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, &cdc, actlen); if (UGETW(cdc.wIndex) != sc->sc_iface_no) { UHSO_DPRINTF(0, "Interface mismatch, got %d expected %d\n", UGETW(cdc.wIndex), sc->sc_iface_no); goto tr_setup; } if (cdc.bmRequestType == UCDC_NOTIFICATION && cdc.bNotification == UCDC_N_SERIAL_STATE) { UHSO_DPRINTF(2, "notify = 0x%02x\n", cdc.data[0]); sc->sc_msr = 0; sc->sc_lsr = 0; if (cdc.data[0] & UCDC_N_SERIAL_RI) sc->sc_msr |= SER_RI; if (cdc.data[0] & UCDC_N_SERIAL_DSR) sc->sc_msr |= SER_DSR; if (cdc.data[0] & UCDC_N_SERIAL_DCD) sc->sc_msr |= SER_DCD; ucom_status_change(&sc->sc_ucom[0]); } case USB_ST_SETUP: tr_setup: default: if (error == USB_ERR_CANCELLED) break; usbd_xfer_set_stall(xfer); goto tr_setup; } } static void uhso_ucom_cfg_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr) { struct uhso_softc *sc = ucom->sc_parent; *lsr = sc->sc_lsr; *msr = sc->sc_msr; } static void uhso_ucom_cfg_set_dtr(struct ucom_softc *ucom, uint8_t onoff) { struct uhso_softc *sc = ucom->sc_parent; if (!(UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_BULK)) return; if (onoff) sc->sc_line |= UCDC_LINE_DTR; else sc->sc_line &= ~UCDC_LINE_DTR; uhso_bs_cfg(sc); } static void uhso_ucom_cfg_set_rts(struct ucom_softc *ucom, uint8_t onoff) { struct uhso_softc *sc = ucom->sc_parent; if (!(UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_BULK)) return; if (onoff) sc->sc_line |= UCDC_LINE_RTS; else sc->sc_line &= ~UCDC_LINE_RTS; uhso_bs_cfg(sc); } static void uhso_ucom_start_read(struct ucom_softc *ucom) { struct uhso_softc *sc = ucom->sc_parent; UHSO_DPRINTF(3, "unit=%d, subunit=%d\n", ucom->sc_super->sc_unit, ucom->sc_subunit); if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_MUX) { sc->sc_tty[ucom->sc_subunit].ht_open = 1; usbd_transfer_start(sc->sc_xfer[UHSO_MUX_ENDPT_INTR]); } else if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_BULK) { sc->sc_tty[0].ht_open = 1; usbd_transfer_start(sc->sc_xfer[UHSO_BULK_ENDPT_READ]); if (sc->sc_xfer[UHSO_BULK_ENDPT_INTR] != NULL) usbd_transfer_start(sc->sc_xfer[UHSO_BULK_ENDPT_INTR]); } } static void uhso_ucom_stop_read(struct ucom_softc *ucom) { struct uhso_softc *sc = ucom->sc_parent; if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_MUX) { sc->sc_tty[ucom->sc_subunit].ht_open = 0; usbd_transfer_stop( sc->sc_tty[ucom->sc_subunit].ht_xfer[UHSO_CTRL_READ]); } else if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_BULK) { sc->sc_tty[0].ht_open = 0; usbd_transfer_start(sc->sc_xfer[UHSO_BULK_ENDPT_READ]); if (sc->sc_xfer[UHSO_BULK_ENDPT_INTR] != NULL) usbd_transfer_stop(sc->sc_xfer[UHSO_BULK_ENDPT_INTR]); } } static void uhso_ucom_start_write(struct ucom_softc *ucom) { struct uhso_softc *sc = ucom->sc_parent; if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_MUX) { UHSO_DPRINTF(3, "local unit %d\n", ucom->sc_subunit); usbd_transfer_start(sc->sc_xfer[UHSO_MUX_ENDPT_INTR]); usbd_xfer_set_priv( sc->sc_tty[ucom->sc_subunit].ht_xfer[UHSO_CTRL_WRITE], &sc->sc_tty[ucom->sc_subunit]); usbd_transfer_start( sc->sc_tty[ucom->sc_subunit].ht_xfer[UHSO_CTRL_WRITE]); } else if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_BULK) { usbd_transfer_start(sc->sc_xfer[UHSO_BULK_ENDPT_WRITE]); } } static void uhso_ucom_stop_write(struct ucom_softc *ucom) { struct uhso_softc *sc = ucom->sc_parent; if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_MUX) { usbd_transfer_stop( sc->sc_tty[ucom->sc_subunit].ht_xfer[UHSO_CTRL_WRITE]); } else if (UHSO_IFACE_USB_TYPE(sc->sc_type) & UHSO_IF_BULK) { usbd_transfer_stop(sc->sc_xfer[UHSO_BULK_ENDPT_WRITE]); } } static int uhso_attach_ifnet(struct uhso_softc *sc, struct usb_interface *iface, int type) { struct ifnet *ifp; usb_error_t uerr; struct sysctl_ctx_list *sctx; struct sysctl_oid *soid; unsigned int devunit; uerr = usbd_transfer_setup(sc->sc_udev, &iface->idesc->bInterfaceNumber, sc->sc_if_xfer, uhso_ifnet_config, UHSO_IFNET_MAX, sc, &sc->sc_mtx); if (uerr) { UHSO_DPRINTF(0, "usbd_transfer_setup failed: %s\n", usbd_errstr(uerr)); return (-1); } sc->sc_ifp = ifp = if_alloc(IFT_OTHER); if (sc->sc_ifp == NULL) { device_printf(sc->sc_dev, "if_alloc() failed\n"); return (-1); } callout_init_mtx(&sc->sc_c, &sc->sc_mtx, 0); mtx_lock(&sc->sc_mtx); callout_reset(&sc->sc_c, 1, uhso_if_rxflush, sc); mtx_unlock(&sc->sc_mtx); /* * We create our own unit numbers for ifnet devices because the * USB interface unit numbers can be at arbitrary positions yielding * odd looking device names. */ devunit = alloc_unr(uhso_ifnet_unit); if_initname(ifp, device_get_name(sc->sc_dev), devunit); ifp->if_mtu = UHSO_MAX_MTU; ifp->if_ioctl = uhso_if_ioctl; ifp->if_init = uhso_if_init; ifp->if_start = uhso_if_start; ifp->if_output = uhso_if_output; ifp->if_flags = IFF_BROADCAST | IFF_MULTICAST | IFF_NOARP; ifp->if_softc = sc; IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen); ifp->if_snd.ifq_drv_maxlen = ifqmaxlen; IFQ_SET_READY(&ifp->if_snd); if_attach(ifp); bpfattach(ifp, DLT_RAW, 0); sctx = device_get_sysctl_ctx(sc->sc_dev); soid = device_get_sysctl_tree(sc->sc_dev); /* Unlocked read... */ SYSCTL_ADD_STRING(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "netif", CTLFLAG_RD, ifp->if_xname, 0, "Attached network interface"); return (0); } static void uhso_ifnet_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhso_softc *sc = usbd_xfer_softc(xfer); struct mbuf *m; struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); UHSO_DPRINTF(3, "status=%d, actlen=%d\n", USB_GET_STATE(xfer), actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen > 0 && (sc->sc_ifp->if_drv_flags & IFF_DRV_RUNNING)) { pc = usbd_xfer_get_frame(xfer, 0); m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); usbd_copy_out(pc, 0, mtod(m, uint8_t *), actlen); m->m_pkthdr.len = m->m_len = actlen; /* Enqueue frame for further processing */ _IF_ENQUEUE(&sc->sc_rxq, m); if (!callout_pending(&sc->sc_c) || !callout_active(&sc->sc_c)) { callout_schedule(&sc->sc_c, 1); } } /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: UHSO_DPRINTF(0, "error: %s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) break; usbd_xfer_set_stall(xfer); goto tr_setup; } } /* * Deferred RX processing, called with mutex locked. * * Each frame we receive might contain several small ip-packets as well * as partial ip-packets. We need to separate/assemble them into individual * packets before sending them to the ip-layer. */ static void uhso_if_rxflush(void *arg) { struct uhso_softc *sc = arg; struct ifnet *ifp = sc->sc_ifp; uint8_t *cp; struct mbuf *m, *m0, *mwait; struct ip *ip; #ifdef INET6 struct ip6_hdr *ip6; #endif uint16_t iplen; int len, isr; m = NULL; mwait = sc->sc_mwait; for (;;) { if (m == NULL) { _IF_DEQUEUE(&sc->sc_rxq, m); if (m == NULL) break; UHSO_DPRINTF(3, "dequeue m=%p, len=%d\n", m, m->m_len); } mtx_unlock(&sc->sc_mtx); /* Do we have a partial packet waiting? */ if (mwait != NULL) { m0 = mwait; mwait = NULL; UHSO_DPRINTF(3, "partial m0=%p(%d), concat w/ m=%p(%d)\n", m0, m0->m_len, m, m->m_len); len = m->m_len + m0->m_len; /* Concat mbufs and fix headers */ m_cat(m0, m); m0->m_pkthdr.len = len; m->m_flags &= ~M_PKTHDR; m = m_pullup(m0, sizeof(struct ip)); if (m == NULL) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); UHSO_DPRINTF(0, "m_pullup failed\n"); mtx_lock(&sc->sc_mtx); continue; } UHSO_DPRINTF(3, "Constructed mbuf=%p, len=%d\n", m, m->m_pkthdr.len); } cp = mtod(m, uint8_t *); ip = (struct ip *)cp; #ifdef INET6 ip6 = (struct ip6_hdr *)cp; #endif /* Check for IPv4 */ if (ip->ip_v == IPVERSION) { iplen = htons(ip->ip_len); isr = NETISR_IP; } #ifdef INET6 /* Check for IPv6 */ else if ((ip6->ip6_vfc & IPV6_VERSION_MASK) == IPV6_VERSION) { iplen = htons(ip6->ip6_plen); isr = NETISR_IPV6; } #endif else { UHSO_DPRINTF(0, "got unexpected ip version %d, " "m=%p, len=%d\n", (*cp & 0xf0) >> 4, m, m->m_len); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); UHSO_HEXDUMP(cp, 4); m_freem(m); m = NULL; mtx_lock(&sc->sc_mtx); continue; } if (iplen == 0) { UHSO_DPRINTF(0, "Zero IP length\n"); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); m_freem(m); m = NULL; mtx_lock(&sc->sc_mtx); continue; } UHSO_DPRINTF(3, "m=%p, len=%d, cp=%p, iplen=%d\n", m, m->m_pkthdr.len, cp, iplen); m0 = NULL; /* More IP packets in this mbuf */ if (iplen < m->m_pkthdr.len) { m0 = m; /* * Allocate a new mbuf for this IP packet and * copy the IP-packet into it. */ m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); memcpy(mtod(m, uint8_t *), mtod(m0, uint8_t *), iplen); m->m_pkthdr.len = m->m_len = iplen; /* Adjust the size of the original mbuf */ m_adj(m0, iplen); m0 = m_defrag(m0, M_WAITOK); UHSO_DPRINTF(3, "New mbuf=%p, len=%d/%d, m0=%p, " "m0_len=%d/%d\n", m, m->m_pkthdr.len, m->m_len, m0, m0->m_pkthdr.len, m0->m_len); } else if (iplen > m->m_pkthdr.len) { UHSO_DPRINTF(3, "Deferred mbuf=%p, len=%d\n", m, m->m_pkthdr.len); mwait = m; m = NULL; mtx_lock(&sc->sc_mtx); continue; } if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1); m->m_pkthdr.rcvif = ifp; /* Dispatch to IP layer */ BPF_MTAP(sc->sc_ifp, m); M_SETFIB(m, ifp->if_fib); netisr_dispatch(isr, m); m = m0 != NULL ? m0 : NULL; mtx_lock(&sc->sc_mtx); } sc->sc_mwait = mwait; } static void uhso_ifnet_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhso_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct usb_page_cache *pc; struct mbuf *m; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); UHSO_DPRINTF(3, "status %d, actlen=%d\n", USB_GET_STATE(xfer), actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; case USB_ST_SETUP: tr_setup: IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; ifp->if_drv_flags |= IFF_DRV_OACTIVE; if (m->m_pkthdr.len > MCLBYTES) m->m_pkthdr.len = MCLBYTES; usbd_xfer_set_frame_len(xfer, 0, m->m_pkthdr.len); pc = usbd_xfer_get_frame(xfer, 0); usbd_m_copy_in(pc, 0, m, 0, m->m_pkthdr.len); usbd_transfer_submit(xfer); BPF_MTAP(ifp, m); m_freem(m); break; default: UHSO_DPRINTF(0, "error: %s\n", usbd_errstr(error)); if (error == USB_ERR_CANCELLED) break; usbd_xfer_set_stall(xfer); goto tr_setup; } } static int uhso_if_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) { struct uhso_softc *sc; sc = ifp->if_softc; switch (cmd) { case SIOCSIFFLAGS: if (ifp->if_flags & IFF_UP) { if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) { uhso_if_init(sc); } } else { if (ifp->if_drv_flags & IFF_DRV_RUNNING) { mtx_lock(&sc->sc_mtx); uhso_if_stop(sc); mtx_unlock(&sc->sc_mtx); } } break; case SIOCSIFADDR: case SIOCADDMULTI: case SIOCDELMULTI: break; default: return (EINVAL); } return (0); } static void uhso_if_init(void *priv) { struct uhso_softc *sc = priv; struct ifnet *ifp = sc->sc_ifp; mtx_lock(&sc->sc_mtx); uhso_if_stop(sc); ifp = sc->sc_ifp; ifp->if_flags |= IFF_UP; ifp->if_drv_flags |= IFF_DRV_RUNNING; mtx_unlock(&sc->sc_mtx); UHSO_DPRINTF(2, "ifnet initialized\n"); } static int uhso_if_output(struct ifnet *ifp, struct mbuf *m0, const struct sockaddr *dst, struct route *ro) { int error; /* Only IPv4/6 support */ if (dst->sa_family != AF_INET #ifdef INET6 && dst->sa_family != AF_INET6 #endif ) { return (EAFNOSUPPORT); } error = (ifp->if_transmit)(ifp, m0); if (error) { if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); return (ENOBUFS); } if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); return (0); } static void uhso_if_start(struct ifnet *ifp) { struct uhso_softc *sc = ifp->if_softc; if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) { UHSO_DPRINTF(1, "Not running\n"); return; } mtx_lock(&sc->sc_mtx); usbd_transfer_start(sc->sc_if_xfer[UHSO_IFNET_READ]); usbd_transfer_start(sc->sc_if_xfer[UHSO_IFNET_WRITE]); mtx_unlock(&sc->sc_mtx); UHSO_DPRINTF(3, "interface started\n"); } static void uhso_if_stop(struct uhso_softc *sc) { usbd_transfer_stop(sc->sc_if_xfer[UHSO_IFNET_READ]); usbd_transfer_stop(sc->sc_if_xfer[UHSO_IFNET_WRITE]); sc->sc_ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); } Index: head/sys/dev/usb/serial/u3g.c =================================================================== --- head/sys/dev/usb/serial/u3g.c (revision 276700) +++ head/sys/dev/usb/serial/u3g.c (revision 276701) @@ -1,1217 +1,1217 @@ /* * Copyright (c) 2008 AnyWi Technologies * Author: Andrea Guzzo * * based on uark.c 1.1 2006/08/14 08:30:22 jsg * * * parts from ubsa.c 183348 2008-09-25 12:00:56Z phk * * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * $FreeBSD$ */ /* * NOTE: * * - The detour through the tty layer is ridiculously expensive wrt * buffering due to the high speeds. * * We should consider adding a simple r/w device which allows * attaching of PPP in a more efficient way. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR u3g_debug #include #include #include #include #include #ifdef USB_DEBUG static int u3g_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, u3g, CTLFLAG_RW, 0, "USB 3g"); -SYSCTL_INT(_hw_usb_u3g, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_u3g, OID_AUTO, debug, CTLFLAG_RWTUN, &u3g_debug, 0, "Debug level"); #endif #define U3G_MAXPORTS 12 #define U3G_CONFIG_INDEX 0 #define U3G_BSIZE 2048 #define U3G_TXSIZE (U3G_BSIZE / U3G_TXFRAMES) #define U3G_TXFRAMES 4 /* Eject methods; See also usb_quirks.h:UQ_MSC_EJECT_* */ #define U3GINIT_HUAWEI 1 /* Requires Huawei init command */ #define U3GINIT_SIERRA 2 /* Requires Sierra init command */ #define U3GINIT_SCSIEJECT 3 /* Requires SCSI eject command */ #define U3GINIT_REZERO 4 /* Requires SCSI rezero command */ #define U3GINIT_ZTESTOR 5 /* Requires ZTE SCSI command */ #define U3GINIT_CMOTECH 6 /* Requires CMOTECH SCSI command */ #define U3GINIT_WAIT 7 /* Device reappears after a delay */ #define U3GINIT_SAEL_M460 8 /* Requires vendor init */ #define U3GINIT_HUAWEISCSI 9 /* Requires Huawei SCSI init command */ #define U3GINIT_HUAWEISCSI2 10 /* Requires Huawei SCSI init command (2) */ #define U3GINIT_TCT 11 /* Requires TCT Mobile init command */ enum { U3G_BULK_WR, U3G_BULK_RD, U3G_INTR, U3G_N_TRANSFER, }; struct u3g_softc { struct ucom_super_softc sc_super_ucom; struct ucom_softc sc_ucom[U3G_MAXPORTS]; struct usb_xfer *sc_xfer[U3G_MAXPORTS][U3G_N_TRANSFER]; uint8_t sc_iface[U3G_MAXPORTS]; /* local status register */ uint8_t sc_lsr[U3G_MAXPORTS]; /* local status register */ uint8_t sc_msr[U3G_MAXPORTS]; /* u3g status register */ uint16_t sc_line[U3G_MAXPORTS]; /* line status */ struct usb_device *sc_udev; struct mtx sc_mtx; uint8_t sc_numports; }; static device_probe_t u3g_probe; static device_attach_t u3g_attach; static device_detach_t u3g_detach; static void u3g_free_softc(struct u3g_softc *); static usb_callback_t u3g_write_callback; static usb_callback_t u3g_read_callback; static usb_callback_t u3g_intr_callback; static void u3g_cfg_get_status(struct ucom_softc *, uint8_t *, uint8_t *); static void u3g_cfg_set_dtr(struct ucom_softc *, uint8_t); static void u3g_cfg_set_rts(struct ucom_softc *, uint8_t); static void u3g_start_read(struct ucom_softc *ucom); static void u3g_stop_read(struct ucom_softc *ucom); static void u3g_start_write(struct ucom_softc *ucom); static void u3g_stop_write(struct ucom_softc *ucom); static void u3g_poll(struct ucom_softc *ucom); static void u3g_free(struct ucom_softc *ucom); static void u3g_test_autoinst(void *, struct usb_device *, struct usb_attach_arg *); static int u3g_driver_loaded(struct module *mod, int what, void *arg); static eventhandler_tag u3g_etag; static const struct usb_config u3g_config[U3G_N_TRANSFER] = { [U3G_BULK_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = U3G_BSIZE,/* bytes */ .frames = U3G_TXFRAMES, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = &u3g_write_callback, }, [U3G_BULK_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = U3G_BSIZE,/* bytes */ .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &u3g_read_callback, }, [U3G_INTR] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,.no_pipe_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = &u3g_intr_callback, }, }; static const struct ucom_callback u3g_callback = { .ucom_cfg_get_status = &u3g_cfg_get_status, .ucom_cfg_set_dtr = &u3g_cfg_set_dtr, .ucom_cfg_set_rts = &u3g_cfg_set_rts, .ucom_start_read = &u3g_start_read, .ucom_stop_read = &u3g_stop_read, .ucom_start_write = &u3g_start_write, .ucom_stop_write = &u3g_stop_write, .ucom_poll = &u3g_poll, .ucom_free = &u3g_free, }; static device_method_t u3g_methods[] = { DEVMETHOD(device_probe, u3g_probe), DEVMETHOD(device_attach, u3g_attach), DEVMETHOD(device_detach, u3g_detach), DEVMETHOD_END }; static devclass_t u3g_devclass; static driver_t u3g_driver = { .name = "u3g", .methods = u3g_methods, .size = sizeof(struct u3g_softc), }; DRIVER_MODULE(u3g, uhub, u3g_driver, u3g_devclass, u3g_driver_loaded, 0); MODULE_DEPEND(u3g, ucom, 1, 1, 1); MODULE_DEPEND(u3g, usb, 1, 1, 1); MODULE_VERSION(u3g, 1); static const STRUCT_USB_HOST_ID u3g_devs[] = { #define U3G_DEV(v,p,i) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, i) } U3G_DEV(ACERP, H10, 0), U3G_DEV(AIRPLUS, MCD650, 0), U3G_DEV(AIRPRIME, PC5220, 0), U3G_DEV(AIRPRIME, AC313U, 0), U3G_DEV(ALINK, 3G, 0), U3G_DEV(ALINK, 3GU, 0), U3G_DEV(ALINK, DWM652U5, 0), U3G_DEV(AMOI, H01, 0), U3G_DEV(AMOI, H01A, 0), U3G_DEV(AMOI, H02, 0), U3G_DEV(ANYDATA, ADU_500A, 0), U3G_DEV(ANYDATA, ADU_620UW, 0), U3G_DEV(ANYDATA, ADU_E100X, 0), U3G_DEV(AXESSTEL, DATAMODEM, 0), U3G_DEV(CMOTECH, CDMA_MODEM1, 0), U3G_DEV(CMOTECH, CGU628, U3GINIT_CMOTECH), U3G_DEV(DELL, U5500, 0), U3G_DEV(DELL, U5505, 0), U3G_DEV(DELL, U5510, 0), U3G_DEV(DELL, U5520, 0), U3G_DEV(DELL, U5520_2, 0), U3G_DEV(DELL, U5520_3, 0), U3G_DEV(DELL, U5700, 0), U3G_DEV(DELL, U5700_2, 0), U3G_DEV(DELL, U5700_3, 0), U3G_DEV(DELL, U5700_4, 0), U3G_DEV(DELL, U5720, 0), U3G_DEV(DELL, U5720_2, 0), U3G_DEV(DELL, U5730, 0), U3G_DEV(DELL, U5730_2, 0), U3G_DEV(DELL, U5730_3, 0), U3G_DEV(DELL, U740, 0), U3G_DEV(DLINK, DWR510_CD, U3GINIT_SCSIEJECT), U3G_DEV(DLINK, DWR510, 0), U3G_DEV(DLINK3, DWM652, 0), U3G_DEV(HP, EV2200, 0), U3G_DEV(HP, HS2300, 0), U3G_DEV(HP, UN2420_QDL, 0), U3G_DEV(HP, UN2420, 0), U3G_DEV(HUAWEI, E1401, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1402, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1403, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1404, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1405, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1406, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1407, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1408, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1409, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E140A, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E140B, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E140D, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E140E, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E140F, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1410, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1411, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1412, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1413, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1414, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1415, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1416, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1417, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1418, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1419, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E141A, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E141B, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E141C, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E141D, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E141E, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E141F, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1420, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1421, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1422, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1423, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1424, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1425, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1426, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1427, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1428, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1429, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E142A, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E142B, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E142C, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E142D, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E142E, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E142F, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1430, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1431, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1432, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1433, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1434, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1435, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1436, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1437, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1438, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1439, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E143A, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E143B, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E143C, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E143D, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E143E, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E143F, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E173, 0), U3G_DEV(HUAWEI, E173_INIT, U3GINIT_HUAWEISCSI), U3G_DEV(HUAWEI, E3131, 0), U3G_DEV(HUAWEI, E3131_INIT, U3GINIT_HUAWEISCSI), U3G_DEV(HUAWEI, E180V, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E220, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E220BIS, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E392, U3GINIT_HUAWEISCSI), U3G_DEV(HUAWEI, MOBILE, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, E1752, U3GINIT_HUAWEISCSI), U3G_DEV(HUAWEI, E1820, U3GINIT_HUAWEISCSI), U3G_DEV(HUAWEI, K3772, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, K3772_INIT, U3GINIT_HUAWEISCSI2), U3G_DEV(HUAWEI, K3765, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, K3765_INIT, U3GINIT_HUAWEISCSI), U3G_DEV(HUAWEI, K3770, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, K3770_INIT, U3GINIT_HUAWEISCSI), U3G_DEV(HUAWEI, K4505, U3GINIT_HUAWEI), U3G_DEV(HUAWEI, K4505_INIT, U3GINIT_HUAWEISCSI), U3G_DEV(HUAWEI, ETS2055, U3GINIT_HUAWEI), U3G_DEV(KYOCERA2, CDMA_MSM_K, 0), U3G_DEV(KYOCERA2, KPC680, 0), U3G_DEV(LONGCHEER, WM66, U3GINIT_HUAWEI), U3G_DEV(LONGCHEER, DISK, U3GINIT_TCT), U3G_DEV(LONGCHEER, W14, 0), U3G_DEV(LONGCHEER, XSSTICK, 0), U3G_DEV(MERLIN, V620, 0), U3G_DEV(NEOTEL, PRIME, 0), U3G_DEV(NOVATEL, E725, 0), U3G_DEV(NOVATEL, ES620, 0), U3G_DEV(NOVATEL, ES620_2, 0), U3G_DEV(NOVATEL, EU730, 0), U3G_DEV(NOVATEL, EU740, 0), U3G_DEV(NOVATEL, EU870D, 0), U3G_DEV(NOVATEL, MC760, 0), U3G_DEV(NOVATEL, MC547, 0), U3G_DEV(NOVATEL, MC679, 0), U3G_DEV(NOVATEL, MC950D, 0), U3G_DEV(NOVATEL, MC990D, 0), U3G_DEV(NOVATEL, MIFI2200, U3GINIT_SCSIEJECT), U3G_DEV(NOVATEL, MIFI2200V, U3GINIT_SCSIEJECT), U3G_DEV(NOVATEL, U720, 0), U3G_DEV(NOVATEL, U727, 0), U3G_DEV(NOVATEL, U727_2, 0), U3G_DEV(NOVATEL, U740, 0), U3G_DEV(NOVATEL, U740_2, 0), U3G_DEV(NOVATEL, U760, U3GINIT_SCSIEJECT), U3G_DEV(NOVATEL, U870, 0), U3G_DEV(NOVATEL, V620, 0), U3G_DEV(NOVATEL, V640, 0), U3G_DEV(NOVATEL, V720, 0), U3G_DEV(NOVATEL, V740, 0), U3G_DEV(NOVATEL, X950D, 0), U3G_DEV(NOVATEL, XU870, 0), U3G_DEV(MOTOROLA2, MB886, U3GINIT_SCSIEJECT), U3G_DEV(OPTION, E6500, 0), U3G_DEV(OPTION, E6501, 0), U3G_DEV(OPTION, E6601, 0), U3G_DEV(OPTION, E6721, 0), U3G_DEV(OPTION, E6741, 0), U3G_DEV(OPTION, E6761, 0), U3G_DEV(OPTION, E6800, 0), U3G_DEV(OPTION, E7021, 0), U3G_DEV(OPTION, E7041, 0), U3G_DEV(OPTION, E7061, 0), U3G_DEV(OPTION, E7100, 0), U3G_DEV(OPTION, GE40X, 0), U3G_DEV(OPTION, GT3G, 0), U3G_DEV(OPTION, GT3GPLUS, 0), U3G_DEV(OPTION, GT3GQUAD, 0), U3G_DEV(OPTION, GT3G_1, 0), U3G_DEV(OPTION, GT3G_2, 0), U3G_DEV(OPTION, GT3G_3, 0), U3G_DEV(OPTION, GT3G_4, 0), U3G_DEV(OPTION, GT3G_5, 0), U3G_DEV(OPTION, GT3G_6, 0), U3G_DEV(OPTION, GTHSDPA, 0), U3G_DEV(OPTION, GTM380, 0), U3G_DEV(OPTION, GTMAX36, 0), U3G_DEV(OPTION, GTMAX380HSUPAE, 0), U3G_DEV(OPTION, GTMAXHSUPA, 0), U3G_DEV(OPTION, GTMAXHSUPAE, 0), U3G_DEV(OPTION, VODAFONEMC3G, 0), U3G_DEV(QISDA, H20_1, 0), U3G_DEV(QISDA, H20_2, 0), U3G_DEV(QISDA, H21_1, 0), U3G_DEV(QISDA, H21_2, 0), U3G_DEV(QUALCOMM, NTT_L02C_MODEM, U3GINIT_SCSIEJECT), U3G_DEV(QUALCOMM2, AC8700, 0), U3G_DEV(QUALCOMM2, MF330, 0), U3G_DEV(QUALCOMM2, SIM5218, 0), U3G_DEV(QUALCOMM2, VW110L, U3GINIT_SCSIEJECT), U3G_DEV(QUALCOMM2, GOBI2000_QDL, 0), U3G_DEV(QUALCOMM2, GOBI2000, 0), U3G_DEV(QUALCOMM2, VT80N, 0), U3G_DEV(QUALCOMM3, VFAST2, 0), U3G_DEV(QUALCOMMINC, AC2726, 0), U3G_DEV(QUALCOMMINC, AC682_INIT, U3GINIT_SCSIEJECT), U3G_DEV(QUALCOMMINC, AC682, 0), U3G_DEV(QUALCOMMINC, AC8700, 0), U3G_DEV(QUALCOMMINC, AC8710, 0), U3G_DEV(QUALCOMMINC, CDMA_MSM, U3GINIT_SCSIEJECT), U3G_DEV(QUALCOMMINC, E0002, 0), U3G_DEV(QUALCOMMINC, E0003, 0), U3G_DEV(QUALCOMMINC, E0004, 0), U3G_DEV(QUALCOMMINC, E0005, 0), U3G_DEV(QUALCOMMINC, E0006, 0), U3G_DEV(QUALCOMMINC, E0007, 0), U3G_DEV(QUALCOMMINC, E0008, 0), U3G_DEV(QUALCOMMINC, E0009, 0), U3G_DEV(QUALCOMMINC, E000A, 0), U3G_DEV(QUALCOMMINC, E000B, 0), U3G_DEV(QUALCOMMINC, E000C, 0), U3G_DEV(QUALCOMMINC, E000D, 0), U3G_DEV(QUALCOMMINC, E000E, 0), U3G_DEV(QUALCOMMINC, E000F, 0), U3G_DEV(QUALCOMMINC, E0010, 0), U3G_DEV(QUALCOMMINC, E0011, 0), U3G_DEV(QUALCOMMINC, E0012, 0), U3G_DEV(QUALCOMMINC, E0013, 0), U3G_DEV(QUALCOMMINC, E0014, 0), U3G_DEV(QUALCOMMINC, E0017, 0), U3G_DEV(QUALCOMMINC, E0018, 0), U3G_DEV(QUALCOMMINC, E0019, 0), U3G_DEV(QUALCOMMINC, E0020, 0), U3G_DEV(QUALCOMMINC, E0021, 0), U3G_DEV(QUALCOMMINC, E0022, 0), U3G_DEV(QUALCOMMINC, E0023, 0), U3G_DEV(QUALCOMMINC, E0024, 0), U3G_DEV(QUALCOMMINC, E0025, 0), U3G_DEV(QUALCOMMINC, E0026, 0), U3G_DEV(QUALCOMMINC, E0027, 0), U3G_DEV(QUALCOMMINC, E0028, 0), U3G_DEV(QUALCOMMINC, E0029, 0), U3G_DEV(QUALCOMMINC, E0030, 0), U3G_DEV(QUALCOMMINC, E0032, 0), U3G_DEV(QUALCOMMINC, E0033, 0), U3G_DEV(QUALCOMMINC, E0037, 0), U3G_DEV(QUALCOMMINC, E0039, 0), U3G_DEV(QUALCOMMINC, E0042, 0), U3G_DEV(QUALCOMMINC, E0043, 0), U3G_DEV(QUALCOMMINC, E0048, 0), U3G_DEV(QUALCOMMINC, E0049, 0), U3G_DEV(QUALCOMMINC, E0051, 0), U3G_DEV(QUALCOMMINC, E0052, 0), U3G_DEV(QUALCOMMINC, E0054, 0), U3G_DEV(QUALCOMMINC, E0055, 0), U3G_DEV(QUALCOMMINC, E0057, 0), U3G_DEV(QUALCOMMINC, E0058, 0), U3G_DEV(QUALCOMMINC, E0059, 0), U3G_DEV(QUALCOMMINC, E0060, 0), U3G_DEV(QUALCOMMINC, E0061, 0), U3G_DEV(QUALCOMMINC, E0062, 0), U3G_DEV(QUALCOMMINC, E0063, 0), U3G_DEV(QUALCOMMINC, E0064, 0), U3G_DEV(QUALCOMMINC, E0066, 0), U3G_DEV(QUALCOMMINC, E0069, 0), U3G_DEV(QUALCOMMINC, E0070, 0), U3G_DEV(QUALCOMMINC, E0073, 0), U3G_DEV(QUALCOMMINC, E0076, 0), U3G_DEV(QUALCOMMINC, E0078, 0), U3G_DEV(QUALCOMMINC, E0082, 0), U3G_DEV(QUALCOMMINC, E0086, 0), U3G_DEV(QUALCOMMINC, SURFSTICK, 0), U3G_DEV(QUALCOMMINC, E2002, 0), U3G_DEV(QUALCOMMINC, E2003, 0), U3G_DEV(QUALCOMMINC, K3772_Z, 0), U3G_DEV(QUALCOMMINC, K3772_Z_INIT, U3GINIT_SCSIEJECT), U3G_DEV(QUALCOMMINC, MF195E, 0), U3G_DEV(QUALCOMMINC, MF195E_INIT, U3GINIT_SCSIEJECT), U3G_DEV(QUALCOMMINC, MF626, 0), U3G_DEV(QUALCOMMINC, MF628, 0), U3G_DEV(QUALCOMMINC, MF633R, 0), U3G_DEV(QUANTA, GKE, 0), U3G_DEV(QUANTA, GLE, 0), U3G_DEV(QUANTA, GLX, 0), U3G_DEV(QUANTA, Q101, 0), U3G_DEV(QUANTA, Q111, 0), U3G_DEV(SIERRA, AC402, 0), U3G_DEV(SIERRA, AC595U, 0), U3G_DEV(SIERRA, AC313U, 0), U3G_DEV(SIERRA, AC597E, 0), U3G_DEV(SIERRA, AC875E, 0), U3G_DEV(SIERRA, AC875U, 0), U3G_DEV(SIERRA, AC875U_2, 0), U3G_DEV(SIERRA, AC880, 0), U3G_DEV(SIERRA, AC880E, 0), U3G_DEV(SIERRA, AC880U, 0), U3G_DEV(SIERRA, AC881, 0), U3G_DEV(SIERRA, AC881E, 0), U3G_DEV(SIERRA, AC881U, 0), U3G_DEV(SIERRA, AC885E, 0), U3G_DEV(SIERRA, AC885E_2, 0), U3G_DEV(SIERRA, AC885U, 0), U3G_DEV(SIERRA, AIRCARD580, 0), U3G_DEV(SIERRA, AIRCARD595, 0), U3G_DEV(SIERRA, AIRCARD875, 0), U3G_DEV(SIERRA, C22, 0), U3G_DEV(SIERRA, C597, 0), U3G_DEV(SIERRA, C888, 0), U3G_DEV(SIERRA, E0029, 0), U3G_DEV(SIERRA, E6892, 0), U3G_DEV(SIERRA, E6893, 0), U3G_DEV(SIERRA, EM5625, 0), U3G_DEV(SIERRA, EM5725, 0), U3G_DEV(SIERRA, MC5720, 0), U3G_DEV(SIERRA, MC5720_2, 0), U3G_DEV(SIERRA, MC5725, 0), U3G_DEV(SIERRA, MC5727, 0), U3G_DEV(SIERRA, MC5727_2, 0), U3G_DEV(SIERRA, MC5728, 0), U3G_DEV(SIERRA, MC8700, 0), U3G_DEV(SIERRA, MC8755, 0), U3G_DEV(SIERRA, MC8755_2, 0), U3G_DEV(SIERRA, MC8755_3, 0), U3G_DEV(SIERRA, MC8755_4, 0), U3G_DEV(SIERRA, MC8765, 0), U3G_DEV(SIERRA, MC8765_2, 0), U3G_DEV(SIERRA, MC8765_3, 0), U3G_DEV(SIERRA, MC8775, 0), U3G_DEV(SIERRA, MC8775_2, 0), U3G_DEV(SIERRA, MC8780, 0), U3G_DEV(SIERRA, MC8780_2, 0), U3G_DEV(SIERRA, MC8780_3, 0), U3G_DEV(SIERRA, MC8781, 0), U3G_DEV(SIERRA, MC8781_2, 0), U3G_DEV(SIERRA, MC8781_3, 0), U3G_DEV(SIERRA, MC8785, 0), U3G_DEV(SIERRA, MC8785_2, 0), U3G_DEV(SIERRA, MC8790, 0), U3G_DEV(SIERRA, MC8791, 0), U3G_DEV(SIERRA, MC8792, 0), U3G_DEV(SIERRA, MINI5725, 0), U3G_DEV(SIERRA, T11, 0), U3G_DEV(SIERRA, T598, 0), U3G_DEV(SILABS, SAEL, U3GINIT_SAEL_M460), U3G_DEV(STELERA, C105, 0), U3G_DEV(STELERA, E1003, 0), U3G_DEV(STELERA, E1004, 0), U3G_DEV(STELERA, E1005, 0), U3G_DEV(STELERA, E1006, 0), U3G_DEV(STELERA, E1007, 0), U3G_DEV(STELERA, E1008, 0), U3G_DEV(STELERA, E1009, 0), U3G_DEV(STELERA, E100A, 0), U3G_DEV(STELERA, E100B, 0), U3G_DEV(STELERA, E100C, 0), U3G_DEV(STELERA, E100D, 0), U3G_DEV(STELERA, E100E, 0), U3G_DEV(STELERA, E100F, 0), U3G_DEV(STELERA, E1010, 0), U3G_DEV(STELERA, E1011, 0), U3G_DEV(STELERA, E1012, 0), U3G_DEV(TCTMOBILE, X060S, 0), U3G_DEV(TCTMOBILE, X080S, U3GINIT_TCT), U3G_DEV(TELIT, UC864E, 0), U3G_DEV(TELIT, UC864G, 0), U3G_DEV(TLAYTECH, TEU800, 0), U3G_DEV(TOSHIBA, G450, 0), U3G_DEV(TOSHIBA, HSDPA, 0), U3G_DEV(YISO, C893, 0), U3G_DEV(WETELECOM, WM_D200, 0), /* Autoinstallers */ U3G_DEV(NOVATEL, ZEROCD, U3GINIT_SCSIEJECT), U3G_DEV(OPTION, GTICON322, U3GINIT_REZERO), U3G_DEV(QUALCOMMINC, ZTE_STOR, U3GINIT_ZTESTOR), U3G_DEV(QUALCOMMINC, ZTE_STOR2, U3GINIT_SCSIEJECT), U3G_DEV(QUANTA, Q101_STOR, U3GINIT_SCSIEJECT), U3G_DEV(SIERRA, TRUINSTALL, U3GINIT_SIERRA), #undef U3G_DEV }; static int u3g_sierra_init(struct usb_device *udev) { struct usb_device_request req; req.bmRequestType = UT_VENDOR; req.bRequest = UR_SET_INTERFACE; USETW(req.wValue, UF_DEVICE_REMOTE_WAKEUP); USETW(req.wIndex, UHF_PORT_CONNECTION); USETW(req.wLength, 0); if (usbd_do_request_flags(udev, NULL, &req, NULL, 0, NULL, USB_MS_HZ)) { /* ignore any errors */ } return (0); } static int u3g_huawei_init(struct usb_device *udev) { struct usb_device_request req; req.bmRequestType = UT_WRITE_DEVICE; req.bRequest = UR_SET_FEATURE; USETW(req.wValue, UF_DEVICE_REMOTE_WAKEUP); USETW(req.wIndex, UHF_PORT_SUSPEND); USETW(req.wLength, 0); if (usbd_do_request_flags(udev, NULL, &req, NULL, 0, NULL, USB_MS_HZ)) { /* ignore any errors */ } return (0); } static void u3g_sael_m460_init(struct usb_device *udev) { static const uint8_t setup[][24] = { { 0x41, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x41, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x41, 0x13, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0xc1, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x40, 0x02 }, { 0xc1, 0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00 }, { 0x41, 0x07, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 }, { 0xc1, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02 }, { 0x41, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x41, 0x07, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 }, { 0x41, 0x03, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00 }, { 0x41, 0x19, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x13 }, { 0x41, 0x13, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x09, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00 }, { 0x41, 0x12, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x41, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x41, 0x07, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 }, { 0x41, 0x03, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00 }, { 0x41, 0x19, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x13 }, { 0x41, 0x13, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x09, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00 }, { 0x41, 0x07, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 }, }; struct usb_device_request req; usb_error_t err; uint16_t len; uint8_t buf[0x300]; uint8_t n; DPRINTFN(1, "\n"); if (usbd_req_set_alt_interface_no(udev, NULL, 0, 0)) { DPRINTFN(0, "Alt setting 0 failed\n"); return; } for (n = 0; n != (sizeof(setup)/sizeof(setup[0])); n++) { memcpy(&req, setup[n], sizeof(req)); len = UGETW(req.wLength); if (req.bmRequestType & UE_DIR_IN) { if (len > sizeof(buf)) { DPRINTFN(0, "too small buffer\n"); continue; } err = usbd_do_request(udev, NULL, &req, buf); } else { if (len > (sizeof(setup[0]) - 8)) { DPRINTFN(0, "too small buffer\n"); continue; } err = usbd_do_request(udev, NULL, &req, __DECONST(uint8_t *, &setup[n][8])); } if (err) { DPRINTFN(1, "request %u failed\n", (unsigned int)n); /* * Some of the requests will fail. Stop doing * requests when we are getting timeouts so * that we don't block the explore/attach * thread forever. */ if (err == USB_ERR_TIMEOUT) break; } } } /* * The following function handles 3G modem devices (E220, Mobile, * etc.) with auto-install flash disks for Windows/MacOSX on the first * interface. After some command or some delay they change appearance * to a modem. */ static void u3g_test_autoinst(void *arg, struct usb_device *udev, struct usb_attach_arg *uaa) { struct usb_interface *iface; struct usb_interface_descriptor *id; int error; unsigned long method; if (uaa->dev_state != UAA_DEV_READY) return; iface = usbd_get_iface(udev, 0); if (iface == NULL) return; id = iface->idesc; if (id == NULL || id->bInterfaceClass != UICLASS_MASS) return; if (usb_test_quirk(uaa, UQ_MSC_EJECT_HUAWEI)) method = U3GINIT_HUAWEI; else if (usb_test_quirk(uaa, UQ_MSC_EJECT_SIERRA)) method = U3GINIT_SIERRA; else if (usb_test_quirk(uaa, UQ_MSC_EJECT_SCSIEJECT)) method = U3GINIT_SCSIEJECT; else if (usb_test_quirk(uaa, UQ_MSC_EJECT_REZERO)) method = U3GINIT_REZERO; else if (usb_test_quirk(uaa, UQ_MSC_EJECT_ZTESTOR)) method = U3GINIT_ZTESTOR; else if (usb_test_quirk(uaa, UQ_MSC_EJECT_CMOTECH)) method = U3GINIT_CMOTECH; else if (usb_test_quirk(uaa, UQ_MSC_EJECT_WAIT)) method = U3GINIT_WAIT; else if (usb_test_quirk(uaa, UQ_MSC_EJECT_HUAWEISCSI)) method = U3GINIT_HUAWEISCSI; else if (usb_test_quirk(uaa, UQ_MSC_EJECT_HUAWEISCSI2)) method = U3GINIT_HUAWEISCSI2; else if (usb_test_quirk(uaa, UQ_MSC_EJECT_TCT)) method = U3GINIT_TCT; else if (usbd_lookup_id_by_uaa(u3g_devs, sizeof(u3g_devs), uaa) == 0) method = USB_GET_DRIVER_INFO(uaa); else return; /* no device match */ if (bootverbose) { printf("Ejecting %s %s using method %ld\n", usb_get_manufacturer(udev), usb_get_product(udev), method); } switch (method) { case U3GINIT_HUAWEI: error = u3g_huawei_init(udev); break; case U3GINIT_HUAWEISCSI: error = usb_msc_eject(udev, 0, MSC_EJECT_HUAWEI); break; case U3GINIT_HUAWEISCSI2: error = usb_msc_eject(udev, 0, MSC_EJECT_HUAWEI2); break; case U3GINIT_SCSIEJECT: error = usb_msc_eject(udev, 0, MSC_EJECT_STOPUNIT); break; case U3GINIT_REZERO: error = usb_msc_eject(udev, 0, MSC_EJECT_REZERO); break; case U3GINIT_ZTESTOR: error = usb_msc_eject(udev, 0, MSC_EJECT_STOPUNIT); if (error == 0) error = usb_msc_eject(udev, 0, MSC_EJECT_ZTESTOR); break; case U3GINIT_CMOTECH: error = usb_msc_eject(udev, 0, MSC_EJECT_CMOTECH); break; case U3GINIT_TCT: error = usb_msc_eject(udev, 0, MSC_EJECT_TCT); break; case U3GINIT_SIERRA: error = u3g_sierra_init(udev); break; case U3GINIT_WAIT: /* Just pretend we ejected, the card will timeout */ error = 0; break; default: /* no 3G eject quirks */ error = EOPNOTSUPP; break; } if (error == 0) { /* success, mark the udev as disappearing */ uaa->dev_state = UAA_DEV_EJECTING; } } static int u3g_driver_loaded(struct module *mod, int what, void *arg) { switch (what) { case MOD_LOAD: /* register our autoinstall handler */ u3g_etag = EVENTHANDLER_REGISTER(usb_dev_configured, u3g_test_autoinst, NULL, EVENTHANDLER_PRI_ANY); break; case MOD_UNLOAD: EVENTHANDLER_DEREGISTER(usb_dev_configured, u3g_etag); break; default: return (EOPNOTSUPP); } return (0); } static int u3g_probe(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); if (uaa->usb_mode != USB_MODE_HOST) { return (ENXIO); } if (uaa->info.bConfigIndex != U3G_CONFIG_INDEX) { return (ENXIO); } if (uaa->info.bInterfaceClass != UICLASS_VENDOR) { return (ENXIO); } return (usbd_lookup_id_by_uaa(u3g_devs, sizeof(u3g_devs), uaa)); } static int u3g_attach(device_t dev) { struct usb_config u3g_config_tmp[U3G_N_TRANSFER]; struct usb_attach_arg *uaa = device_get_ivars(dev); struct u3g_softc *sc = device_get_softc(dev); struct usb_interface *iface; struct usb_interface_descriptor *id; uint32_t iface_valid; int error, type, nports; int ep, n; uint8_t i; DPRINTF("sc=%p\n", sc); type = USB_GET_DRIVER_INFO(uaa); if (type == U3GINIT_SAEL_M460 || usb_test_quirk(uaa, UQ_MSC_EJECT_SAEL_M460)) { u3g_sael_m460_init(uaa->device); } /* copy in USB config */ for (n = 0; n != U3G_N_TRANSFER; n++) u3g_config_tmp[n] = u3g_config[n]; device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "u3g", NULL, MTX_DEF); ucom_ref(&sc->sc_super_ucom); sc->sc_udev = uaa->device; /* Claim all interfaces on the device */ iface_valid = 0; for (i = uaa->info.bIfaceIndex; i < USB_IFACE_MAX; i++) { iface = usbd_get_iface(uaa->device, i); if (iface == NULL) break; id = usbd_get_interface_descriptor(iface); if (id == NULL || id->bInterfaceClass != UICLASS_VENDOR) continue; usbd_set_parent_iface(uaa->device, i, uaa->info.bIfaceIndex); iface_valid |= (1<device, &i, sc->sc_xfer[nports], u3g_config_tmp, U3G_N_TRANSFER, &sc->sc_ucom[nports], &sc->sc_mtx); if (error) { /* next interface */ i++; ep = 0; continue; } iface = usbd_get_iface(uaa->device, i); id = usbd_get_interface_descriptor(iface); sc->sc_iface[nports] = id->bInterfaceNumber; if (bootverbose && sc->sc_xfer[nports][U3G_INTR]) { device_printf(dev, "port %d supports modem control\n", nports); } /* set stall by default */ mtx_lock(&sc->sc_mtx); usbd_xfer_set_stall(sc->sc_xfer[nports][U3G_BULK_WR]); usbd_xfer_set_stall(sc->sc_xfer[nports][U3G_BULK_RD]); mtx_unlock(&sc->sc_mtx); nports++; /* found one port */ ep++; if (nports == U3G_MAXPORTS) break; } if (nports == 0) { device_printf(dev, "no ports found\n"); goto detach; } sc->sc_numports = nports; error = ucom_attach(&sc->sc_super_ucom, sc->sc_ucom, sc->sc_numports, sc, &u3g_callback, &sc->sc_mtx); if (error) { DPRINTF("ucom_attach failed\n"); goto detach; } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, dev); device_printf(dev, "Found %u port%s.\n", sc->sc_numports, sc->sc_numports > 1 ? "s":""); return (0); detach: u3g_detach(dev); return (ENXIO); } static int u3g_detach(device_t dev) { struct u3g_softc *sc = device_get_softc(dev); uint8_t subunit; DPRINTF("sc=%p\n", sc); /* NOTE: It is not dangerous to detach more ports than attached! */ ucom_detach(&sc->sc_super_ucom, sc->sc_ucom); for (subunit = 0; subunit != U3G_MAXPORTS; subunit++) usbd_transfer_unsetup(sc->sc_xfer[subunit], U3G_N_TRANSFER); device_claim_softc(dev); u3g_free_softc(sc); return (0); } UCOM_UNLOAD_DRAIN(u3g); static void u3g_free_softc(struct u3g_softc *sc) { if (ucom_unref(&sc->sc_super_ucom)) { mtx_destroy(&sc->sc_mtx); device_free_softc(sc); } } static void u3g_free(struct ucom_softc *ucom) { u3g_free_softc(ucom->sc_parent); } static void u3g_start_read(struct ucom_softc *ucom) { struct u3g_softc *sc = ucom->sc_parent; /* start interrupt endpoint (if configured) */ usbd_transfer_start(sc->sc_xfer[ucom->sc_subunit][U3G_INTR]); /* start read endpoint */ usbd_transfer_start(sc->sc_xfer[ucom->sc_subunit][U3G_BULK_RD]); } static void u3g_stop_read(struct ucom_softc *ucom) { struct u3g_softc *sc = ucom->sc_parent; /* stop interrupt endpoint (if configured) */ usbd_transfer_stop(sc->sc_xfer[ucom->sc_subunit][U3G_INTR]); /* stop read endpoint */ usbd_transfer_stop(sc->sc_xfer[ucom->sc_subunit][U3G_BULK_RD]); } static void u3g_start_write(struct ucom_softc *ucom) { struct u3g_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[ucom->sc_subunit][U3G_BULK_WR]); } static void u3g_stop_write(struct ucom_softc *ucom) { struct u3g_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[ucom->sc_subunit][U3G_BULK_WR]); } static void u3g_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct ucom_softc *ucom = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint32_t actlen; uint32_t frame; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: case USB_ST_SETUP: tr_setup: for (frame = 0; frame != U3G_TXFRAMES; frame++) { usbd_xfer_set_frame_offset(xfer, frame * U3G_TXSIZE, frame); pc = usbd_xfer_get_frame(xfer, frame); if (ucom_get_data(ucom, pc, 0, U3G_TXSIZE, &actlen) == 0) break; usbd_xfer_set_frame_len(xfer, frame, actlen); } if (frame != 0) { usbd_xfer_set_frames(xfer, frame); usbd_transfer_submit(xfer); } break; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* do a builtin clear-stall */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void u3g_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct ucom_softc *ucom = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); ucom_put_data(ucom, pc, 0, actlen); case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* do a builtin clear-stall */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void u3g_cfg_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr) { struct u3g_softc *sc = ucom->sc_parent; *lsr = sc->sc_lsr[ucom->sc_subunit]; *msr = sc->sc_msr[ucom->sc_subunit]; } static void u3g_cfg_set_line(struct ucom_softc *ucom) { struct u3g_softc *sc = ucom->sc_parent; struct usb_device_request req; req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SET_CONTROL_LINE_STATE; USETW(req.wValue, sc->sc_line[ucom->sc_subunit]); req.wIndex[0] = sc->sc_iface[ucom->sc_subunit]; req.wIndex[1] = 0; USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, ucom, &req, NULL, 0, 1000); } static void u3g_cfg_set_dtr(struct ucom_softc *ucom, uint8_t onoff) { struct u3g_softc *sc = ucom->sc_parent; DPRINTF("onoff = %d\n", onoff); if (onoff) sc->sc_line[ucom->sc_subunit] |= UCDC_LINE_DTR; else sc->sc_line[ucom->sc_subunit] &= ~UCDC_LINE_DTR; u3g_cfg_set_line(ucom); } static void u3g_cfg_set_rts(struct ucom_softc *ucom, uint8_t onoff) { struct u3g_softc *sc = ucom->sc_parent; DPRINTF("onoff = %d\n", onoff); if (onoff) sc->sc_line[ucom->sc_subunit] |= UCDC_LINE_RTS; else sc->sc_line[ucom->sc_subunit] &= ~UCDC_LINE_RTS; u3g_cfg_set_line(ucom); } static void u3g_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct ucom_softc *ucom = usbd_xfer_softc(xfer); struct u3g_softc *sc = ucom->sc_parent; struct usb_page_cache *pc; struct usb_cdc_notification pkt; int actlen; uint16_t wLen; uint8_t mstatus; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen < 8) { /* usb_cdc_notification with 2 data bytes */ DPRINTF("message too short (expected 8, received %d)\n", actlen); goto tr_setup; } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, &pkt, actlen); wLen = UGETW(pkt.wLength); if (wLen < 2) { DPRINTF("message too short (expected 2 data bytes, received %d)\n", wLen); goto tr_setup; } if (pkt.bmRequestType == UCDC_NOTIFICATION && pkt.bNotification == UCDC_N_SERIAL_STATE) { /* * Set the serial state in ucom driver based on * the bits from the notify message */ DPRINTF("notify bytes = 0x%02x, 0x%02x\n", pkt.data[0], pkt.data[1]); /* currently, lsr is always zero. */ sc->sc_lsr[ucom->sc_subunit] = 0; sc->sc_msr[ucom->sc_subunit] = 0; mstatus = pkt.data[0]; if (mstatus & UCDC_N_SERIAL_RI) sc->sc_msr[ucom->sc_subunit] |= SER_RI; if (mstatus & UCDC_N_SERIAL_DSR) sc->sc_msr[ucom->sc_subunit] |= SER_DSR; if (mstatus & UCDC_N_SERIAL_DCD) sc->sc_msr[ucom->sc_subunit] |= SER_DCD; ucom_status_change(ucom); } case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void u3g_poll(struct ucom_softc *ucom) { struct u3g_softc *sc = ucom->sc_parent; usbd_transfer_poll(sc->sc_xfer[ucom->sc_subunit], U3G_N_TRANSFER); } Index: head/sys/dev/usb/serial/ubsa.c =================================================================== --- head/sys/dev/usb/serial/ubsa.c (revision 276700) +++ head/sys/dev/usb/serial/ubsa.c (revision 276701) @@ -1,689 +1,689 @@ /*- * Copyright (c) 2002, Alexander Kabaev . * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /*- * Copyright (c) 2001 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Ichiro FUKUHARA (ichiro@ichiro.org). * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR ubsa_debug #include #include #include #ifdef USB_DEBUG static int ubsa_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, ubsa, CTLFLAG_RW, 0, "USB ubsa"); -SYSCTL_INT(_hw_usb_ubsa, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_ubsa, OID_AUTO, debug, CTLFLAG_RWTUN, &ubsa_debug, 0, "ubsa debug level"); #endif #define UBSA_BSIZE 1024 /* bytes */ #define UBSA_CONFIG_INDEX 0 #define UBSA_IFACE_INDEX 0 #define UBSA_REG_BAUDRATE 0x00 #define UBSA_REG_STOP_BITS 0x01 #define UBSA_REG_DATA_BITS 0x02 #define UBSA_REG_PARITY 0x03 #define UBSA_REG_DTR 0x0A #define UBSA_REG_RTS 0x0B #define UBSA_REG_BREAK 0x0C #define UBSA_REG_FLOW_CTRL 0x10 #define UBSA_PARITY_NONE 0x00 #define UBSA_PARITY_EVEN 0x01 #define UBSA_PARITY_ODD 0x02 #define UBSA_PARITY_MARK 0x03 #define UBSA_PARITY_SPACE 0x04 #define UBSA_FLOW_NONE 0x0000 #define UBSA_FLOW_OCTS 0x0001 #define UBSA_FLOW_ODSR 0x0002 #define UBSA_FLOW_IDSR 0x0004 #define UBSA_FLOW_IDTR 0x0008 #define UBSA_FLOW_IRTS 0x0010 #define UBSA_FLOW_ORTS 0x0020 #define UBSA_FLOW_UNKNOWN 0x0040 #define UBSA_FLOW_OXON 0x0080 #define UBSA_FLOW_IXON 0x0100 /* line status register */ #define UBSA_LSR_TSRE 0x40 /* Transmitter empty: byte sent */ #define UBSA_LSR_TXRDY 0x20 /* Transmitter buffer empty */ #define UBSA_LSR_BI 0x10 /* Break detected */ #define UBSA_LSR_FE 0x08 /* Framing error: bad stop bit */ #define UBSA_LSR_PE 0x04 /* Parity error */ #define UBSA_LSR_OE 0x02 /* Overrun, lost incoming byte */ #define UBSA_LSR_RXRDY 0x01 /* Byte ready in Receive Buffer */ #define UBSA_LSR_RCV_MASK 0x1f /* Mask for incoming data or error */ /* modem status register */ /* All deltas are from the last read of the MSR. */ #define UBSA_MSR_DCD 0x80 /* Current Data Carrier Detect */ #define UBSA_MSR_RI 0x40 /* Current Ring Indicator */ #define UBSA_MSR_DSR 0x20 /* Current Data Set Ready */ #define UBSA_MSR_CTS 0x10 /* Current Clear to Send */ #define UBSA_MSR_DDCD 0x08 /* DCD has changed state */ #define UBSA_MSR_TERI 0x04 /* RI has toggled low to high */ #define UBSA_MSR_DDSR 0x02 /* DSR has changed state */ #define UBSA_MSR_DCTS 0x01 /* CTS has changed state */ enum { UBSA_BULK_DT_WR, UBSA_BULK_DT_RD, UBSA_INTR_DT_RD, UBSA_N_TRANSFER, }; struct ubsa_softc { struct ucom_super_softc sc_super_ucom; struct ucom_softc sc_ucom; struct usb_xfer *sc_xfer[UBSA_N_TRANSFER]; struct usb_device *sc_udev; struct mtx sc_mtx; uint8_t sc_iface_no; /* interface number */ uint8_t sc_iface_index; /* interface index */ uint8_t sc_lsr; /* local status register */ uint8_t sc_msr; /* UBSA status register */ }; static device_probe_t ubsa_probe; static device_attach_t ubsa_attach; static device_detach_t ubsa_detach; static void ubsa_free_softc(struct ubsa_softc *); static usb_callback_t ubsa_write_callback; static usb_callback_t ubsa_read_callback; static usb_callback_t ubsa_intr_callback; static void ubsa_cfg_request(struct ubsa_softc *, uint8_t, uint16_t); static void ubsa_free(struct ucom_softc *); static void ubsa_cfg_set_dtr(struct ucom_softc *, uint8_t); static void ubsa_cfg_set_rts(struct ucom_softc *, uint8_t); static void ubsa_cfg_set_break(struct ucom_softc *, uint8_t); static int ubsa_pre_param(struct ucom_softc *, struct termios *); static void ubsa_cfg_param(struct ucom_softc *, struct termios *); static void ubsa_start_read(struct ucom_softc *); static void ubsa_stop_read(struct ucom_softc *); static void ubsa_start_write(struct ucom_softc *); static void ubsa_stop_write(struct ucom_softc *); static void ubsa_cfg_get_status(struct ucom_softc *, uint8_t *, uint8_t *); static void ubsa_poll(struct ucom_softc *ucom); static const struct usb_config ubsa_config[UBSA_N_TRANSFER] = { [UBSA_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = UBSA_BSIZE, /* bytes */ .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = &ubsa_write_callback, }, [UBSA_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = UBSA_BSIZE, /* bytes */ .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &ubsa_read_callback, }, [UBSA_INTR_DT_RD] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = &ubsa_intr_callback, }, }; static const struct ucom_callback ubsa_callback = { .ucom_cfg_get_status = &ubsa_cfg_get_status, .ucom_cfg_set_dtr = &ubsa_cfg_set_dtr, .ucom_cfg_set_rts = &ubsa_cfg_set_rts, .ucom_cfg_set_break = &ubsa_cfg_set_break, .ucom_cfg_param = &ubsa_cfg_param, .ucom_pre_param = &ubsa_pre_param, .ucom_start_read = &ubsa_start_read, .ucom_stop_read = &ubsa_stop_read, .ucom_start_write = &ubsa_start_write, .ucom_stop_write = &ubsa_stop_write, .ucom_poll = &ubsa_poll, .ucom_free = &ubsa_free, }; static const STRUCT_USB_HOST_ID ubsa_devs[] = { /* AnyData ADU-500A */ {USB_VPI(USB_VENDOR_ANYDATA, USB_PRODUCT_ANYDATA_ADU_500A, 0)}, /* AnyData ADU-E100A/H */ {USB_VPI(USB_VENDOR_ANYDATA, USB_PRODUCT_ANYDATA_ADU_E100X, 0)}, /* Axesstel MV100H */ {USB_VPI(USB_VENDOR_AXESSTEL, USB_PRODUCT_AXESSTEL_DATAMODEM, 0)}, /* BELKIN F5U103 */ {USB_VPI(USB_VENDOR_BELKIN, USB_PRODUCT_BELKIN_F5U103, 0)}, /* BELKIN F5U120 */ {USB_VPI(USB_VENDOR_BELKIN, USB_PRODUCT_BELKIN_F5U120, 0)}, /* GoHubs GO-COM232 */ {USB_VPI(USB_VENDOR_ETEK, USB_PRODUCT_ETEK_1COM, 0)}, /* GoHubs GO-COM232 */ {USB_VPI(USB_VENDOR_GOHUBS, USB_PRODUCT_GOHUBS_GOCOM232, 0)}, /* Peracom */ {USB_VPI(USB_VENDOR_PERACOM, USB_PRODUCT_PERACOM_SERIAL1, 0)}, }; static device_method_t ubsa_methods[] = { DEVMETHOD(device_probe, ubsa_probe), DEVMETHOD(device_attach, ubsa_attach), DEVMETHOD(device_detach, ubsa_detach), DEVMETHOD_END }; static devclass_t ubsa_devclass; static driver_t ubsa_driver = { .name = "ubsa", .methods = ubsa_methods, .size = sizeof(struct ubsa_softc), }; DRIVER_MODULE(ubsa, uhub, ubsa_driver, ubsa_devclass, NULL, 0); MODULE_DEPEND(ubsa, ucom, 1, 1, 1); MODULE_DEPEND(ubsa, usb, 1, 1, 1); MODULE_VERSION(ubsa, 1); static int ubsa_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) { return (ENXIO); } if (uaa->info.bConfigIndex != UBSA_CONFIG_INDEX) { return (ENXIO); } if (uaa->info.bIfaceIndex != UBSA_IFACE_INDEX) { return (ENXIO); } return (usbd_lookup_id_by_uaa(ubsa_devs, sizeof(ubsa_devs), uaa)); } static int ubsa_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct ubsa_softc *sc = device_get_softc(dev); int error; DPRINTF("sc=%p\n", sc); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "ubsa", NULL, MTX_DEF); ucom_ref(&sc->sc_super_ucom); sc->sc_udev = uaa->device; sc->sc_iface_no = uaa->info.bIfaceNum; sc->sc_iface_index = UBSA_IFACE_INDEX; error = usbd_transfer_setup(uaa->device, &sc->sc_iface_index, sc->sc_xfer, ubsa_config, UBSA_N_TRANSFER, sc, &sc->sc_mtx); if (error) { DPRINTF("could not allocate all pipes\n"); goto detach; } /* clear stall at first run */ mtx_lock(&sc->sc_mtx); usbd_xfer_set_stall(sc->sc_xfer[UBSA_BULK_DT_WR]); usbd_xfer_set_stall(sc->sc_xfer[UBSA_BULK_DT_RD]); mtx_unlock(&sc->sc_mtx); error = ucom_attach(&sc->sc_super_ucom, &sc->sc_ucom, 1, sc, &ubsa_callback, &sc->sc_mtx); if (error) { DPRINTF("ucom_attach failed\n"); goto detach; } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, dev); return (0); detach: ubsa_detach(dev); return (ENXIO); } static int ubsa_detach(device_t dev) { struct ubsa_softc *sc = device_get_softc(dev); DPRINTF("sc=%p\n", sc); ucom_detach(&sc->sc_super_ucom, &sc->sc_ucom); usbd_transfer_unsetup(sc->sc_xfer, UBSA_N_TRANSFER); device_claim_softc(dev); ubsa_free_softc(sc); return (0); } UCOM_UNLOAD_DRAIN(ubsa); static void ubsa_free_softc(struct ubsa_softc *sc) { if (ucom_unref(&sc->sc_super_ucom)) { mtx_destroy(&sc->sc_mtx); device_free_softc(sc); } } static void ubsa_free(struct ucom_softc *ucom) { ubsa_free_softc(ucom->sc_parent); } static void ubsa_cfg_request(struct ubsa_softc *sc, uint8_t index, uint16_t value) { struct usb_device_request req; usb_error_t err; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = index; USETW(req.wValue, value); req.wIndex[0] = sc->sc_iface_no; req.wIndex[1] = 0; USETW(req.wLength, 0); err = ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); if (err) { DPRINTFN(0, "device request failed, err=%s " "(ignored)\n", usbd_errstr(err)); } } static void ubsa_cfg_set_dtr(struct ucom_softc *ucom, uint8_t onoff) { struct ubsa_softc *sc = ucom->sc_parent; DPRINTF("onoff = %d\n", onoff); ubsa_cfg_request(sc, UBSA_REG_DTR, onoff ? 1 : 0); } static void ubsa_cfg_set_rts(struct ucom_softc *ucom, uint8_t onoff) { struct ubsa_softc *sc = ucom->sc_parent; DPRINTF("onoff = %d\n", onoff); ubsa_cfg_request(sc, UBSA_REG_RTS, onoff ? 1 : 0); } static void ubsa_cfg_set_break(struct ucom_softc *ucom, uint8_t onoff) { struct ubsa_softc *sc = ucom->sc_parent; DPRINTF("onoff = %d\n", onoff); ubsa_cfg_request(sc, UBSA_REG_BREAK, onoff ? 1 : 0); } static int ubsa_pre_param(struct ucom_softc *ucom, struct termios *t) { DPRINTF("sc = %p\n", ucom->sc_parent); switch (t->c_ospeed) { case B0: case B300: case B600: case B1200: case B2400: case B4800: case B9600: case B19200: case B38400: case B57600: case B115200: case B230400: break; default: return (EINVAL); } return (0); } static void ubsa_cfg_param(struct ucom_softc *ucom, struct termios *t) { struct ubsa_softc *sc = ucom->sc_parent; uint16_t value = 0; DPRINTF("sc = %p\n", sc); switch (t->c_ospeed) { case B0: ubsa_cfg_request(sc, UBSA_REG_FLOW_CTRL, 0); ubsa_cfg_set_dtr(&sc->sc_ucom, 0); ubsa_cfg_set_rts(&sc->sc_ucom, 0); break; case B300: case B600: case B1200: case B2400: case B4800: case B9600: case B19200: case B38400: case B57600: case B115200: case B230400: value = B230400 / t->c_ospeed; ubsa_cfg_request(sc, UBSA_REG_BAUDRATE, value); break; default: return; } if (t->c_cflag & PARENB) value = (t->c_cflag & PARODD) ? UBSA_PARITY_ODD : UBSA_PARITY_EVEN; else value = UBSA_PARITY_NONE; ubsa_cfg_request(sc, UBSA_REG_PARITY, value); switch (t->c_cflag & CSIZE) { case CS5: value = 0; break; case CS6: value = 1; break; case CS7: value = 2; break; default: case CS8: value = 3; break; } ubsa_cfg_request(sc, UBSA_REG_DATA_BITS, value); value = (t->c_cflag & CSTOPB) ? 1 : 0; ubsa_cfg_request(sc, UBSA_REG_STOP_BITS, value); value = 0; if (t->c_cflag & CRTSCTS) value |= UBSA_FLOW_OCTS | UBSA_FLOW_IRTS; if (t->c_iflag & (IXON | IXOFF)) value |= UBSA_FLOW_OXON | UBSA_FLOW_IXON; ubsa_cfg_request(sc, UBSA_REG_FLOW_CTRL, value); } static void ubsa_start_read(struct ucom_softc *ucom) { struct ubsa_softc *sc = ucom->sc_parent; /* start interrupt endpoint */ usbd_transfer_start(sc->sc_xfer[UBSA_INTR_DT_RD]); /* start read endpoint */ usbd_transfer_start(sc->sc_xfer[UBSA_BULK_DT_RD]); } static void ubsa_stop_read(struct ucom_softc *ucom) { struct ubsa_softc *sc = ucom->sc_parent; /* stop interrupt endpoint */ usbd_transfer_stop(sc->sc_xfer[UBSA_INTR_DT_RD]); /* stop read endpoint */ usbd_transfer_stop(sc->sc_xfer[UBSA_BULK_DT_RD]); } static void ubsa_start_write(struct ucom_softc *ucom) { struct ubsa_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[UBSA_BULK_DT_WR]); } static void ubsa_stop_write(struct ucom_softc *ucom) { struct ubsa_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[UBSA_BULK_DT_WR]); } static void ubsa_cfg_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr) { struct ubsa_softc *sc = ucom->sc_parent; DPRINTF("\n"); *lsr = sc->sc_lsr; *msr = sc->sc_msr; } static void ubsa_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct ubsa_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint32_t actlen; switch (USB_GET_STATE(xfer)) { case USB_ST_SETUP: case USB_ST_TRANSFERRED: tr_setup: pc = usbd_xfer_get_frame(xfer, 0); if (ucom_get_data(&sc->sc_ucom, pc, 0, UBSA_BSIZE, &actlen)) { usbd_xfer_set_frame_len(xfer, 0, actlen); usbd_transfer_submit(xfer); } return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void ubsa_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct ubsa_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); ucom_put_data(&sc->sc_ucom, pc, 0, actlen); case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void ubsa_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct ubsa_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint8_t buf[4]; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen >= (int)sizeof(buf)) { pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, buf, sizeof(buf)); /* * incidentally, Belkin adapter status bits match * UART 16550 bits */ sc->sc_lsr = buf[2]; sc->sc_msr = buf[3]; DPRINTF("lsr = 0x%02x, msr = 0x%02x\n", sc->sc_lsr, sc->sc_msr); ucom_status_change(&sc->sc_ucom); } else { DPRINTF("ignoring short packet, %d bytes\n", actlen); } case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void ubsa_poll(struct ucom_softc *ucom) { struct ubsa_softc *sc = ucom->sc_parent; usbd_transfer_poll(sc->sc_xfer, UBSA_N_TRANSFER); } Index: head/sys/dev/usb/serial/ubser.c =================================================================== --- head/sys/dev/usb/serial/ubser.c (revision 276700) +++ head/sys/dev/usb/serial/ubser.c (revision 276701) @@ -1,559 +1,559 @@ /*- * Copyright (c) 2004 Bernd Walter * * $URL: https://devel.bwct.de/svn/projects/ubser/ubser.c $ * $Date: 2004-02-29 01:53:10 +0100 (Sun, 29 Feb 2004) $ * $Author: ticso $ * $Rev: 1127 $ */ /*- * Copyright (c) 2001-2002, Shunsuke Akiyama . * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /*- * Copyright (c) 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Lennart Augustsson (lennart@augustsson.net). * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * BWCT serial adapter driver */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR ubser_debug #include #include #include #define UBSER_UNIT_MAX 32 /* Vendor Interface Requests */ #define VENDOR_GET_NUMSER 0x01 #define VENDOR_SET_BREAK 0x02 #define VENDOR_CLEAR_BREAK 0x03 #ifdef USB_DEBUG static int ubser_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, ubser, CTLFLAG_RW, 0, "USB ubser"); -SYSCTL_INT(_hw_usb_ubser, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_ubser, OID_AUTO, debug, CTLFLAG_RWTUN, &ubser_debug, 0, "ubser debug level"); #endif enum { UBSER_BULK_DT_WR, UBSER_BULK_DT_RD, UBSER_N_TRANSFER, }; struct ubser_softc { struct ucom_super_softc sc_super_ucom; struct ucom_softc sc_ucom[UBSER_UNIT_MAX]; struct usb_xfer *sc_xfer[UBSER_N_TRANSFER]; struct usb_device *sc_udev; struct mtx sc_mtx; uint16_t sc_tx_size; uint8_t sc_numser; uint8_t sc_iface_no; uint8_t sc_iface_index; uint8_t sc_curr_tx_unit; }; /* prototypes */ static device_probe_t ubser_probe; static device_attach_t ubser_attach; static device_detach_t ubser_detach; static void ubser_free_softc(struct ubser_softc *); static usb_callback_t ubser_write_callback; static usb_callback_t ubser_read_callback; static void ubser_free(struct ucom_softc *); static int ubser_pre_param(struct ucom_softc *, struct termios *); static void ubser_cfg_set_break(struct ucom_softc *, uint8_t); static void ubser_cfg_get_status(struct ucom_softc *, uint8_t *, uint8_t *); static void ubser_start_read(struct ucom_softc *); static void ubser_stop_read(struct ucom_softc *); static void ubser_start_write(struct ucom_softc *); static void ubser_stop_write(struct ucom_softc *); static void ubser_poll(struct ucom_softc *ucom); static const struct usb_config ubser_config[UBSER_N_TRANSFER] = { [UBSER_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = 0, /* use wMaxPacketSize */ .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = &ubser_write_callback, }, [UBSER_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = 0, /* use wMaxPacketSize */ .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &ubser_read_callback, }, }; static const struct ucom_callback ubser_callback = { .ucom_cfg_set_break = &ubser_cfg_set_break, .ucom_cfg_get_status = &ubser_cfg_get_status, .ucom_pre_param = &ubser_pre_param, .ucom_start_read = &ubser_start_read, .ucom_stop_read = &ubser_stop_read, .ucom_start_write = &ubser_start_write, .ucom_stop_write = &ubser_stop_write, .ucom_poll = &ubser_poll, .ucom_free = &ubser_free, }; static device_method_t ubser_methods[] = { DEVMETHOD(device_probe, ubser_probe), DEVMETHOD(device_attach, ubser_attach), DEVMETHOD(device_detach, ubser_detach), DEVMETHOD_END }; static devclass_t ubser_devclass; static driver_t ubser_driver = { .name = "ubser", .methods = ubser_methods, .size = sizeof(struct ubser_softc), }; DRIVER_MODULE(ubser, uhub, ubser_driver, ubser_devclass, NULL, 0); MODULE_DEPEND(ubser, ucom, 1, 1, 1); MODULE_DEPEND(ubser, usb, 1, 1, 1); MODULE_VERSION(ubser, 1); static int ubser_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) { return (ENXIO); } /* check if this is a BWCT vendor specific ubser interface */ if ((strcmp(usb_get_manufacturer(uaa->device), "BWCT") == 0) && (uaa->info.bInterfaceClass == 0xff) && (uaa->info.bInterfaceSubClass == 0x00)) return (0); return (ENXIO); } static int ubser_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct ubser_softc *sc = device_get_softc(dev); struct usb_device_request req; uint8_t n; int error; device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "ubser", NULL, MTX_DEF); ucom_ref(&sc->sc_super_ucom); sc->sc_iface_no = uaa->info.bIfaceNum; sc->sc_iface_index = uaa->info.bIfaceIndex; sc->sc_udev = uaa->device; /* get number of serials */ req.bmRequestType = UT_READ_VENDOR_INTERFACE; req.bRequest = VENDOR_GET_NUMSER; USETW(req.wValue, 0); req.wIndex[0] = sc->sc_iface_no; req.wIndex[1] = 0; USETW(req.wLength, 1); error = usbd_do_request_flags(uaa->device, NULL, &req, &sc->sc_numser, 0, NULL, USB_DEFAULT_TIMEOUT); if (error || (sc->sc_numser == 0)) { device_printf(dev, "failed to get number " "of serial ports: %s\n", usbd_errstr(error)); goto detach; } if (sc->sc_numser > UBSER_UNIT_MAX) sc->sc_numser = UBSER_UNIT_MAX; device_printf(dev, "found %i serials\n", sc->sc_numser); error = usbd_transfer_setup(uaa->device, &sc->sc_iface_index, sc->sc_xfer, ubser_config, UBSER_N_TRANSFER, sc, &sc->sc_mtx); if (error) { goto detach; } sc->sc_tx_size = usbd_xfer_max_len(sc->sc_xfer[UBSER_BULK_DT_WR]); if (sc->sc_tx_size == 0) { DPRINTFN(0, "invalid tx_size\n"); goto detach; } /* initialize port numbers */ for (n = 0; n < sc->sc_numser; n++) { sc->sc_ucom[n].sc_portno = n; } error = ucom_attach(&sc->sc_super_ucom, sc->sc_ucom, sc->sc_numser, sc, &ubser_callback, &sc->sc_mtx); if (error) { goto detach; } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, dev); mtx_lock(&sc->sc_mtx); usbd_xfer_set_stall(sc->sc_xfer[UBSER_BULK_DT_WR]); usbd_xfer_set_stall(sc->sc_xfer[UBSER_BULK_DT_RD]); usbd_transfer_start(sc->sc_xfer[UBSER_BULK_DT_RD]); mtx_unlock(&sc->sc_mtx); return (0); /* success */ detach: ubser_detach(dev); return (ENXIO); /* failure */ } static int ubser_detach(device_t dev) { struct ubser_softc *sc = device_get_softc(dev); DPRINTF("\n"); ucom_detach(&sc->sc_super_ucom, sc->sc_ucom); usbd_transfer_unsetup(sc->sc_xfer, UBSER_N_TRANSFER); device_claim_softc(dev); ubser_free_softc(sc); return (0); } UCOM_UNLOAD_DRAIN(ubser); static void ubser_free_softc(struct ubser_softc *sc) { if (ucom_unref(&sc->sc_super_ucom)) { mtx_destroy(&sc->sc_mtx); device_free_softc(sc); } } static void ubser_free(struct ucom_softc *ucom) { ubser_free_softc(ucom->sc_parent); } static int ubser_pre_param(struct ucom_softc *ucom, struct termios *t) { DPRINTF("\n"); /* * The firmware on our devices can only do 8n1@9600bps * without handshake. * We refuse to accept other configurations. */ /* ensure 9600bps */ switch (t->c_ospeed) { case 9600: break; default: return (EINVAL); } /* 2 stop bits not possible */ if (t->c_cflag & CSTOPB) return (EINVAL); /* XXX parity handling not possible with current firmware */ if (t->c_cflag & PARENB) return (EINVAL); /* we can only do 8 data bits */ switch (t->c_cflag & CSIZE) { case CS8: break; default: return (EINVAL); } /* we can't do any kind of hardware handshaking */ if ((t->c_cflag & (CRTS_IFLOW | CDTR_IFLOW | CDSR_OFLOW | CCAR_OFLOW)) != 0) return (EINVAL); /* * XXX xon/xoff not supported by the firmware! * This is handled within FreeBSD only and may overflow buffers * because of delayed reaction due to device buffering. */ return (0); } static __inline void ubser_inc_tx_unit(struct ubser_softc *sc) { sc->sc_curr_tx_unit++; if (sc->sc_curr_tx_unit >= sc->sc_numser) { sc->sc_curr_tx_unit = 0; } } static void ubser_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct ubser_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint8_t buf[1]; uint8_t first_unit = sc->sc_curr_tx_unit; uint32_t actlen; switch (USB_GET_STATE(xfer)) { case USB_ST_SETUP: case USB_ST_TRANSFERRED: tr_setup: pc = usbd_xfer_get_frame(xfer, 0); do { if (ucom_get_data(sc->sc_ucom + sc->sc_curr_tx_unit, pc, 1, sc->sc_tx_size - 1, &actlen)) { buf[0] = sc->sc_curr_tx_unit; usbd_copy_in(pc, 0, buf, 1); usbd_xfer_set_frame_len(xfer, 0, actlen + 1); usbd_transfer_submit(xfer); ubser_inc_tx_unit(sc); /* round robin */ break; } ubser_inc_tx_unit(sc); } while (sc->sc_curr_tx_unit != first_unit); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void ubser_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct ubser_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint8_t buf[1]; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen < 1) { DPRINTF("invalid actlen=0!\n"); goto tr_setup; } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, buf, 1); if (buf[0] >= sc->sc_numser) { DPRINTF("invalid serial number!\n"); goto tr_setup; } ucom_put_data(sc->sc_ucom + buf[0], pc, 1, actlen - 1); case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void ubser_cfg_set_break(struct ucom_softc *ucom, uint8_t onoff) { struct ubser_softc *sc = ucom->sc_parent; uint8_t x = ucom->sc_portno; struct usb_device_request req; usb_error_t err; if (onoff) { req.bmRequestType = UT_READ_VENDOR_INTERFACE; req.bRequest = VENDOR_SET_BREAK; req.wValue[0] = x; req.wValue[1] = 0; req.wIndex[0] = sc->sc_iface_no; req.wIndex[1] = 0; USETW(req.wLength, 0); err = ucom_cfg_do_request(sc->sc_udev, ucom, &req, NULL, 0, 1000); if (err) { DPRINTFN(0, "send break failed, error=%s\n", usbd_errstr(err)); } } } static void ubser_cfg_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr) { /* fake status bits */ *lsr = 0; *msr = SER_DCD; } static void ubser_start_read(struct ucom_softc *ucom) { struct ubser_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[UBSER_BULK_DT_RD]); } static void ubser_stop_read(struct ucom_softc *ucom) { struct ubser_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[UBSER_BULK_DT_RD]); } static void ubser_start_write(struct ucom_softc *ucom) { struct ubser_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[UBSER_BULK_DT_WR]); } static void ubser_stop_write(struct ucom_softc *ucom) { struct ubser_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[UBSER_BULK_DT_WR]); } static void ubser_poll(struct ucom_softc *ucom) { struct ubser_softc *sc = ucom->sc_parent; usbd_transfer_poll(sc->sc_xfer, UBSER_N_TRANSFER); } Index: head/sys/dev/usb/serial/uchcom.c =================================================================== --- head/sys/dev/usb/serial/uchcom.c (revision 276700) +++ head/sys/dev/usb/serial/uchcom.c (revision 276701) @@ -1,876 +1,876 @@ /* $NetBSD: uchcom.c,v 1.1 2007/09/03 17:57:37 tshiozak Exp $ */ /*- * Copyright (c) 2007, Takanori Watanabe * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Copyright (c) 2007 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Takuya SHIOZAKI (tshiozak@netbsd.org). * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * Driver for WinChipHead CH341/340, the worst USB-serial chip in the * world. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR uchcom_debug #include #include #include #ifdef USB_DEBUG static int uchcom_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, uchcom, CTLFLAG_RW, 0, "USB uchcom"); -SYSCTL_INT(_hw_usb_uchcom, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_uchcom, OID_AUTO, debug, CTLFLAG_RWTUN, &uchcom_debug, 0, "uchcom debug level"); #endif #define UCHCOM_IFACE_INDEX 0 #define UCHCOM_CONFIG_INDEX 0 #define UCHCOM_REV_CH340 0x0250 #define UCHCOM_INPUT_BUF_SIZE 8 #define UCHCOM_REQ_GET_VERSION 0x5F #define UCHCOM_REQ_READ_REG 0x95 #define UCHCOM_REQ_WRITE_REG 0x9A #define UCHCOM_REQ_RESET 0xA1 #define UCHCOM_REQ_SET_DTRRTS 0xA4 #define UCHCOM_REG_STAT1 0x06 #define UCHCOM_REG_STAT2 0x07 #define UCHCOM_REG_BPS_PRE 0x12 #define UCHCOM_REG_BPS_DIV 0x13 #define UCHCOM_REG_BPS_MOD 0x14 #define UCHCOM_REG_BPS_PAD 0x0F #define UCHCOM_REG_BREAK1 0x05 #define UCHCOM_REG_BREAK2 0x18 #define UCHCOM_REG_LCR1 0x18 #define UCHCOM_REG_LCR2 0x25 #define UCHCOM_VER_20 0x20 #define UCHCOM_BASE_UNKNOWN 0 #define UCHCOM_BPS_MOD_BASE 20000000 #define UCHCOM_BPS_MOD_BASE_OFS 1100 #define UCHCOM_DTR_MASK 0x20 #define UCHCOM_RTS_MASK 0x40 #define UCHCOM_BRK1_MASK 0x01 #define UCHCOM_BRK2_MASK 0x40 #define UCHCOM_LCR1_MASK 0xAF #define UCHCOM_LCR2_MASK 0x07 #define UCHCOM_LCR1_PARENB 0x80 #define UCHCOM_LCR2_PAREVEN 0x07 #define UCHCOM_LCR2_PARODD 0x06 #define UCHCOM_LCR2_PARMARK 0x05 #define UCHCOM_LCR2_PARSPACE 0x04 #define UCHCOM_INTR_STAT1 0x02 #define UCHCOM_INTR_STAT2 0x03 #define UCHCOM_INTR_LEAST 4 #define UCHCOM_BULK_BUF_SIZE 1024 /* bytes */ enum { UCHCOM_BULK_DT_WR, UCHCOM_BULK_DT_RD, UCHCOM_INTR_DT_RD, UCHCOM_N_TRANSFER, }; struct uchcom_softc { struct ucom_super_softc sc_super_ucom; struct ucom_softc sc_ucom; struct usb_xfer *sc_xfer[UCHCOM_N_TRANSFER]; struct usb_device *sc_udev; struct mtx sc_mtx; uint8_t sc_dtr; /* local copy */ uint8_t sc_rts; /* local copy */ uint8_t sc_version; uint8_t sc_msr; uint8_t sc_lsr; /* local status register */ }; struct uchcom_divider { uint8_t dv_prescaler; uint8_t dv_div; uint8_t dv_mod; }; struct uchcom_divider_record { uint32_t dvr_high; uint32_t dvr_low; uint32_t dvr_base_clock; struct uchcom_divider dvr_divider; }; static const struct uchcom_divider_record dividers[] = { {307200, 307200, UCHCOM_BASE_UNKNOWN, {7, 0xD9, 0}}, {921600, 921600, UCHCOM_BASE_UNKNOWN, {7, 0xF3, 0}}, {2999999, 23530, 6000000, {3, 0, 0}}, {23529, 2942, 750000, {2, 0, 0}}, {2941, 368, 93750, {1, 0, 0}}, {367, 1, 11719, {0, 0, 0}}, }; #define NUM_DIVIDERS (sizeof (dividers) / sizeof (dividers[0])) static const STRUCT_USB_HOST_ID uchcom_devs[] = { {USB_VPI(USB_VENDOR_WCH, USB_PRODUCT_WCH_CH341SER, 0)}, {USB_VPI(USB_VENDOR_WCH2, USB_PRODUCT_WCH2_CH341SER, 0)}, {USB_VPI(USB_VENDOR_WCH2, USB_PRODUCT_WCH2_CH341SER_2, 0)}, }; /* protypes */ static void uchcom_free(struct ucom_softc *); static int uchcom_pre_param(struct ucom_softc *, struct termios *); static void uchcom_cfg_get_status(struct ucom_softc *, uint8_t *, uint8_t *); static void uchcom_cfg_open(struct ucom_softc *ucom); static void uchcom_cfg_param(struct ucom_softc *, struct termios *); static void uchcom_cfg_set_break(struct ucom_softc *, uint8_t); static void uchcom_cfg_set_dtr(struct ucom_softc *, uint8_t); static void uchcom_cfg_set_rts(struct ucom_softc *, uint8_t); static void uchcom_start_read(struct ucom_softc *); static void uchcom_start_write(struct ucom_softc *); static void uchcom_stop_read(struct ucom_softc *); static void uchcom_stop_write(struct ucom_softc *); static void uchcom_update_version(struct uchcom_softc *); static void uchcom_convert_status(struct uchcom_softc *, uint8_t); static void uchcom_update_status(struct uchcom_softc *); static void uchcom_set_dtr_rts(struct uchcom_softc *); static int uchcom_calc_divider_settings(struct uchcom_divider *, uint32_t); static void uchcom_set_baudrate(struct uchcom_softc *, uint32_t); static void uchcom_poll(struct ucom_softc *ucom); static device_probe_t uchcom_probe; static device_attach_t uchcom_attach; static device_detach_t uchcom_detach; static void uchcom_free_softc(struct uchcom_softc *); static usb_callback_t uchcom_intr_callback; static usb_callback_t uchcom_write_callback; static usb_callback_t uchcom_read_callback; static const struct usb_config uchcom_config_data[UCHCOM_N_TRANSFER] = { [UCHCOM_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = UCHCOM_BULK_BUF_SIZE, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = &uchcom_write_callback, }, [UCHCOM_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = UCHCOM_BULK_BUF_SIZE, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &uchcom_read_callback, }, [UCHCOM_INTR_DT_RD] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = &uchcom_intr_callback, }, }; static struct ucom_callback uchcom_callback = { .ucom_cfg_get_status = &uchcom_cfg_get_status, .ucom_cfg_set_dtr = &uchcom_cfg_set_dtr, .ucom_cfg_set_rts = &uchcom_cfg_set_rts, .ucom_cfg_set_break = &uchcom_cfg_set_break, .ucom_cfg_open = &uchcom_cfg_open, .ucom_cfg_param = &uchcom_cfg_param, .ucom_pre_param = &uchcom_pre_param, .ucom_start_read = &uchcom_start_read, .ucom_stop_read = &uchcom_stop_read, .ucom_start_write = &uchcom_start_write, .ucom_stop_write = &uchcom_stop_write, .ucom_poll = &uchcom_poll, .ucom_free = &uchcom_free, }; /* ---------------------------------------------------------------------- * driver entry points */ static int uchcom_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); DPRINTFN(11, "\n"); if (uaa->usb_mode != USB_MODE_HOST) { return (ENXIO); } if (uaa->info.bConfigIndex != UCHCOM_CONFIG_INDEX) { return (ENXIO); } if (uaa->info.bIfaceIndex != UCHCOM_IFACE_INDEX) { return (ENXIO); } return (usbd_lookup_id_by_uaa(uchcom_devs, sizeof(uchcom_devs), uaa)); } static int uchcom_attach(device_t dev) { struct uchcom_softc *sc = device_get_softc(dev); struct usb_attach_arg *uaa = device_get_ivars(dev); int error; uint8_t iface_index; DPRINTFN(11, "\n"); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "uchcom", NULL, MTX_DEF); ucom_ref(&sc->sc_super_ucom); sc->sc_udev = uaa->device; switch (uaa->info.bcdDevice) { case UCHCOM_REV_CH340: device_printf(dev, "CH340 detected\n"); break; default: device_printf(dev, "CH341 detected\n"); break; } iface_index = UCHCOM_IFACE_INDEX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, uchcom_config_data, UCHCOM_N_TRANSFER, sc, &sc->sc_mtx); if (error) { DPRINTF("one or more missing USB endpoints, " "error=%s\n", usbd_errstr(error)); goto detach; } /* clear stall at first run */ mtx_lock(&sc->sc_mtx); usbd_xfer_set_stall(sc->sc_xfer[UCHCOM_BULK_DT_WR]); usbd_xfer_set_stall(sc->sc_xfer[UCHCOM_BULK_DT_RD]); mtx_unlock(&sc->sc_mtx); error = ucom_attach(&sc->sc_super_ucom, &sc->sc_ucom, 1, sc, &uchcom_callback, &sc->sc_mtx); if (error) { goto detach; } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, dev); return (0); detach: uchcom_detach(dev); return (ENXIO); } static int uchcom_detach(device_t dev) { struct uchcom_softc *sc = device_get_softc(dev); DPRINTFN(11, "\n"); ucom_detach(&sc->sc_super_ucom, &sc->sc_ucom); usbd_transfer_unsetup(sc->sc_xfer, UCHCOM_N_TRANSFER); device_claim_softc(dev); uchcom_free_softc(sc); return (0); } UCOM_UNLOAD_DRAIN(uchcom); static void uchcom_free_softc(struct uchcom_softc *sc) { if (ucom_unref(&sc->sc_super_ucom)) { mtx_destroy(&sc->sc_mtx); device_free_softc(sc); } } static void uchcom_free(struct ucom_softc *ucom) { uchcom_free_softc(ucom->sc_parent); } /* ---------------------------------------------------------------------- * low level i/o */ static void uchcom_ctrl_write(struct uchcom_softc *sc, uint8_t reqno, uint16_t value, uint16_t index) { struct usb_device_request req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = reqno; USETW(req.wValue, value); USETW(req.wIndex, index); USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); } static void uchcom_ctrl_read(struct uchcom_softc *sc, uint8_t reqno, uint16_t value, uint16_t index, void *buf, uint16_t buflen) { struct usb_device_request req; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = reqno; USETW(req.wValue, value); USETW(req.wIndex, index); USETW(req.wLength, buflen); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, buf, USB_SHORT_XFER_OK, 1000); } static void uchcom_write_reg(struct uchcom_softc *sc, uint8_t reg1, uint8_t val1, uint8_t reg2, uint8_t val2) { DPRINTF("0x%02X<-0x%02X, 0x%02X<-0x%02X\n", (unsigned)reg1, (unsigned)val1, (unsigned)reg2, (unsigned)val2); uchcom_ctrl_write( sc, UCHCOM_REQ_WRITE_REG, reg1 | ((uint16_t)reg2 << 8), val1 | ((uint16_t)val2 << 8)); } static void uchcom_read_reg(struct uchcom_softc *sc, uint8_t reg1, uint8_t *rval1, uint8_t reg2, uint8_t *rval2) { uint8_t buf[UCHCOM_INPUT_BUF_SIZE]; uchcom_ctrl_read( sc, UCHCOM_REQ_READ_REG, reg1 | ((uint16_t)reg2 << 8), 0, buf, sizeof(buf)); DPRINTF("0x%02X->0x%02X, 0x%02X->0x%02X\n", (unsigned)reg1, (unsigned)buf[0], (unsigned)reg2, (unsigned)buf[1]); if (rval1) *rval1 = buf[0]; if (rval2) *rval2 = buf[1]; } static void uchcom_get_version(struct uchcom_softc *sc, uint8_t *rver) { uint8_t buf[UCHCOM_INPUT_BUF_SIZE]; uchcom_ctrl_read(sc, UCHCOM_REQ_GET_VERSION, 0, 0, buf, sizeof(buf)); if (rver) *rver = buf[0]; } static void uchcom_get_status(struct uchcom_softc *sc, uint8_t *rval) { uchcom_read_reg(sc, UCHCOM_REG_STAT1, rval, UCHCOM_REG_STAT2, NULL); } static void uchcom_set_dtr_rts_10(struct uchcom_softc *sc, uint8_t val) { uchcom_write_reg(sc, UCHCOM_REG_STAT1, val, UCHCOM_REG_STAT1, val); } static void uchcom_set_dtr_rts_20(struct uchcom_softc *sc, uint8_t val) { uchcom_ctrl_write(sc, UCHCOM_REQ_SET_DTRRTS, val, 0); } /* ---------------------------------------------------------------------- * middle layer */ static void uchcom_update_version(struct uchcom_softc *sc) { uchcom_get_version(sc, &sc->sc_version); } static void uchcom_convert_status(struct uchcom_softc *sc, uint8_t cur) { sc->sc_dtr = !(cur & UCHCOM_DTR_MASK); sc->sc_rts = !(cur & UCHCOM_RTS_MASK); cur = ~cur & 0x0F; sc->sc_msr = (cur << 4) | ((sc->sc_msr >> 4) ^ cur); } static void uchcom_update_status(struct uchcom_softc *sc) { uint8_t cur; uchcom_get_status(sc, &cur); uchcom_convert_status(sc, cur); } static void uchcom_set_dtr_rts(struct uchcom_softc *sc) { uint8_t val = 0; if (sc->sc_dtr) val |= UCHCOM_DTR_MASK; if (sc->sc_rts) val |= UCHCOM_RTS_MASK; if (sc->sc_version < UCHCOM_VER_20) uchcom_set_dtr_rts_10(sc, ~val); else uchcom_set_dtr_rts_20(sc, ~val); } static void uchcom_cfg_set_break(struct ucom_softc *ucom, uint8_t onoff) { struct uchcom_softc *sc = ucom->sc_parent; uint8_t brk1; uint8_t brk2; uchcom_read_reg(sc, UCHCOM_REG_BREAK1, &brk1, UCHCOM_REG_BREAK2, &brk2); if (onoff) { /* on - clear bits */ brk1 &= ~UCHCOM_BRK1_MASK; brk2 &= ~UCHCOM_BRK2_MASK; } else { /* off - set bits */ brk1 |= UCHCOM_BRK1_MASK; brk2 |= UCHCOM_BRK2_MASK; } uchcom_write_reg(sc, UCHCOM_REG_BREAK1, brk1, UCHCOM_REG_BREAK2, brk2); } static int uchcom_calc_divider_settings(struct uchcom_divider *dp, uint32_t rate) { const struct uchcom_divider_record *rp; uint32_t div; uint32_t rem; uint32_t mod; uint8_t i; /* find record */ for (i = 0; i != NUM_DIVIDERS; i++) { if (dividers[i].dvr_high >= rate && dividers[i].dvr_low <= rate) { rp = ÷rs[i]; goto found; } } return (-1); found: dp->dv_prescaler = rp->dvr_divider.dv_prescaler; if (rp->dvr_base_clock == UCHCOM_BASE_UNKNOWN) dp->dv_div = rp->dvr_divider.dv_div; else { div = rp->dvr_base_clock / rate; rem = rp->dvr_base_clock % rate; if (div == 0 || div >= 0xFF) return (-1); if ((rem << 1) >= rate) div += 1; dp->dv_div = (uint8_t)-div; } mod = (UCHCOM_BPS_MOD_BASE / rate) + UCHCOM_BPS_MOD_BASE_OFS; mod = mod + (mod / 2); dp->dv_mod = (mod + 0xFF) / 0x100; return (0); } static void uchcom_set_baudrate(struct uchcom_softc *sc, uint32_t rate) { struct uchcom_divider dv; if (uchcom_calc_divider_settings(&dv, rate)) return; uchcom_write_reg(sc, UCHCOM_REG_BPS_PRE, dv.dv_prescaler, UCHCOM_REG_BPS_DIV, dv.dv_div); uchcom_write_reg(sc, UCHCOM_REG_BPS_MOD, dv.dv_mod, UCHCOM_REG_BPS_PAD, 0); } /* ---------------------------------------------------------------------- * methods for ucom */ static void uchcom_cfg_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr) { struct uchcom_softc *sc = ucom->sc_parent; DPRINTF("\n"); *lsr = sc->sc_lsr; *msr = sc->sc_msr; } static void uchcom_cfg_set_dtr(struct ucom_softc *ucom, uint8_t onoff) { struct uchcom_softc *sc = ucom->sc_parent; DPRINTF("onoff = %d\n", onoff); sc->sc_dtr = onoff; uchcom_set_dtr_rts(sc); } static void uchcom_cfg_set_rts(struct ucom_softc *ucom, uint8_t onoff) { struct uchcom_softc *sc = ucom->sc_parent; DPRINTF("onoff = %d\n", onoff); sc->sc_rts = onoff; uchcom_set_dtr_rts(sc); } static void uchcom_cfg_open(struct ucom_softc *ucom) { struct uchcom_softc *sc = ucom->sc_parent; DPRINTF("\n"); uchcom_update_version(sc); uchcom_update_status(sc); } static int uchcom_pre_param(struct ucom_softc *ucom, struct termios *t) { struct uchcom_divider dv; switch (t->c_cflag & CSIZE) { case CS8: break; default: return (EIO); } if (uchcom_calc_divider_settings(&dv, t->c_ospeed)) { return (EIO); } return (0); /* success */ } static void uchcom_cfg_param(struct ucom_softc *ucom, struct termios *t) { struct uchcom_softc *sc = ucom->sc_parent; uchcom_get_version(sc, 0); uchcom_ctrl_write(sc, UCHCOM_REQ_RESET, 0, 0); uchcom_set_baudrate(sc, t->c_ospeed); uchcom_read_reg(sc, 0x18, 0, 0x25, 0); uchcom_write_reg(sc, 0x18, 0x50, 0x25, 0x00); uchcom_update_status(sc); uchcom_ctrl_write(sc, UCHCOM_REQ_RESET, 0x501f, 0xd90a); uchcom_set_baudrate(sc, t->c_ospeed); uchcom_set_dtr_rts(sc); uchcom_update_status(sc); } static void uchcom_start_read(struct ucom_softc *ucom) { struct uchcom_softc *sc = ucom->sc_parent; /* start interrupt endpoint */ usbd_transfer_start(sc->sc_xfer[UCHCOM_INTR_DT_RD]); /* start read endpoint */ usbd_transfer_start(sc->sc_xfer[UCHCOM_BULK_DT_RD]); } static void uchcom_stop_read(struct ucom_softc *ucom) { struct uchcom_softc *sc = ucom->sc_parent; /* stop interrupt endpoint */ usbd_transfer_stop(sc->sc_xfer[UCHCOM_INTR_DT_RD]); /* stop read endpoint */ usbd_transfer_stop(sc->sc_xfer[UCHCOM_BULK_DT_RD]); } static void uchcom_start_write(struct ucom_softc *ucom) { struct uchcom_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[UCHCOM_BULK_DT_WR]); } static void uchcom_stop_write(struct ucom_softc *ucom) { struct uchcom_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[UCHCOM_BULK_DT_WR]); } /* ---------------------------------------------------------------------- * callback when the modem status is changed. */ static void uchcom_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct uchcom_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint8_t buf[UCHCOM_INTR_LEAST]; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTF("actlen = %u\n", actlen); if (actlen >= UCHCOM_INTR_LEAST) { pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, buf, UCHCOM_INTR_LEAST); DPRINTF("data = 0x%02X 0x%02X 0x%02X 0x%02X\n", (unsigned)buf[0], (unsigned)buf[1], (unsigned)buf[2], (unsigned)buf[3]); uchcom_convert_status(sc, buf[UCHCOM_INTR_STAT1]); ucom_status_change(&sc->sc_ucom); } case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void uchcom_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct uchcom_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint32_t actlen; switch (USB_GET_STATE(xfer)) { case USB_ST_SETUP: case USB_ST_TRANSFERRED: tr_setup: pc = usbd_xfer_get_frame(xfer, 0); if (ucom_get_data(&sc->sc_ucom, pc, 0, usbd_xfer_max_len(xfer), &actlen)) { DPRINTF("actlen = %d\n", actlen); usbd_xfer_set_frame_len(xfer, 0, actlen); usbd_transfer_submit(xfer); } break; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void uchcom_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct uchcom_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen > 0) { pc = usbd_xfer_get_frame(xfer, 0); ucom_put_data(&sc->sc_ucom, pc, 0, actlen); } case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void uchcom_poll(struct ucom_softc *ucom) { struct uchcom_softc *sc = ucom->sc_parent; usbd_transfer_poll(sc->sc_xfer, UCHCOM_N_TRANSFER); } static device_method_t uchcom_methods[] = { /* Device interface */ DEVMETHOD(device_probe, uchcom_probe), DEVMETHOD(device_attach, uchcom_attach), DEVMETHOD(device_detach, uchcom_detach), DEVMETHOD_END }; static driver_t uchcom_driver = { .name = "uchcom", .methods = uchcom_methods, .size = sizeof(struct uchcom_softc) }; static devclass_t uchcom_devclass; DRIVER_MODULE(uchcom, uhub, uchcom_driver, uchcom_devclass, NULL, 0); MODULE_DEPEND(uchcom, ucom, 1, 1, 1); MODULE_DEPEND(uchcom, usb, 1, 1, 1); MODULE_VERSION(uchcom, 1); Index: head/sys/dev/usb/serial/uftdi.c =================================================================== --- head/sys/dev/usb/serial/uftdi.c (revision 276700) +++ head/sys/dev/usb/serial/uftdi.c (revision 276701) @@ -1,1881 +1,1881 @@ /* $NetBSD: uftdi.c,v 1.13 2002/09/23 05:51:23 simonb Exp $ */ /*- * Copyright (c) 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Lennart Augustsson (lennart@augustsson.net). * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * NOTE: all function names beginning like "uftdi_cfg_" can only * be called from within the config thread function ! */ /* * FTDI FT232x, FT2232x, FT4232x, FT8U100AX and FT8U232xM serial adapters. * * Note that we specifically do not do a reset or otherwise alter the state of * the chip during attach, detach, open, and close, because it could be * pre-initialized (via an attached serial eeprom) to power-on into a mode such * as bitbang in which the pins are being driven to a specific state which we * must not perturb. The device gets reset at power-on, and doesn't need to be * reset again after that to function, except as directed by ioctl() calls. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR uftdi_debug #include #include #include #include #include static SYSCTL_NODE(_hw_usb, OID_AUTO, uftdi, CTLFLAG_RW, 0, "USB uftdi"); #ifdef USB_DEBUG static int uftdi_debug = 0; -SYSCTL_INT(_hw_usb_uftdi, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_uftdi, OID_AUTO, debug, CTLFLAG_RWTUN, &uftdi_debug, 0, "Debug level"); #endif #define UFTDI_CONFIG_INDEX 0 /* * IO buffer sizes and FTDI device procotol sizes. * * Note that the output packet size in the following defines is not the usb * protocol packet size based on bus speed, it is the size dictated by the FTDI * device itself, and is used only on older chips. * * We allocate buffers bigger than the hardware's packet size, and process * multiple packets within each buffer. This allows the controller to make * optimal use of the usb bus by conducting multiple transfers with the device * during a single bus timeslice to fill or drain the chip's fifos. * * The output data on newer chips has no packet header, and we are able to pack * any number of output bytes into a buffer. On some older chips, each output * packet contains a 1-byte header and up to 63 bytes of payload. The size is * encoded in 6 bits of the header, hence the 64-byte limit on packet size. We * loop to fill the buffer with many of these header+payload packets. * * The input data on all chips consists of packets which contain a 2-byte header * followed by data payload. The total size of the packet is wMaxPacketSize * which can change based on the bus speed (e.g., 64 for full speed, 512 for * high speed). We loop to extract the headers and payloads from the packets * packed into an input buffer. */ #define UFTDI_IBUFSIZE 2048 #define UFTDI_IHDRSIZE 2 #define UFTDI_OBUFSIZE 2048 #define UFTDI_OPKTSIZE 64 enum { UFTDI_BULK_DT_WR, UFTDI_BULK_DT_RD, UFTDI_N_TRANSFER, }; enum { DEVT_SIO, DEVT_232A, DEVT_232B, DEVT_2232D, /* Includes 2232C */ DEVT_232R, DEVT_2232H, DEVT_4232H, DEVT_232H, DEVT_230X, }; #define DEVF_BAUDBITS_HINDEX 0x01 /* Baud bits in high byte of index. */ #define DEVF_BAUDCLK_12M 0X02 /* Base baud clock is 12MHz. */ struct uftdi_softc { struct ucom_super_softc sc_super_ucom; struct ucom_softc sc_ucom; struct usb_device *sc_udev; struct usb_xfer *sc_xfer[UFTDI_N_TRANSFER]; device_t sc_dev; struct mtx sc_mtx; uint32_t sc_unit; uint16_t sc_last_lcr; uint16_t sc_bcdDevice; uint8_t sc_devtype; uint8_t sc_devflags; uint8_t sc_hdrlen; uint8_t sc_msr; uint8_t sc_lsr; }; struct uftdi_param_config { uint16_t baud_lobits; uint16_t baud_hibits; uint16_t lcr; uint8_t v_start; uint8_t v_stop; uint8_t v_flow; }; /* prototypes */ static device_probe_t uftdi_probe; static device_attach_t uftdi_attach; static device_detach_t uftdi_detach; static void uftdi_free_softc(struct uftdi_softc *); static usb_callback_t uftdi_write_callback; static usb_callback_t uftdi_read_callback; static void uftdi_free(struct ucom_softc *); static void uftdi_cfg_open(struct ucom_softc *); static void uftdi_cfg_close(struct ucom_softc *); static void uftdi_cfg_set_dtr(struct ucom_softc *, uint8_t); static void uftdi_cfg_set_rts(struct ucom_softc *, uint8_t); static void uftdi_cfg_set_break(struct ucom_softc *, uint8_t); static int uftdi_set_parm_soft(struct ucom_softc *, struct termios *, struct uftdi_param_config *); static int uftdi_pre_param(struct ucom_softc *, struct termios *); static void uftdi_cfg_param(struct ucom_softc *, struct termios *); static void uftdi_cfg_get_status(struct ucom_softc *, uint8_t *, uint8_t *); static int uftdi_reset(struct ucom_softc *, int); static int uftdi_set_bitmode(struct ucom_softc *, uint8_t, uint8_t); static int uftdi_get_bitmode(struct ucom_softc *, uint8_t *); static int uftdi_set_latency(struct ucom_softc *, int); static int uftdi_get_latency(struct ucom_softc *, int *); static int uftdi_set_event_char(struct ucom_softc *, int); static int uftdi_set_error_char(struct ucom_softc *, int); static int uftdi_ioctl(struct ucom_softc *, uint32_t, caddr_t, int, struct thread *); static void uftdi_start_read(struct ucom_softc *); static void uftdi_stop_read(struct ucom_softc *); static void uftdi_start_write(struct ucom_softc *); static void uftdi_stop_write(struct ucom_softc *); static void uftdi_poll(struct ucom_softc *ucom); static const struct usb_config uftdi_config[UFTDI_N_TRANSFER] = { [UFTDI_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = UFTDI_OBUFSIZE, .flags = {.pipe_bof = 1,}, .callback = &uftdi_write_callback, }, [UFTDI_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = UFTDI_IBUFSIZE, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &uftdi_read_callback, }, }; static const struct ucom_callback uftdi_callback = { .ucom_cfg_get_status = &uftdi_cfg_get_status, .ucom_cfg_set_dtr = &uftdi_cfg_set_dtr, .ucom_cfg_set_rts = &uftdi_cfg_set_rts, .ucom_cfg_set_break = &uftdi_cfg_set_break, .ucom_cfg_param = &uftdi_cfg_param, .ucom_cfg_open = &uftdi_cfg_open, .ucom_cfg_close = &uftdi_cfg_close, .ucom_pre_param = &uftdi_pre_param, .ucom_ioctl = &uftdi_ioctl, .ucom_start_read = &uftdi_start_read, .ucom_stop_read = &uftdi_stop_read, .ucom_start_write = &uftdi_start_write, .ucom_stop_write = &uftdi_stop_write, .ucom_poll = &uftdi_poll, .ucom_free = &uftdi_free, }; static device_method_t uftdi_methods[] = { /* Device interface */ DEVMETHOD(device_probe, uftdi_probe), DEVMETHOD(device_attach, uftdi_attach), DEVMETHOD(device_detach, uftdi_detach), DEVMETHOD_END }; static devclass_t uftdi_devclass; static driver_t uftdi_driver = { .name = "uftdi", .methods = uftdi_methods, .size = sizeof(struct uftdi_softc), }; DRIVER_MODULE(uftdi, uhub, uftdi_driver, uftdi_devclass, NULL, NULL); MODULE_DEPEND(uftdi, ucom, 1, 1, 1); MODULE_DEPEND(uftdi, usb, 1, 1, 1); MODULE_VERSION(uftdi, 1); static const STRUCT_USB_HOST_ID uftdi_devs[] = { #define UFTDI_DEV(v, p, i) \ { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, i) } UFTDI_DEV(ACTON, SPECTRAPRO, 0), UFTDI_DEV(ALTI2, N3, 0), UFTDI_DEV(ANALOGDEVICES, GNICE, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(ANALOGDEVICES, GNICEPLUS, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(ATMEL, STK541, 0), UFTDI_DEV(BAYER, CONTOUR_CABLE, 0), UFTDI_DEV(BBELECTRONICS, 232USB9M, 0), UFTDI_DEV(BBELECTRONICS, 485USB9F_2W, 0), UFTDI_DEV(BBELECTRONICS, 485USB9F_4W, 0), UFTDI_DEV(BBELECTRONICS, 485USBTB_2W, 0), UFTDI_DEV(BBELECTRONICS, 485USBTB_4W, 0), UFTDI_DEV(BBELECTRONICS, TTL3USB9M, 0), UFTDI_DEV(BBELECTRONICS, TTL5USB9M, 0), UFTDI_DEV(BBELECTRONICS, USO9ML2, 0), UFTDI_DEV(BBELECTRONICS, USO9ML2DR, 0), UFTDI_DEV(BBELECTRONICS, USO9ML2DR_2, 0), UFTDI_DEV(BBELECTRONICS, USOPTL4, 0), UFTDI_DEV(BBELECTRONICS, USOPTL4DR, 0), UFTDI_DEV(BBELECTRONICS, USOPTL4DR2, 0), UFTDI_DEV(BBELECTRONICS, USOTL4, 0), UFTDI_DEV(BBELECTRONICS, USPTL4, 0), UFTDI_DEV(BBELECTRONICS, USTL4, 0), UFTDI_DEV(BBELECTRONICS, ZZ_PROG1_USB, 0), UFTDI_DEV(CONTEC, COM1USBH, 0), UFTDI_DEV(DRESDENELEKTRONIK, SENSORTERMINALBOARD, 0), UFTDI_DEV(DRESDENELEKTRONIK, WIRELESSHANDHELDTERMINAL, 0), UFTDI_DEV(DRESDENELEKTRONIK, DE_RFNODE, 0), UFTDI_DEV(DRESDENELEKTRONIK, LEVELSHIFTERSTICKLOWCOST, 0), UFTDI_DEV(ELEKTOR, FT323R, 0), UFTDI_DEV(EVOLUTION, ER1, 0), UFTDI_DEV(EVOLUTION, HYBRID, 0), UFTDI_DEV(EVOLUTION, RCM4, 0), UFTDI_DEV(FALCOM, SAMBA, 0), UFTDI_DEV(FALCOM, TWIST, 0), UFTDI_DEV(FIC, NEO1973_DEBUG, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(FIC, NEO1973_DEBUG, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(FTDI, 232EX, 0), UFTDI_DEV(FTDI, 232H, 0), UFTDI_DEV(FTDI, 232RL, 0), UFTDI_DEV(FTDI, 4N_GALAXY_DE_1, 0), UFTDI_DEV(FTDI, 4N_GALAXY_DE_2, 0), UFTDI_DEV(FTDI, 4N_GALAXY_DE_3, 0), UFTDI_DEV(FTDI, 8U232AM_ALT, 0), UFTDI_DEV(FTDI, ACCESSO, 0), UFTDI_DEV(FTDI, ACG_HFDUAL, 0), UFTDI_DEV(FTDI, ACTIVE_ROBOTS, 0), UFTDI_DEV(FTDI, ACTZWAVE, 0), UFTDI_DEV(FTDI, AMC232, 0), UFTDI_DEV(FTDI, ARTEMIS, 0), UFTDI_DEV(FTDI, ASK_RDR400, 0), UFTDI_DEV(FTDI, ATIK_ATK16, 0), UFTDI_DEV(FTDI, ATIK_ATK16C, 0), UFTDI_DEV(FTDI, ATIK_ATK16HR, 0), UFTDI_DEV(FTDI, ATIK_ATK16HRC, 0), UFTDI_DEV(FTDI, ATIK_ATK16IC, 0), UFTDI_DEV(FTDI, BCS_SE923, 0), UFTDI_DEV(FTDI, CANDAPTER, 0), UFTDI_DEV(FTDI, CANUSB, 0), UFTDI_DEV(FTDI, CCSICDU20_0, 0), UFTDI_DEV(FTDI, CCSICDU40_1, 0), UFTDI_DEV(FTDI, CCSICDU64_4, 0), UFTDI_DEV(FTDI, CCSLOAD_N_GO_3, 0), UFTDI_DEV(FTDI, CCSMACHX_2, 0), UFTDI_DEV(FTDI, CCSPRIME8_5, 0), UFTDI_DEV(FTDI, CFA_631, 0), UFTDI_DEV(FTDI, CFA_632, 0), UFTDI_DEV(FTDI, CFA_633, 0), UFTDI_DEV(FTDI, CFA_634, 0), UFTDI_DEV(FTDI, CFA_635, 0), UFTDI_DEV(FTDI, CHAMSYS_24_MASTER_WING, 0), UFTDI_DEV(FTDI, CHAMSYS_MAXI_WING, 0), UFTDI_DEV(FTDI, CHAMSYS_MEDIA_WING, 0), UFTDI_DEV(FTDI, CHAMSYS_MIDI_TIMECODE, 0), UFTDI_DEV(FTDI, CHAMSYS_MINI_WING, 0), UFTDI_DEV(FTDI, CHAMSYS_PC_WING, 0), UFTDI_DEV(FTDI, CHAMSYS_USB_DMX, 0), UFTDI_DEV(FTDI, CHAMSYS_WING, 0), UFTDI_DEV(FTDI, COM4SM, 0), UFTDI_DEV(FTDI, CONVERTER_0, 0), UFTDI_DEV(FTDI, CONVERTER_1, 0), UFTDI_DEV(FTDI, CONVERTER_2, 0), UFTDI_DEV(FTDI, CONVERTER_3, 0), UFTDI_DEV(FTDI, CONVERTER_4, 0), UFTDI_DEV(FTDI, CONVERTER_5, 0), UFTDI_DEV(FTDI, CONVERTER_6, 0), UFTDI_DEV(FTDI, CONVERTER_7, 0), UFTDI_DEV(FTDI, CTI_USB_MINI_485, 0), UFTDI_DEV(FTDI, CTI_USB_NANO_485, 0), UFTDI_DEV(FTDI, DMX4ALL, 0), UFTDI_DEV(FTDI, DOMINTELL_DGQG, 0), UFTDI_DEV(FTDI, DOMINTELL_DUSB, 0), UFTDI_DEV(FTDI, DOTEC, 0), UFTDI_DEV(FTDI, ECLO_COM_1WIRE, 0), UFTDI_DEV(FTDI, ECO_PRO_CDS, 0), UFTDI_DEV(FTDI, EISCOU, 0), UFTDI_DEV(FTDI, ELSTER_UNICOM, 0), UFTDI_DEV(FTDI, ELV_ALC8500, 0), UFTDI_DEV(FTDI, ELV_CLI7000, 0), UFTDI_DEV(FTDI, ELV_CSI8, 0), UFTDI_DEV(FTDI, ELV_EC3000, 0), UFTDI_DEV(FTDI, ELV_EM1000DL, 0), UFTDI_DEV(FTDI, ELV_EM1010PC, 0), UFTDI_DEV(FTDI, ELV_FEM, 0), UFTDI_DEV(FTDI, ELV_FHZ1000PC, 0), UFTDI_DEV(FTDI, ELV_FHZ1300PC, 0), UFTDI_DEV(FTDI, ELV_FM3RX, 0), UFTDI_DEV(FTDI, ELV_FS20SIG, 0), UFTDI_DEV(FTDI, ELV_HS485, 0), UFTDI_DEV(FTDI, ELV_KL100, 0), UFTDI_DEV(FTDI, ELV_MSM1, 0), UFTDI_DEV(FTDI, ELV_PCD200, 0), UFTDI_DEV(FTDI, ELV_PCK100, 0), UFTDI_DEV(FTDI, ELV_PPS7330, 0), UFTDI_DEV(FTDI, ELV_RFP500, 0), UFTDI_DEV(FTDI, ELV_T1100, 0), UFTDI_DEV(FTDI, ELV_TFD128, 0), UFTDI_DEV(FTDI, ELV_TFM100, 0), UFTDI_DEV(FTDI, ELV_TWS550, 0), UFTDI_DEV(FTDI, ELV_UAD8, 0), UFTDI_DEV(FTDI, ELV_UDA7, 0), UFTDI_DEV(FTDI, ELV_UDF77, 0), UFTDI_DEV(FTDI, ELV_UIO88, 0), UFTDI_DEV(FTDI, ELV_ULA200, 0), UFTDI_DEV(FTDI, ELV_UM100, 0), UFTDI_DEV(FTDI, ELV_UMS100, 0), UFTDI_DEV(FTDI, ELV_UO100, 0), UFTDI_DEV(FTDI, ELV_UR100, 0), UFTDI_DEV(FTDI, ELV_USI2, 0), UFTDI_DEV(FTDI, ELV_USR, 0), UFTDI_DEV(FTDI, ELV_UTP8, 0), UFTDI_DEV(FTDI, ELV_WS300PC, 0), UFTDI_DEV(FTDI, ELV_WS444PC, 0), UFTDI_DEV(FTDI, ELV_WS500, 0), UFTDI_DEV(FTDI, ELV_WS550, 0), UFTDI_DEV(FTDI, ELV_WS777, 0), UFTDI_DEV(FTDI, ELV_WS888, 0), UFTDI_DEV(FTDI, EMCU2D, 0), UFTDI_DEV(FTDI, EMCU2H, 0), UFTDI_DEV(FTDI, FUTURE_0, 0), UFTDI_DEV(FTDI, FUTURE_1, 0), UFTDI_DEV(FTDI, FUTURE_2, 0), UFTDI_DEV(FTDI, GAMMASCOUT, 0), UFTDI_DEV(FTDI, GENERIC, 0), UFTDI_DEV(FTDI, GUDEADS_E808, 0), UFTDI_DEV(FTDI, GUDEADS_E809, 0), UFTDI_DEV(FTDI, GUDEADS_E80A, 0), UFTDI_DEV(FTDI, GUDEADS_E80B, 0), UFTDI_DEV(FTDI, GUDEADS_E80C, 0), UFTDI_DEV(FTDI, GUDEADS_E80D, 0), UFTDI_DEV(FTDI, GUDEADS_E80E, 0), UFTDI_DEV(FTDI, GUDEADS_E80F, 0), UFTDI_DEV(FTDI, GUDEADS_E88D, 0), UFTDI_DEV(FTDI, GUDEADS_E88E, 0), UFTDI_DEV(FTDI, GUDEADS_E88F, 0), UFTDI_DEV(FTDI, HD_RADIO, 0), UFTDI_DEV(FTDI, HO720, 0), UFTDI_DEV(FTDI, HO730, 0), UFTDI_DEV(FTDI, HO820, 0), UFTDI_DEV(FTDI, HO870, 0), UFTDI_DEV(FTDI, IBS_APP70, 0), UFTDI_DEV(FTDI, IBS_PCMCIA, 0), UFTDI_DEV(FTDI, IBS_PEDO, 0), UFTDI_DEV(FTDI, IBS_PICPRO, 0), UFTDI_DEV(FTDI, IBS_PK1, 0), UFTDI_DEV(FTDI, IBS_PROD, 0), UFTDI_DEV(FTDI, IBS_RS232MON, 0), UFTDI_DEV(FTDI, IBS_US485, 0), UFTDI_DEV(FTDI, IPLUS, 0), UFTDI_DEV(FTDI, IPLUS2, 0), UFTDI_DEV(FTDI, IRTRANS, 0), UFTDI_DEV(FTDI, KBS, 0), UFTDI_DEV(FTDI, KTLINK, 0), UFTDI_DEV(FTDI, LENZ_LIUSB, 0), UFTDI_DEV(FTDI, LK202, 0), UFTDI_DEV(FTDI, LK204, 0), UFTDI_DEV(FTDI, LM3S_DEVEL_BOARD, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(FTDI, LM3S_EVAL_BOARD, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(FTDI, LM3S_ICDI_B_BOARD, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(FTDI, MASTERDEVEL2, 0), UFTDI_DEV(FTDI, MAXSTREAM, 0), UFTDI_DEV(FTDI, MHAM_DB9, 0), UFTDI_DEV(FTDI, MHAM_IC, 0), UFTDI_DEV(FTDI, MHAM_KW, 0), UFTDI_DEV(FTDI, MHAM_RS232, 0), UFTDI_DEV(FTDI, MHAM_Y6, 0), UFTDI_DEV(FTDI, MHAM_Y8, 0), UFTDI_DEV(FTDI, MHAM_Y9, 0), UFTDI_DEV(FTDI, MHAM_YS, 0), UFTDI_DEV(FTDI, MICRO_CHAMELEON, 0), UFTDI_DEV(FTDI, MTXORB_5, 0), UFTDI_DEV(FTDI, MTXORB_6, 0), UFTDI_DEV(FTDI, MX2_3, 0), UFTDI_DEV(FTDI, MX4_5, 0), UFTDI_DEV(FTDI, NXTCAM, 0), UFTDI_DEV(FTDI, OCEANIC, 0), UFTDI_DEV(FTDI, OOCDLINK, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(FTDI, OPENDCC, 0), UFTDI_DEV(FTDI, OPENDCC_GATEWAY, 0), UFTDI_DEV(FTDI, OPENDCC_GBM, 0), UFTDI_DEV(FTDI, OPENDCC_SNIFFER, 0), UFTDI_DEV(FTDI, OPENDCC_THROTTLE, 0), UFTDI_DEV(FTDI, PCDJ_DAC2, 0), UFTDI_DEV(FTDI, PCMSFU, 0), UFTDI_DEV(FTDI, PERLE_ULTRAPORT, 0), UFTDI_DEV(FTDI, PHI_FISCO, 0), UFTDI_DEV(FTDI, PIEGROUP, 0), UFTDI_DEV(FTDI, PROPOX_JTAGCABLEII, 0), UFTDI_DEV(FTDI, R2000KU_TRUE_RNG, 0), UFTDI_DEV(FTDI, R2X0, 0), UFTDI_DEV(FTDI, RELAIS, 0), UFTDI_DEV(FTDI, REU_TINY, 0), UFTDI_DEV(FTDI, RMP200, 0), UFTDI_DEV(FTDI, RM_CANVIEW, 0), UFTDI_DEV(FTDI, RRCIRKITS_LOCOBUFFER, 0), UFTDI_DEV(FTDI, SCIENCESCOPE_HS_LOGBOOK, 0), UFTDI_DEV(FTDI, SCIENCESCOPE_LOGBOOKML, 0), UFTDI_DEV(FTDI, SCIENCESCOPE_LS_LOGBOOK, 0), UFTDI_DEV(FTDI, SCS_DEVICE_0, 0), UFTDI_DEV(FTDI, SCS_DEVICE_1, 0), UFTDI_DEV(FTDI, SCS_DEVICE_2, 0), UFTDI_DEV(FTDI, SCS_DEVICE_3, 0), UFTDI_DEV(FTDI, SCS_DEVICE_4, 0), UFTDI_DEV(FTDI, SCS_DEVICE_5, 0), UFTDI_DEV(FTDI, SCS_DEVICE_6, 0), UFTDI_DEV(FTDI, SCS_DEVICE_7, 0), UFTDI_DEV(FTDI, SDMUSBQSS, 0), UFTDI_DEV(FTDI, SEMC_DSS20, 0), UFTDI_DEV(FTDI, SERIAL_2232C, UFTDI_JTAG_CHECK_STRING), UFTDI_DEV(FTDI, SERIAL_2232D, 0), UFTDI_DEV(FTDI, SERIAL_232RL, 0), UFTDI_DEV(FTDI, SERIAL_4232H, 0), UFTDI_DEV(FTDI, SERIAL_8U100AX, 0), UFTDI_DEV(FTDI, SERIAL_8U232AM, 0), UFTDI_DEV(FTDI, SERIAL_8U232AM4, 0), UFTDI_DEV(FTDI, SIGNALYZER_SH2, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(FTDI, SIGNALYZER_SH4, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(FTDI, SIGNALYZER_SLITE, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(FTDI, SIGNALYZER_ST, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(FTDI, SPECIAL_1, 0), UFTDI_DEV(FTDI, SPECIAL_3, 0), UFTDI_DEV(FTDI, SPECIAL_4, 0), UFTDI_DEV(FTDI, SPROG_II, 0), UFTDI_DEV(FTDI, SR_RADIO, 0), UFTDI_DEV(FTDI, SUUNTO_SPORTS, 0), UFTDI_DEV(FTDI, TACTRIX_OPENPORT_13M, 0), UFTDI_DEV(FTDI, TACTRIX_OPENPORT_13S, 0), UFTDI_DEV(FTDI, TACTRIX_OPENPORT_13U, 0), UFTDI_DEV(FTDI, TAVIR_STK500, 0), UFTDI_DEV(FTDI, TERATRONIK_D2XX, 0), UFTDI_DEV(FTDI, TERATRONIK_VCP, 0), UFTDI_DEV(FTDI, THORLABS, 0), UFTDI_DEV(FTDI, TNC_X, 0), UFTDI_DEV(FTDI, TTUSB, 0), UFTDI_DEV(FTDI, TURTELIZER2, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(FTDI, UOPTBR, 0), UFTDI_DEV(FTDI, USBSERIAL, 0), UFTDI_DEV(FTDI, USBX_707, 0), UFTDI_DEV(FTDI, USB_UIRT, 0), UFTDI_DEV(FTDI, USINT_CAT, 0), UFTDI_DEV(FTDI, USINT_RS232, 0), UFTDI_DEV(FTDI, USINT_WKEY, 0), UFTDI_DEV(FTDI, VARDAAN, 0), UFTDI_DEV(FTDI, VNHCPCUSB_D, 0), UFTDI_DEV(FTDI, WESTREX_MODEL_777, 0), UFTDI_DEV(FTDI, WESTREX_MODEL_8900F, 0), UFTDI_DEV(FTDI, XDS100V2, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(FTDI, XDS100V3, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(FTDI, XF_547, 0), UFTDI_DEV(FTDI, XF_640, 0), UFTDI_DEV(FTDI, XF_642, 0), UFTDI_DEV(FTDI, XM_RADIO, 0), UFTDI_DEV(FTDI, YEI_SERVOCENTER31, 0), UFTDI_DEV(GNOTOMETRICS, USB, 0), UFTDI_DEV(ICOM, SP1, 0), UFTDI_DEV(ICOM, OPC_U_UC, 0), UFTDI_DEV(ICOM, RP2C1, 0), UFTDI_DEV(ICOM, RP2C2, 0), UFTDI_DEV(ICOM, RP2D, 0), UFTDI_DEV(ICOM, RP2KVR, 0), UFTDI_DEV(ICOM, RP2KVT, 0), UFTDI_DEV(ICOM, RP2VR, 0), UFTDI_DEV(ICOM, RP2VT, 0), UFTDI_DEV(ICOM, RP4KVR, 0), UFTDI_DEV(ICOM, RP4KVT, 0), UFTDI_DEV(IDTECH, IDT1221U, 0), UFTDI_DEV(INTERBIOMETRICS, IOBOARD, 0), UFTDI_DEV(INTERBIOMETRICS, MINI_IOBOARD, 0), UFTDI_DEV(INTREPIDCS, NEOVI, 0), UFTDI_DEV(INTREPIDCS, VALUECAN, 0), UFTDI_DEV(IONICS, PLUGCOMPUTER, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(JETI, SPC1201, 0), UFTDI_DEV(KOBIL, CONV_B1, 0), UFTDI_DEV(KOBIL, CONV_KAAN, 0), UFTDI_DEV(LARSENBRUSGAARD, ALTITRACK, 0), UFTDI_DEV(MARVELL, SHEEVAPLUG, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0100, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0101, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0102, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0103, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0104, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0105, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0106, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0107, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0108, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0109, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_010A, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_010B, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_010C, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_010D, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_010E, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_010F, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0110, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0111, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0112, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0113, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0114, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0115, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0116, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0117, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0118, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0119, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_011A, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_011B, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_011C, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_011D, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_011E, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_011F, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0120, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0121, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0122, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0123, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0124, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0125, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0126, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0128, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0129, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_012A, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_012B, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_012D, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_012E, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_012F, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0130, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0131, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0132, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0133, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0134, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0135, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0136, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0137, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0138, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0139, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_013A, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_013B, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_013C, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_013D, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_013E, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_013F, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0140, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0141, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0142, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0143, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0144, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0145, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0146, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0147, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0148, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0149, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_014A, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_014B, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_014C, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_014D, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_014E, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_014F, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0150, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0151, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0152, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0159, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_015A, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_015B, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_015C, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_015D, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_015E, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_015F, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0160, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0161, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0162, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0163, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0164, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0165, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0166, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0167, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0168, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0169, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_016A, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_016B, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_016C, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_016D, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_016E, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_016F, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0170, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0171, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0172, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0173, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0174, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0175, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0176, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0177, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0178, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0179, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_017A, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_017B, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_017C, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_017D, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_017E, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_017F, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0180, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0181, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0182, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0183, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0184, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0185, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0186, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0187, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0188, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0189, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_018A, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_018B, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_018C, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_018D, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_018E, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_018F, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0190, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0191, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0192, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0193, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0194, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0195, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0196, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0197, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0198, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_0199, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_019A, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_019B, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_019C, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_019D, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_019E, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_019F, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01A0, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01A1, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01A2, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01A3, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01A4, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01A5, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01A6, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01A7, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01A8, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01A9, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01AA, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01AB, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01AC, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01AD, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01AE, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01AF, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01B0, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01B1, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01B2, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01B3, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01B4, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01B5, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01B6, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01B7, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01B8, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01B9, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01BA, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01BB, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01BC, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01BD, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01BE, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01BF, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01C0, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01C1, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01C2, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01C3, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01C4, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01C5, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01C6, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01C7, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01C8, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01C9, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01CA, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01CB, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01CC, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01CD, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01CE, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01CF, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01D0, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01D1, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01D2, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01D3, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01D4, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01D5, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01D6, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01D7, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01D8, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01D9, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01DA, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01DB, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01DC, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01DD, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01DE, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01DF, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01E0, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01E1, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01E2, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01E3, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01E4, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01E5, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01E6, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01E7, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01E8, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01E9, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01EA, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01EB, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01EC, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01ED, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01EE, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01EF, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01F0, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01F1, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01F2, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01F3, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01F4, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01F5, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01F6, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01F7, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01F8, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01F9, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01FA, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01FB, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01FC, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01FD, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01FE, 0), UFTDI_DEV(MATRIXORBITAL, FTDI_RANGE_01FF, 0), UFTDI_DEV(MATRIXORBITAL, MOUA, 0), UFTDI_DEV(MELCO, PCOPRS1, 0), UFTDI_DEV(METAGEEK, TELLSTICK, 0), UFTDI_DEV(MOBILITY, USB_SERIAL, 0), UFTDI_DEV(OLIMEX, ARM_USB_OCD, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(OLIMEX, ARM_USB_OCD_H, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(OPTO, CRD7734, 0), UFTDI_DEV(OPTO, CRD7734_1, 0), UFTDI_DEV(PAPOUCH, AD4USB, 0), UFTDI_DEV(PAPOUCH, AP485, 0), UFTDI_DEV(PAPOUCH, AP485_2, 0), UFTDI_DEV(PAPOUCH, DRAK5, 0), UFTDI_DEV(PAPOUCH, DRAK6, 0), UFTDI_DEV(PAPOUCH, GMSR, 0), UFTDI_DEV(PAPOUCH, GMUX, 0), UFTDI_DEV(PAPOUCH, IRAMP, 0), UFTDI_DEV(PAPOUCH, LEC, 0), UFTDI_DEV(PAPOUCH, MU, 0), UFTDI_DEV(PAPOUCH, QUIDO10X1, 0), UFTDI_DEV(PAPOUCH, QUIDO2X16, 0), UFTDI_DEV(PAPOUCH, QUIDO2X2, 0), UFTDI_DEV(PAPOUCH, QUIDO30X3, 0), UFTDI_DEV(PAPOUCH, QUIDO3X32, 0), UFTDI_DEV(PAPOUCH, QUIDO4X4, 0), UFTDI_DEV(PAPOUCH, QUIDO60X3, 0), UFTDI_DEV(PAPOUCH, QUIDO8X8, 0), UFTDI_DEV(PAPOUCH, SB232, 0), UFTDI_DEV(PAPOUCH, SB422, 0), UFTDI_DEV(PAPOUCH, SB422_2, 0), UFTDI_DEV(PAPOUCH, SB485, 0), UFTDI_DEV(PAPOUCH, SB485C, 0), UFTDI_DEV(PAPOUCH, SB485S, 0), UFTDI_DEV(PAPOUCH, SB485_2, 0), UFTDI_DEV(PAPOUCH, SIMUKEY, 0), UFTDI_DEV(PAPOUCH, TMU, 0), UFTDI_DEV(PAPOUCH, UPSUSB, 0), UFTDI_DEV(POSIFLEX, PP7000, 0), UFTDI_DEV(QIHARDWARE, JTAGSERIAL, UFTDI_JTAG_IFACE(0)), UFTDI_DEV(RATOC, REXUSB60F, 0), UFTDI_DEV(RTSYSTEMS, CT29B, 0), UFTDI_DEV(RTSYSTEMS, SERIAL_VX7, 0), UFTDI_DEV(SEALEVEL, 2101, 0), UFTDI_DEV(SEALEVEL, 2102, 0), UFTDI_DEV(SEALEVEL, 2103, 0), UFTDI_DEV(SEALEVEL, 2104, 0), UFTDI_DEV(SEALEVEL, 2106, 0), UFTDI_DEV(SEALEVEL, 2201_1, 0), UFTDI_DEV(SEALEVEL, 2201_2, 0), UFTDI_DEV(SEALEVEL, 2202_1, 0), UFTDI_DEV(SEALEVEL, 2202_2, 0), UFTDI_DEV(SEALEVEL, 2203_1, 0), UFTDI_DEV(SEALEVEL, 2203_2, 0), UFTDI_DEV(SEALEVEL, 2401_1, 0), UFTDI_DEV(SEALEVEL, 2401_2, 0), UFTDI_DEV(SEALEVEL, 2401_3, 0), UFTDI_DEV(SEALEVEL, 2401_4, 0), UFTDI_DEV(SEALEVEL, 2402_1, 0), UFTDI_DEV(SEALEVEL, 2402_2, 0), UFTDI_DEV(SEALEVEL, 2402_3, 0), UFTDI_DEV(SEALEVEL, 2402_4, 0), UFTDI_DEV(SEALEVEL, 2403_1, 0), UFTDI_DEV(SEALEVEL, 2403_2, 0), UFTDI_DEV(SEALEVEL, 2403_3, 0), UFTDI_DEV(SEALEVEL, 2403_4, 0), UFTDI_DEV(SEALEVEL, 2801_1, 0), UFTDI_DEV(SEALEVEL, 2801_2, 0), UFTDI_DEV(SEALEVEL, 2801_3, 0), UFTDI_DEV(SEALEVEL, 2801_4, 0), UFTDI_DEV(SEALEVEL, 2801_5, 0), UFTDI_DEV(SEALEVEL, 2801_6, 0), UFTDI_DEV(SEALEVEL, 2801_7, 0), UFTDI_DEV(SEALEVEL, 2801_8, 0), UFTDI_DEV(SEALEVEL, 2802_1, 0), UFTDI_DEV(SEALEVEL, 2802_2, 0), UFTDI_DEV(SEALEVEL, 2802_3, 0), UFTDI_DEV(SEALEVEL, 2802_4, 0), UFTDI_DEV(SEALEVEL, 2802_5, 0), UFTDI_DEV(SEALEVEL, 2802_6, 0), UFTDI_DEV(SEALEVEL, 2802_7, 0), UFTDI_DEV(SEALEVEL, 2802_8, 0), UFTDI_DEV(SEALEVEL, 2803_1, 0), UFTDI_DEV(SEALEVEL, 2803_2, 0), UFTDI_DEV(SEALEVEL, 2803_3, 0), UFTDI_DEV(SEALEVEL, 2803_4, 0), UFTDI_DEV(SEALEVEL, 2803_5, 0), UFTDI_DEV(SEALEVEL, 2803_6, 0), UFTDI_DEV(SEALEVEL, 2803_7, 0), UFTDI_DEV(SEALEVEL, 2803_8, 0), UFTDI_DEV(SIIG2, DK201, 0), UFTDI_DEV(SIIG2, US2308, 0), UFTDI_DEV(TESTO, USB_INTERFACE, 0), UFTDI_DEV(TML, USB_SERIAL, 0), UFTDI_DEV(TTI, QL355P, 0), UFTDI_DEV(UNKNOWN4, NF_RIC, 0), #undef UFTDI_DEV }; /* * Jtag product name strings table. Some products have one or more interfaces * dedicated to jtag or gpio, but use a product ID that's the same as other * products which don't. They are marked with a flag in the table above, and * the following string table is checked for flagged products. The string check * is done with strstr(); in effect there is an implicit wildcard at the * beginning and end of each product name string in table. */ static const struct jtag_by_name { const char * product_name; uint32_t jtag_interfaces; } jtag_products_by_name[] = { /* TI Beaglebone and TI XDS100Vn jtag product line. */ {"XDS100V", UFTDI_JTAG_IFACE(0)}, }; /* * Set up a sysctl and tunable to en/disable the feature of skipping the * creation of tty devices for jtag interfaces. Enabled by default. */ static int skip_jtag_interfaces = 1; SYSCTL_INT(_hw_usb_uftdi, OID_AUTO, skip_jtag_interfaces, CTLFLAG_RWTUN, &skip_jtag_interfaces, 1, "Skip creating tty devices for jtag interfaces"); static boolean_t is_jtag_interface(struct usb_attach_arg *uaa, const struct usb_device_id *id) { int i, iface_bit; const char * product_name; const struct jtag_by_name *jbn; /* We only allocate 8 flag bits for jtag interface flags. */ if (uaa->info.bIfaceIndex >= UFTDI_JTAG_IFACES_MAX) return (0); iface_bit = UFTDI_JTAG_IFACE(uaa->info.bIfaceIndex); /* * If requested, search the name strings table and use the interface * bits from that table when the product name string matches, else use * the jtag interface bits from the main ID table. */ if ((id->driver_info & UFTDI_JTAG_MASK) == UFTDI_JTAG_CHECK_STRING) { product_name = usb_get_product(uaa->device); for (i = 0; i < nitems(jtag_products_by_name); i++) { jbn = &jtag_products_by_name[i]; if (strstr(product_name, jbn->product_name) != NULL && (jbn->jtag_interfaces & iface_bit) != 0) return (1); } } else if ((id->driver_info & iface_bit) != 0) return (1); return (0); } /* * Set up softc fields whose value depends on the device type. * * Note that the 2232C and 2232D devices are the same for our purposes. In the * silicon the difference is that the D series has CPU FIFO mode and C doesn't. * I haven't found any way of determining the C/D difference from info provided * by the chip other than trying to set CPU FIFO mode and having it work or not. * * Due to a hardware bug, a 232B chip without an eeprom reports itself as a * 232A, but if the serial number is also zero we know it's really a 232B. */ static void uftdi_devtype_setup(struct uftdi_softc *sc, struct usb_attach_arg *uaa) { struct usb_device_descriptor *dd; sc->sc_bcdDevice = uaa->info.bcdDevice; switch (uaa->info.bcdDevice) { case 0x200: dd = usbd_get_device_descriptor(sc->sc_udev); if (dd->iSerialNumber == 0) { sc->sc_devtype = DEVT_232B; } else { sc->sc_devtype = DEVT_232A; } sc->sc_ucom.sc_portno = 0; break; case 0x400: sc->sc_devtype = DEVT_232B; sc->sc_ucom.sc_portno = 0; break; case 0x500: sc->sc_devtype = DEVT_2232D; sc->sc_devflags |= DEVF_BAUDBITS_HINDEX; sc->sc_ucom.sc_portno = FTDI_PIT_SIOA + uaa->info.bIfaceNum; break; case 0x600: sc->sc_devtype = DEVT_232R; sc->sc_ucom.sc_portno = 0; break; case 0x700: sc->sc_devtype = DEVT_2232H; sc->sc_devflags |= DEVF_BAUDBITS_HINDEX | DEVF_BAUDCLK_12M; sc->sc_ucom.sc_portno = FTDI_PIT_SIOA + uaa->info.bIfaceNum; break; case 0x800: sc->sc_devtype = DEVT_4232H; sc->sc_devflags |= DEVF_BAUDBITS_HINDEX | DEVF_BAUDCLK_12M; sc->sc_ucom.sc_portno = FTDI_PIT_SIOA + uaa->info.bIfaceNum; break; case 0x900: sc->sc_devtype = DEVT_232H; sc->sc_devflags |= DEVF_BAUDBITS_HINDEX | DEVF_BAUDCLK_12M; sc->sc_ucom.sc_portno = FTDI_PIT_SIOA + uaa->info.bIfaceNum; break; case 0x1000: sc->sc_devtype = DEVT_230X; sc->sc_devflags |= DEVF_BAUDBITS_HINDEX; sc->sc_ucom.sc_portno = FTDI_PIT_SIOA + uaa->info.bIfaceNum; break; default: if (uaa->info.bcdDevice < 0x200) { sc->sc_devtype = DEVT_SIO; sc->sc_hdrlen = 1; } else { sc->sc_devtype = DEVT_232R; device_printf(sc->sc_dev, "Warning: unknown FTDI " "device type, bcdDevice=0x%04x, assuming 232R\n", uaa->info.bcdDevice); } sc->sc_ucom.sc_portno = 0; break; } } static int uftdi_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); const struct usb_device_id *id; if (uaa->usb_mode != USB_MODE_HOST) { return (ENXIO); } if (uaa->info.bConfigIndex != UFTDI_CONFIG_INDEX) { return (ENXIO); } /* * Attach to all present interfaces unless this is a JTAG one, which * we leave for userland. */ id = usbd_lookup_id_by_info(uftdi_devs, sizeof(uftdi_devs), &uaa->info); if (id == NULL) return (ENXIO); if (skip_jtag_interfaces && is_jtag_interface(uaa, id)) { printf("%s: skipping JTAG interface #%d for '%s' at %u.%u\n", device_get_name(dev), uaa->info.bIfaceIndex, usb_get_product(uaa->device), usbd_get_bus_index(uaa->device), usbd_get_device_index(uaa->device)); return (ENXIO); } uaa->driver_info = id->driver_info; return (BUS_PROBE_SPECIFIC); } static int uftdi_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct uftdi_softc *sc = device_get_softc(dev); int error; DPRINTF("\n"); sc->sc_udev = uaa->device; sc->sc_dev = dev; sc->sc_unit = device_get_unit(dev); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "uftdi", NULL, MTX_DEF); ucom_ref(&sc->sc_super_ucom); uftdi_devtype_setup(sc, uaa); error = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex, sc->sc_xfer, uftdi_config, UFTDI_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(dev, "allocating USB " "transfers failed\n"); goto detach; } /* clear stall at first run */ mtx_lock(&sc->sc_mtx); usbd_xfer_set_stall(sc->sc_xfer[UFTDI_BULK_DT_WR]); usbd_xfer_set_stall(sc->sc_xfer[UFTDI_BULK_DT_RD]); mtx_unlock(&sc->sc_mtx); /* set a valid "lcr" value */ sc->sc_last_lcr = (FTDI_SIO_SET_DATA_STOP_BITS_2 | FTDI_SIO_SET_DATA_PARITY_NONE | FTDI_SIO_SET_DATA_BITS(8)); error = ucom_attach(&sc->sc_super_ucom, &sc->sc_ucom, 1, sc, &uftdi_callback, &sc->sc_mtx); if (error) { goto detach; } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, dev); return (0); /* success */ detach: uftdi_detach(dev); return (ENXIO); } static int uftdi_detach(device_t dev) { struct uftdi_softc *sc = device_get_softc(dev); ucom_detach(&sc->sc_super_ucom, &sc->sc_ucom); usbd_transfer_unsetup(sc->sc_xfer, UFTDI_N_TRANSFER); device_claim_softc(dev); uftdi_free_softc(sc); return (0); } UCOM_UNLOAD_DRAIN(uftdi); static void uftdi_free_softc(struct uftdi_softc *sc) { if (ucom_unref(&sc->sc_super_ucom)) { mtx_destroy(&sc->sc_mtx); device_free_softc(sc); } } static void uftdi_free(struct ucom_softc *ucom) { uftdi_free_softc(ucom->sc_parent); } static void uftdi_cfg_open(struct ucom_softc *ucom) { /* * This do-nothing open routine exists for the sole purpose of this * DPRINTF() so that you can see the point at which open gets called * when debugging is enabled. */ DPRINTF(""); } static void uftdi_cfg_close(struct ucom_softc *ucom) { /* * This do-nothing close routine exists for the sole purpose of this * DPRINTF() so that you can see the point at which close gets called * when debugging is enabled. */ DPRINTF(""); } static void uftdi_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct uftdi_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint32_t pktlen; uint32_t buflen; uint8_t buf[1]; switch (USB_GET_STATE(xfer)) { default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); } /* FALLTHROUGH */ case USB_ST_SETUP: case USB_ST_TRANSFERRED: /* * If output packets don't require headers (the common case) we * can just load the buffer up with payload bytes all at once. * Otherwise, loop to format packets into the buffer while there * is data available, and room for a packet header and at least * one byte of payload. * * NOTE: The FTDI chip doesn't accept zero length * packets. This cannot happen because the "pktlen" * will always be non-zero when "ucom_get_data()" * returns non-zero which we check below. */ pc = usbd_xfer_get_frame(xfer, 0); if (sc->sc_hdrlen == 0) { if (ucom_get_data(&sc->sc_ucom, pc, 0, UFTDI_OBUFSIZE, &buflen) == 0) break; } else { buflen = 0; while (buflen < UFTDI_OBUFSIZE - sc->sc_hdrlen - 1 && ucom_get_data(&sc->sc_ucom, pc, buflen + sc->sc_hdrlen, UFTDI_OPKTSIZE - sc->sc_hdrlen, &pktlen) != 0) { buf[0] = FTDI_OUT_TAG(pktlen, sc->sc_ucom.sc_portno); usbd_copy_in(pc, buflen, buf, 1); buflen += pktlen + sc->sc_hdrlen; } } if (buflen != 0) { usbd_xfer_set_frame_len(xfer, 0, buflen); usbd_transfer_submit(xfer); } break; } } static void uftdi_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct uftdi_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint8_t buf[2]; uint8_t ftdi_msr; uint8_t msr; uint8_t lsr; int buflen; int pktlen; int pktmax; int offset; usbd_xfer_status(xfer, &buflen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (buflen < UFTDI_IHDRSIZE) goto tr_setup; pc = usbd_xfer_get_frame(xfer, 0); pktmax = xfer->max_packet_size - UFTDI_IHDRSIZE; lsr = 0; msr = 0; offset = 0; /* * Extract packet headers and payload bytes from the buffer. * Feed payload bytes to ucom/tty layer; OR-accumulate header * status bits which are transient and could toggle with each * packet. After processing all packets in the buffer, process * the accumulated transient MSR and LSR values along with the * non-transient bits from the last packet header. */ while (buflen >= UFTDI_IHDRSIZE) { usbd_copy_out(pc, offset, buf, UFTDI_IHDRSIZE); offset += UFTDI_IHDRSIZE; buflen -= UFTDI_IHDRSIZE; lsr |= FTDI_GET_LSR(buf); if (FTDI_GET_MSR(buf) & FTDI_SIO_RI_MASK) msr |= SER_RI; pktlen = min(buflen, pktmax); if (pktlen != 0) { ucom_put_data(&sc->sc_ucom, pc, offset, pktlen); offset += pktlen; buflen -= pktlen; } } ftdi_msr = FTDI_GET_MSR(buf); if (ftdi_msr & FTDI_SIO_CTS_MASK) msr |= SER_CTS; if (ftdi_msr & FTDI_SIO_DSR_MASK) msr |= SER_DSR; if (ftdi_msr & FTDI_SIO_RI_MASK) msr |= SER_RI; if (ftdi_msr & FTDI_SIO_RLSD_MASK) msr |= SER_DCD; if ((sc->sc_msr != msr) || ((sc->sc_lsr & FTDI_LSR_MASK) != (lsr & FTDI_LSR_MASK))) { DPRINTF("status change msr=0x%02x (0x%02x) " "lsr=0x%02x (0x%02x)\n", msr, sc->sc_msr, lsr, sc->sc_lsr); sc->sc_msr = msr; sc->sc_lsr = lsr; ucom_status_change(&sc->sc_ucom); } /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void uftdi_cfg_set_dtr(struct ucom_softc *ucom, uint8_t onoff) { struct uftdi_softc *sc = ucom->sc_parent; uint16_t wIndex = ucom->sc_portno; uint16_t wValue; struct usb_device_request req; wValue = onoff ? FTDI_SIO_SET_DTR_HIGH : FTDI_SIO_SET_DTR_LOW; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_MODEM_CTRL; USETW(req.wValue, wValue); USETW(req.wIndex, wIndex); USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); } static void uftdi_cfg_set_rts(struct ucom_softc *ucom, uint8_t onoff) { struct uftdi_softc *sc = ucom->sc_parent; uint16_t wIndex = ucom->sc_portno; uint16_t wValue; struct usb_device_request req; wValue = onoff ? FTDI_SIO_SET_RTS_HIGH : FTDI_SIO_SET_RTS_LOW; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_MODEM_CTRL; USETW(req.wValue, wValue); USETW(req.wIndex, wIndex); USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); } static void uftdi_cfg_set_break(struct ucom_softc *ucom, uint8_t onoff) { struct uftdi_softc *sc = ucom->sc_parent; uint16_t wIndex = ucom->sc_portno; uint16_t wValue; struct usb_device_request req; if (onoff) { sc->sc_last_lcr |= FTDI_SIO_SET_BREAK; } else { sc->sc_last_lcr &= ~FTDI_SIO_SET_BREAK; } wValue = sc->sc_last_lcr; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_SET_DATA; USETW(req.wValue, wValue); USETW(req.wIndex, wIndex); USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); } /* * Return true if the given speed is within operational tolerance of the target * speed. FTDI recommends that the hardware speed be within 3% of nominal. */ static inline boolean_t uftdi_baud_within_tolerance(uint64_t speed, uint64_t target) { return ((speed >= (target * 100) / 103) && (speed <= (target * 100) / 97)); } static int uftdi_sio_encode_baudrate(struct uftdi_softc *sc, speed_t speed, struct uftdi_param_config *cfg) { u_int i; const speed_t sio_speeds[] = { 300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200 }; /* * The original SIO chips were limited to a small choice of speeds * listed in an internal table of speeds chosen by an index value. */ for (i = 0; i < nitems(sio_speeds); ++i) { if (speed == sio_speeds[i]) { cfg->baud_lobits = i; cfg->baud_hibits = 0; return (0); } } return (ERANGE); } static int uftdi_encode_baudrate(struct uftdi_softc *sc, speed_t speed, struct uftdi_param_config *cfg) { static const uint8_t encoded_fraction[8] = {0, 3, 2, 4, 1, 5, 6, 7}; static const uint8_t roundoff_232a[16] = { 0, 1, 0, 1, 0, -1, 2, 1, 0, -1, -2, -3, 4, 3, 2, 1, }; uint32_t clk, divisor, fastclk_flag, frac, hwspeed; /* * If this chip has the fast clock capability and the speed is within * range, use the 12MHz clock, otherwise the standard clock is 3MHz. */ if ((sc->sc_devflags & DEVF_BAUDCLK_12M) && speed >= 1200) { clk = 12000000; fastclk_flag = (1 << 17); } else { clk = 3000000; fastclk_flag = 0; } /* * Make sure the requested speed is reachable with the available clock * and a 14-bit divisor. */ if (speed < (clk >> 14) || speed > clk) return (ERANGE); /* * Calculate the divisor, initially yielding a fixed point number with a * 4-bit (1/16ths) fraction, then round it to the nearest fraction the * hardware can handle. When the integral part of the divisor is * greater than one, the fractional part is in 1/8ths of the base clock. * The FT8U232AM chips can handle only 0.125, 0.250, and 0.5 fractions. * Later chips can handle all 1/8th fractions. * * If the integral part of the divisor is 1, a special rule applies: the * fractional part can only be .0 or .5 (this is a limitation of the * hardware). We handle this by truncating the fraction rather than * rounding, because this only applies to the two fastest speeds the * chip can achieve and rounding doesn't matter, either you've asked for * that exact speed or you've asked for something the chip can't do. * * For the FT8U232AM chips, use a roundoff table to adjust the result * to the nearest 1/8th fraction that is supported by the hardware, * leaving a fixed-point number with a 3-bit fraction which exactly * represents the math the hardware divider will do. For later-series * chips that support all 8 fractional divisors, just round 16ths to * 8ths by adding 1 and dividing by 2. */ divisor = (clk << 4) / speed; if ((divisor & 0xf) == 1) divisor &= 0xfffffff8; else if (sc->sc_devtype == DEVT_232A) divisor += roundoff_232a[divisor & 0x0f]; else divisor += 1; /* Rounds odd 16ths up to next 8th. */ divisor >>= 1; /* * Ensure the resulting hardware speed will be within operational * tolerance (within 3% of nominal). */ hwspeed = (clk << 3) / divisor; if (!uftdi_baud_within_tolerance(hwspeed, speed)) return (ERANGE); /* * Re-pack the divisor into hardware format. The lower 14-bits hold the * integral part, while the upper bits specify the fraction by indexing * a table of fractions within the hardware which is laid out as: * {0.0, 0.5, 0.25, 0.125, 0.325, 0.625, 0.725, 0.875} * The A-series chips only have the first four table entries; the * roundoff table logic above ensures that the fractional part for those * chips will be one of the first four values. * * When the divisor is 1 a special encoding applies: 1.0 is encoded as * 0.0, and 1.5 is encoded as 1.0. The rounding logic above has already * ensured that the fraction is either .0 or .5 if the integral is 1. */ frac = divisor & 0x07; divisor >>= 3; if (divisor == 1) { if (frac == 0) divisor = 0; /* 1.0 becomes 0.0 */ else frac = 0; /* 1.5 becomes 1.0 */ } divisor |= (encoded_fraction[frac] << 14) | fastclk_flag; cfg->baud_lobits = (uint16_t)divisor; cfg->baud_hibits = (uint16_t)(divisor >> 16); /* * If this chip requires the baud bits to be in the high byte of the * index word, move the bits up to that location. */ if (sc->sc_devflags & DEVF_BAUDBITS_HINDEX) { cfg->baud_hibits <<= 8; } return (0); } static int uftdi_set_parm_soft(struct ucom_softc *ucom, struct termios *t, struct uftdi_param_config *cfg) { struct uftdi_softc *sc = ucom->sc_parent; int err; memset(cfg, 0, sizeof(*cfg)); if (sc->sc_devtype == DEVT_SIO) err = uftdi_sio_encode_baudrate(sc, t->c_ospeed, cfg); else err = uftdi_encode_baudrate(sc, t->c_ospeed, cfg); if (err != 0) return (err); if (t->c_cflag & CSTOPB) cfg->lcr = FTDI_SIO_SET_DATA_STOP_BITS_2; else cfg->lcr = FTDI_SIO_SET_DATA_STOP_BITS_1; if (t->c_cflag & PARENB) { if (t->c_cflag & PARODD) { cfg->lcr |= FTDI_SIO_SET_DATA_PARITY_ODD; } else { cfg->lcr |= FTDI_SIO_SET_DATA_PARITY_EVEN; } } else { cfg->lcr |= FTDI_SIO_SET_DATA_PARITY_NONE; } switch (t->c_cflag & CSIZE) { case CS5: cfg->lcr |= FTDI_SIO_SET_DATA_BITS(5); break; case CS6: cfg->lcr |= FTDI_SIO_SET_DATA_BITS(6); break; case CS7: cfg->lcr |= FTDI_SIO_SET_DATA_BITS(7); break; case CS8: cfg->lcr |= FTDI_SIO_SET_DATA_BITS(8); break; } if (t->c_cflag & CRTSCTS) { cfg->v_flow = FTDI_SIO_RTS_CTS_HS; } else if (t->c_iflag & (IXON | IXOFF)) { cfg->v_flow = FTDI_SIO_XON_XOFF_HS; cfg->v_start = t->c_cc[VSTART]; cfg->v_stop = t->c_cc[VSTOP]; } else { cfg->v_flow = FTDI_SIO_DISABLE_FLOW_CTRL; } return (0); } static int uftdi_pre_param(struct ucom_softc *ucom, struct termios *t) { struct uftdi_param_config cfg; DPRINTF("\n"); return (uftdi_set_parm_soft(ucom, t, &cfg)); } static void uftdi_cfg_param(struct ucom_softc *ucom, struct termios *t) { struct uftdi_softc *sc = ucom->sc_parent; uint16_t wIndex = ucom->sc_portno; struct uftdi_param_config cfg; struct usb_device_request req; if (uftdi_set_parm_soft(ucom, t, &cfg)) { /* should not happen */ return; } sc->sc_last_lcr = cfg.lcr; DPRINTF("\n"); req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_SET_BAUD_RATE; USETW(req.wValue, cfg.baud_lobits); USETW(req.wIndex, cfg.baud_hibits | wIndex); USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_SET_DATA; USETW(req.wValue, cfg.lcr); USETW(req.wIndex, wIndex); USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_SET_FLOW_CTRL; USETW2(req.wValue, cfg.v_stop, cfg.v_start); USETW2(req.wIndex, cfg.v_flow, wIndex); USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); } static void uftdi_cfg_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr) { struct uftdi_softc *sc = ucom->sc_parent; DPRINTF("msr=0x%02x lsr=0x%02x\n", sc->sc_msr, sc->sc_lsr); *msr = sc->sc_msr; *lsr = sc->sc_lsr; } static int uftdi_reset(struct ucom_softc *ucom, int reset_type) { struct uftdi_softc *sc = ucom->sc_parent; usb_device_request_t req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_RESET; USETW(req.wIndex, sc->sc_ucom.sc_portno); USETW(req.wLength, 0); USETW(req.wValue, reset_type); return (usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, NULL)); } static int uftdi_set_bitmode(struct ucom_softc *ucom, uint8_t bitmode, uint8_t iomask) { struct uftdi_softc *sc = ucom->sc_parent; usb_device_request_t req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_SET_BITMODE; USETW(req.wIndex, sc->sc_ucom.sc_portno); USETW(req.wLength, 0); if (bitmode == UFTDI_BITMODE_NONE) USETW2(req.wValue, 0, 0); else USETW2(req.wValue, (1 << bitmode), iomask); return (usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, NULL)); } static int uftdi_get_bitmode(struct ucom_softc *ucom, uint8_t *iomask) { struct uftdi_softc *sc = ucom->sc_parent; usb_device_request_t req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_GET_BITMODE; USETW(req.wIndex, sc->sc_ucom.sc_portno); USETW(req.wLength, 1); USETW(req.wValue, 0); return (usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, iomask)); } static int uftdi_set_latency(struct ucom_softc *ucom, int latency) { struct uftdi_softc *sc = ucom->sc_parent; usb_device_request_t req; if (latency < 0 || latency > 255) return (USB_ERR_INVAL); req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_SET_LATENCY; USETW(req.wIndex, sc->sc_ucom.sc_portno); USETW(req.wLength, 0); USETW2(req.wValue, 0, latency); return (usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, NULL)); } static int uftdi_get_latency(struct ucom_softc *ucom, int *latency) { struct uftdi_softc *sc = ucom->sc_parent; usb_device_request_t req; usb_error_t err; uint8_t buf; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_GET_LATENCY; USETW(req.wIndex, sc->sc_ucom.sc_portno); USETW(req.wLength, 1); USETW(req.wValue, 0); err = usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, &buf); *latency = buf; return (err); } static int uftdi_set_event_char(struct ucom_softc *ucom, int echar) { struct uftdi_softc *sc = ucom->sc_parent; usb_device_request_t req; uint8_t enable; enable = (echar == -1) ? 0 : 1; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_SET_EVENT_CHAR; USETW(req.wIndex, sc->sc_ucom.sc_portno); USETW(req.wLength, 0); USETW2(req.wValue, enable, echar & 0xff); return (usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, NULL)); } static int uftdi_set_error_char(struct ucom_softc *ucom, int echar) { struct uftdi_softc *sc = ucom->sc_parent; usb_device_request_t req; uint8_t enable; enable = (echar == -1) ? 0 : 1; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = FTDI_SIO_SET_ERROR_CHAR; USETW(req.wIndex, sc->sc_ucom.sc_portno); USETW(req.wLength, 0); USETW2(req.wValue, enable, echar & 0xff); return (usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, NULL)); } static int uftdi_ioctl(struct ucom_softc *ucom, uint32_t cmd, caddr_t data, int flag, struct thread *td) { struct uftdi_softc *sc = ucom->sc_parent; int err; struct uftdi_bitmode * mode; DPRINTF("portno: %d cmd: %#x\n", ucom->sc_portno, cmd); switch (cmd) { case UFTDIIOC_RESET_IO: case UFTDIIOC_RESET_RX: case UFTDIIOC_RESET_TX: err = uftdi_reset(ucom, cmd == UFTDIIOC_RESET_IO ? FTDI_SIO_RESET_SIO : (cmd == UFTDIIOC_RESET_RX ? FTDI_SIO_RESET_PURGE_RX : FTDI_SIO_RESET_PURGE_TX)); break; case UFTDIIOC_SET_BITMODE: mode = (struct uftdi_bitmode *)data; err = uftdi_set_bitmode(ucom, mode->mode, mode->iomask); break; case UFTDIIOC_GET_BITMODE: mode = (struct uftdi_bitmode *)data; err = uftdi_get_bitmode(ucom, &mode->iomask); break; case UFTDIIOC_SET_LATENCY: err = uftdi_set_latency(ucom, *((int *)data)); break; case UFTDIIOC_GET_LATENCY: err = uftdi_get_latency(ucom, (int *)data); break; case UFTDIIOC_SET_ERROR_CHAR: err = uftdi_set_error_char(ucom, *(int *)data); break; case UFTDIIOC_SET_EVENT_CHAR: err = uftdi_set_event_char(ucom, *(int *)data); break; case UFTDIIOC_GET_HWREV: *(int *)data = sc->sc_bcdDevice; err = 0; break; default: return (ENOIOCTL); } if (err != USB_ERR_NORMAL_COMPLETION) return (EIO); return (0); } static void uftdi_start_read(struct ucom_softc *ucom) { struct uftdi_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[UFTDI_BULK_DT_RD]); } static void uftdi_stop_read(struct ucom_softc *ucom) { struct uftdi_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[UFTDI_BULK_DT_RD]); } static void uftdi_start_write(struct ucom_softc *ucom) { struct uftdi_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[UFTDI_BULK_DT_WR]); } static void uftdi_stop_write(struct ucom_softc *ucom) { struct uftdi_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[UFTDI_BULK_DT_WR]); } static void uftdi_poll(struct ucom_softc *ucom) { struct uftdi_softc *sc = ucom->sc_parent; usbd_transfer_poll(sc->sc_xfer, UFTDI_N_TRANSFER); } Index: head/sys/dev/usb/serial/ulpt.c =================================================================== --- head/sys/dev/usb/serial/ulpt.c (revision 276700) +++ head/sys/dev/usb/serial/ulpt.c (revision 276701) @@ -1,761 +1,761 @@ #include __FBSDID("$FreeBSD$"); /* $NetBSD: ulpt.c,v 1.60 2003/10/04 21:19:50 augustss Exp $ */ /*- * Copyright (c) 1998, 2003 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Lennart Augustsson (lennart@augustsson.net) at * Carlstedt Research & Technology. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Printer Class spec: http://www.usb.org/developers/data/devclass/usbprint109.PDF * Printer Class spec: http://www.usb.org/developers/devclass_docs/usbprint11.pdf */ #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 "usbdevs.h" #define USB_DEBUG_VAR ulpt_debug #include #include #ifdef USB_DEBUG static int ulpt_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, ulpt, CTLFLAG_RW, 0, "USB ulpt"); -SYSCTL_INT(_hw_usb_ulpt, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_ulpt, OID_AUTO, debug, CTLFLAG_RWTUN, &ulpt_debug, 0, "Debug level"); #endif #define ULPT_BSIZE (1<<15) /* bytes */ #define ULPT_IFQ_MAXLEN 2 /* units */ #define UR_GET_DEVICE_ID 0x00 #define UR_GET_PORT_STATUS 0x01 #define UR_SOFT_RESET 0x02 #define LPS_NERR 0x08 /* printer no error */ #define LPS_SELECT 0x10 /* printer selected */ #define LPS_NOPAPER 0x20 /* printer out of paper */ #define LPS_INVERT (LPS_SELECT|LPS_NERR) #define LPS_MASK (LPS_SELECT|LPS_NERR|LPS_NOPAPER) enum { ULPT_BULK_DT_WR, ULPT_BULK_DT_RD, ULPT_INTR_DT_RD, ULPT_N_TRANSFER, }; struct ulpt_softc { struct usb_fifo_sc sc_fifo; struct usb_fifo_sc sc_fifo_noreset; struct mtx sc_mtx; struct usb_callout sc_watchdog; device_t sc_dev; struct usb_device *sc_udev; struct usb_fifo *sc_fifo_open[2]; struct usb_xfer *sc_xfer[ULPT_N_TRANSFER]; int sc_fflags; /* current open flags, FREAD and * FWRITE */ uint8_t sc_iface_no; uint8_t sc_last_status; uint8_t sc_zlps; /* number of consequtive zero length * packets received */ }; /* prototypes */ static device_probe_t ulpt_probe; static device_attach_t ulpt_attach; static device_detach_t ulpt_detach; static usb_callback_t ulpt_write_callback; static usb_callback_t ulpt_read_callback; static usb_callback_t ulpt_status_callback; static void ulpt_reset(struct ulpt_softc *); static void ulpt_watchdog(void *); static usb_fifo_close_t ulpt_close; static usb_fifo_cmd_t ulpt_start_read; static usb_fifo_cmd_t ulpt_start_write; static usb_fifo_cmd_t ulpt_stop_read; static usb_fifo_cmd_t ulpt_stop_write; static usb_fifo_ioctl_t ulpt_ioctl; static usb_fifo_open_t ulpt_open; static usb_fifo_open_t unlpt_open; static struct usb_fifo_methods ulpt_fifo_methods = { .f_close = &ulpt_close, .f_ioctl = &ulpt_ioctl, .f_open = &ulpt_open, .f_start_read = &ulpt_start_read, .f_start_write = &ulpt_start_write, .f_stop_read = &ulpt_stop_read, .f_stop_write = &ulpt_stop_write, .basename[0] = "ulpt", }; static struct usb_fifo_methods unlpt_fifo_methods = { .f_close = &ulpt_close, .f_ioctl = &ulpt_ioctl, .f_open = &unlpt_open, .f_start_read = &ulpt_start_read, .f_start_write = &ulpt_start_write, .f_stop_read = &ulpt_stop_read, .f_stop_write = &ulpt_stop_write, .basename[0] = "unlpt", }; static void ulpt_reset(struct ulpt_softc *sc) { struct usb_device_request req; DPRINTFN(2, "\n"); req.bRequest = UR_SOFT_RESET; USETW(req.wValue, 0); USETW(req.wIndex, sc->sc_iface_no); USETW(req.wLength, 0); /* * There was a mistake in the USB printer 1.0 spec that gave the * request type as UT_WRITE_CLASS_OTHER; it should have been * UT_WRITE_CLASS_INTERFACE. Many printers use the old one, * so we try both. */ mtx_lock(&sc->sc_mtx); req.bmRequestType = UT_WRITE_CLASS_OTHER; if (usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx, &req, NULL, 0, NULL, 2 * USB_MS_HZ)) { /* 1.0 */ req.bmRequestType = UT_WRITE_CLASS_INTERFACE; if (usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx, &req, NULL, 0, NULL, 2 * USB_MS_HZ)) { /* 1.1 */ /* ignore error */ } } mtx_unlock(&sc->sc_mtx); } static void ulpt_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct ulpt_softc *sc = usbd_xfer_softc(xfer); struct usb_fifo *f = sc->sc_fifo_open[USB_FIFO_TX]; struct usb_page_cache *pc; int actlen, max; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); if (f == NULL) { /* should not happen */ DPRINTF("no FIFO\n"); return; } DPRINTF("state=0x%x actlen=%d\n", USB_GET_STATE(xfer), actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: case USB_ST_SETUP: tr_setup: pc = usbd_xfer_get_frame(xfer, 0); max = usbd_xfer_max_len(xfer); if (usb_fifo_get_data(f, pc, 0, max, &actlen, 0)) { usbd_xfer_set_frame_len(xfer, 0, actlen); usbd_transfer_submit(xfer); } break; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void ulpt_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct ulpt_softc *sc = usbd_xfer_softc(xfer); struct usb_fifo *f = sc->sc_fifo_open[USB_FIFO_RX]; struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); if (f == NULL) { /* should not happen */ DPRINTF("no FIFO\n"); return; } DPRINTF("state=0x%x\n", USB_GET_STATE(xfer)); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen == 0) { if (sc->sc_zlps == 4) { /* enable BULK throttle */ usbd_xfer_set_interval(xfer, 500); /* ms */ } else { sc->sc_zlps++; } } else { /* disable BULK throttle */ usbd_xfer_set_interval(xfer, 0); sc->sc_zlps = 0; } pc = usbd_xfer_get_frame(xfer, 0); usb_fifo_put_data(f, pc, 0, actlen, 1); case USB_ST_SETUP: tr_setup: if (usb_fifo_put_bytes_max(f) != 0) { usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); } break; default: /* Error */ /* disable BULK throttle */ usbd_xfer_set_interval(xfer, 0); sc->sc_zlps = 0; if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void ulpt_status_callback(struct usb_xfer *xfer, usb_error_t error) { struct ulpt_softc *sc = usbd_xfer_softc(xfer); struct usb_device_request req; struct usb_page_cache *pc; uint8_t cur_status; uint8_t new_status; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 1); usbd_copy_out(pc, 0, &cur_status, 1); cur_status = (cur_status ^ LPS_INVERT) & LPS_MASK; new_status = cur_status & ~sc->sc_last_status; sc->sc_last_status = cur_status; if (new_status & LPS_SELECT) log(LOG_NOTICE, "%s: offline\n", device_get_nameunit(sc->sc_dev)); else if (new_status & LPS_NOPAPER) log(LOG_NOTICE, "%s: out of paper\n", device_get_nameunit(sc->sc_dev)); else if (new_status & LPS_NERR) log(LOG_NOTICE, "%s: output error\n", device_get_nameunit(sc->sc_dev)); break; case USB_ST_SETUP: req.bmRequestType = UT_READ_CLASS_INTERFACE; req.bRequest = UR_GET_PORT_STATUS; USETW(req.wValue, 0); req.wIndex[0] = sc->sc_iface_no; req.wIndex[1] = 0; USETW(req.wLength, 1); pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, &req, sizeof(req)); usbd_xfer_set_frame_len(xfer, 0, sizeof(req)); usbd_xfer_set_frame_len(xfer, 1, 1); usbd_xfer_set_frames(xfer, 2); usbd_transfer_submit(xfer); break; default: /* Error */ DPRINTF("error=%s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* wait for next watchdog timeout */ } break; } } static const struct usb_config ulpt_config[ULPT_N_TRANSFER] = { [ULPT_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = ULPT_BSIZE, .flags = {.pipe_bof = 1,.proxy_buffer = 1}, .callback = &ulpt_write_callback, }, [ULPT_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = ULPT_BSIZE, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,.proxy_buffer = 1}, .callback = &ulpt_read_callback, }, [ULPT_INTR_DT_RD] = { .type = UE_CONTROL, .endpoint = 0x00, /* Control pipe */ .direction = UE_DIR_ANY, .bufsize = sizeof(struct usb_device_request) + 1, .callback = &ulpt_status_callback, .timeout = 1000, /* 1 second */ }, }; static void ulpt_start_read(struct usb_fifo *fifo) { struct ulpt_softc *sc = usb_fifo_softc(fifo); usbd_transfer_start(sc->sc_xfer[ULPT_BULK_DT_RD]); } static void ulpt_stop_read(struct usb_fifo *fifo) { struct ulpt_softc *sc = usb_fifo_softc(fifo); usbd_transfer_stop(sc->sc_xfer[ULPT_BULK_DT_RD]); } static void ulpt_start_write(struct usb_fifo *fifo) { struct ulpt_softc *sc = usb_fifo_softc(fifo); usbd_transfer_start(sc->sc_xfer[ULPT_BULK_DT_WR]); } static void ulpt_stop_write(struct usb_fifo *fifo) { struct ulpt_softc *sc = usb_fifo_softc(fifo); usbd_transfer_stop(sc->sc_xfer[ULPT_BULK_DT_WR]); } static int ulpt_open(struct usb_fifo *fifo, int fflags) { struct ulpt_softc *sc = usb_fifo_softc(fifo); /* we assume that open is a serial process */ if (sc->sc_fflags == 0) { /* reset USB paralell port */ ulpt_reset(sc); } return (unlpt_open(fifo, fflags)); } static int unlpt_open(struct usb_fifo *fifo, int fflags) { struct ulpt_softc *sc = usb_fifo_softc(fifo); if (sc->sc_fflags & fflags) { return (EBUSY); } if (fflags & FREAD) { /* clear stall first */ mtx_lock(&sc->sc_mtx); usbd_xfer_set_stall(sc->sc_xfer[ULPT_BULK_DT_RD]); mtx_unlock(&sc->sc_mtx); if (usb_fifo_alloc_buffer(fifo, usbd_xfer_max_len(sc->sc_xfer[ULPT_BULK_DT_RD]), ULPT_IFQ_MAXLEN)) { return (ENOMEM); } /* set which FIFO is opened */ sc->sc_fifo_open[USB_FIFO_RX] = fifo; } if (fflags & FWRITE) { /* clear stall first */ mtx_lock(&sc->sc_mtx); usbd_xfer_set_stall(sc->sc_xfer[ULPT_BULK_DT_WR]); mtx_unlock(&sc->sc_mtx); if (usb_fifo_alloc_buffer(fifo, usbd_xfer_max_len(sc->sc_xfer[ULPT_BULK_DT_WR]), ULPT_IFQ_MAXLEN)) { return (ENOMEM); } /* set which FIFO is opened */ sc->sc_fifo_open[USB_FIFO_TX] = fifo; } sc->sc_fflags |= fflags & (FREAD | FWRITE); return (0); } static void ulpt_close(struct usb_fifo *fifo, int fflags) { struct ulpt_softc *sc = usb_fifo_softc(fifo); sc->sc_fflags &= ~(fflags & (FREAD | FWRITE)); if (fflags & (FREAD | FWRITE)) { usb_fifo_free_buffer(fifo); } } static int ulpt_ioctl(struct usb_fifo *fifo, u_long cmd, void *data, int fflags) { return (ENODEV); } static const STRUCT_USB_HOST_ID ulpt_devs[] = { /* Uni-directional USB printer */ {USB_IFACE_CLASS(UICLASS_PRINTER), USB_IFACE_SUBCLASS(UISUBCLASS_PRINTER), USB_IFACE_PROTOCOL(UIPROTO_PRINTER_UNI)}, /* Bi-directional USB printer */ {USB_IFACE_CLASS(UICLASS_PRINTER), USB_IFACE_SUBCLASS(UISUBCLASS_PRINTER), USB_IFACE_PROTOCOL(UIPROTO_PRINTER_BI)}, /* 1284 USB printer */ {USB_IFACE_CLASS(UICLASS_PRINTER), USB_IFACE_SUBCLASS(UISUBCLASS_PRINTER), USB_IFACE_PROTOCOL(UIPROTO_PRINTER_1284)}, }; static int ulpt_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); int error; DPRINTFN(11, "\n"); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); error = usbd_lookup_id_by_uaa(ulpt_devs, sizeof(ulpt_devs), uaa); if (error) return (error); return (BUS_PROBE_GENERIC); } static int ulpt_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct ulpt_softc *sc = device_get_softc(dev); struct usb_interface_descriptor *id; int unit = device_get_unit(dev); int error; uint8_t iface_index = uaa->info.bIfaceIndex; uint8_t alt_index; DPRINTFN(11, "sc=%p\n", sc); sc->sc_dev = dev; sc->sc_udev = uaa->device; device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "ulpt lock", NULL, MTX_DEF | MTX_RECURSE); usb_callout_init_mtx(&sc->sc_watchdog, &sc->sc_mtx, 0); /* search through all the descriptors looking for bidir mode */ id = usbd_get_interface_descriptor(uaa->iface); alt_index = 0xFF; while (1) { if (id == NULL) { break; } if ((id->bDescriptorType == UDESC_INTERFACE) && (id->bLength >= sizeof(*id))) { if (id->bInterfaceNumber != uaa->info.bIfaceNum) { break; } else { alt_index++; if ((id->bInterfaceClass == UICLASS_PRINTER) && (id->bInterfaceSubClass == UISUBCLASS_PRINTER) && (id->bInterfaceProtocol == UIPROTO_PRINTER_BI)) { goto found; } } } id = (void *)usb_desc_foreach( usbd_get_config_descriptor(uaa->device), (void *)id); } goto detach; found: DPRINTF("setting alternate " "config number: %d\n", alt_index); if (alt_index) { error = usbd_set_alt_interface_index (uaa->device, iface_index, alt_index); if (error) { DPRINTF("could not set alternate " "config, error=%s\n", usbd_errstr(error)); goto detach; } } sc->sc_iface_no = id->bInterfaceNumber; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, ulpt_config, ULPT_N_TRANSFER, sc, &sc->sc_mtx); if (error) { DPRINTF("error=%s\n", usbd_errstr(error)); goto detach; } device_printf(sc->sc_dev, "using bi-directional mode\n"); #if 0 /* * This code is disabled because for some mysterious reason it causes * printing not to work. But only sometimes, and mostly with * UHCI and less often with OHCI. *sigh* */ { struct usb_config_descriptor *cd = usbd_get_config_descriptor(dev); struct usb_device_request req; int len, alen; req.bmRequestType = UT_READ_CLASS_INTERFACE; req.bRequest = UR_GET_DEVICE_ID; USETW(req.wValue, cd->bConfigurationValue); USETW2(req.wIndex, id->bInterfaceNumber, id->bAlternateSetting); USETW(req.wLength, sizeof devinfo - 1); error = usbd_do_request_flags(dev, &req, devinfo, USB_SHORT_XFER_OK, &alen, USB_DEFAULT_TIMEOUT); if (error) { device_printf(sc->sc_dev, "cannot get device id\n"); } else if (alen <= 2) { device_printf(sc->sc_dev, "empty device id, no " "printer connected?\n"); } else { /* devinfo now contains an IEEE-1284 device ID */ len = ((devinfo[0] & 0xff) << 8) | (devinfo[1] & 0xff); if (len > sizeof devinfo - 3) len = sizeof devinfo - 3; devinfo[len] = 0; printf("%s: device id <", device_get_nameunit(sc->sc_dev)); ieee1284_print_id(devinfo + 2); printf(">\n"); } } #endif error = usb_fifo_attach(uaa->device, sc, &sc->sc_mtx, &ulpt_fifo_methods, &sc->sc_fifo, unit, -1, uaa->info.bIfaceIndex, UID_ROOT, GID_OPERATOR, 0644); if (error) { goto detach; } error = usb_fifo_attach(uaa->device, sc, &sc->sc_mtx, &unlpt_fifo_methods, &sc->sc_fifo_noreset, unit, -1, uaa->info.bIfaceIndex, UID_ROOT, GID_OPERATOR, 0644); if (error) { goto detach; } /* start reading of status */ mtx_lock(&sc->sc_mtx); ulpt_watchdog(sc); mtx_unlock(&sc->sc_mtx); return (0); detach: ulpt_detach(dev); return (ENOMEM); } static int ulpt_detach(device_t dev) { struct ulpt_softc *sc = device_get_softc(dev); DPRINTF("sc=%p\n", sc); usb_fifo_detach(&sc->sc_fifo); usb_fifo_detach(&sc->sc_fifo_noreset); mtx_lock(&sc->sc_mtx); usb_callout_stop(&sc->sc_watchdog); mtx_unlock(&sc->sc_mtx); usbd_transfer_unsetup(sc->sc_xfer, ULPT_N_TRANSFER); usb_callout_drain(&sc->sc_watchdog); mtx_destroy(&sc->sc_mtx); return (0); } #if 0 /* XXX This does not belong here. */ /* * Compare two strings until the second ends. */ static uint8_t ieee1284_compare(const char *a, const char *b) { while (1) { if (*b == 0) { break; } if (*a != *b) { return 1; } b++; a++; } return 0; } /* * Print select parts of an IEEE 1284 device ID. */ void ieee1284_print_id(char *str) { char *p, *q; for (p = str - 1; p; p = strchr(p, ';')) { p++; /* skip ';' */ if (ieee1284_compare(p, "MFG:") == 0 || ieee1284_compare(p, "MANUFACTURER:") == 0 || ieee1284_compare(p, "MDL:") == 0 || ieee1284_compare(p, "MODEL:") == 0) { q = strchr(p, ';'); if (q) printf("%.*s", (int)(q - p + 1), p); } } } #endif static void ulpt_watchdog(void *arg) { struct ulpt_softc *sc = arg; mtx_assert(&sc->sc_mtx, MA_OWNED); /* * Only read status while the device is not opened, due to * possible hardware or firmware bug in some printers. */ if (sc->sc_fflags == 0) usbd_transfer_start(sc->sc_xfer[ULPT_INTR_DT_RD]); usb_callout_reset(&sc->sc_watchdog, hz, &ulpt_watchdog, sc); } static devclass_t ulpt_devclass; static device_method_t ulpt_methods[] = { DEVMETHOD(device_probe, ulpt_probe), DEVMETHOD(device_attach, ulpt_attach), DEVMETHOD(device_detach, ulpt_detach), DEVMETHOD_END }; static driver_t ulpt_driver = { .name = "ulpt", .methods = ulpt_methods, .size = sizeof(struct ulpt_softc), }; DRIVER_MODULE(ulpt, uhub, ulpt_driver, ulpt_devclass, NULL, 0); MODULE_DEPEND(ulpt, usb, 1, 1, 1); MODULE_VERSION(ulpt, 1); Index: head/sys/dev/usb/serial/umcs.c =================================================================== --- head/sys/dev/usb/serial/umcs.c (revision 276700) +++ head/sys/dev/usb/serial/umcs.c (revision 276701) @@ -1,1093 +1,1093 @@ /*- * Copyright (c) 2010 Lev Serebryakov . * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * This driver supports several multiport USB-to-RS232 serial adapters driven * by MosChip mos7820 and mos7840, bridge chips. * The adapters are sold under many different brand names. * * Datasheets are available at MosChip www site at * http://www.moschip.com. The datasheets don't contain full * programming information for the chip. * * It is nornal to have only two enabled ports in devices, based on * quad-port mos7840. * */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR umcs_debug #include #include #include #include #define UMCS7840_MODVER 1 #ifdef USB_DEBUG static int umcs_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, umcs, CTLFLAG_RW, 0, "USB umcs quadport serial adapter"); -SYSCTL_INT(_hw_usb_umcs, OID_AUTO, debug, CTLFLAG_RW, &umcs_debug, 0, "Debug level"); +SYSCTL_INT(_hw_usb_umcs, OID_AUTO, debug, CTLFLAG_RWTUN, &umcs_debug, 0, "Debug level"); #endif /* USB_DEBUG */ /* * Two-port devices (both with 7820 chip and 7840 chip configured as two-port) * have ports 0 and 2, with ports 1 and 3 omitted. * So,PHYSICAL port numbers (indexes) on two-port device will be 0 and 2. * This driver trys to use physical numbers as much as possible. */ /* * Indexed by PHYSICAL port number. * Pack non-regular registers to array to easier if-less access. */ struct umcs7840_port_registers { uint8_t reg_sp; /* SP register. */ uint8_t reg_control; /* CONTROL register. */ uint8_t reg_dcr; /* DCR0 register. DCR1 & DCR2 can be * calculated */ }; static const struct umcs7840_port_registers umcs7840_port_registers[UMCS7840_MAX_PORTS] = { {.reg_sp = MCS7840_DEV_REG_SP1,.reg_control = MCS7840_DEV_REG_CONTROL1,.reg_dcr = MCS7840_DEV_REG_DCR0_1}, {.reg_sp = MCS7840_DEV_REG_SP2,.reg_control = MCS7840_DEV_REG_CONTROL2,.reg_dcr = MCS7840_DEV_REG_DCR0_2}, {.reg_sp = MCS7840_DEV_REG_SP3,.reg_control = MCS7840_DEV_REG_CONTROL3,.reg_dcr = MCS7840_DEV_REG_DCR0_3}, {.reg_sp = MCS7840_DEV_REG_SP4,.reg_control = MCS7840_DEV_REG_CONTROL4,.reg_dcr = MCS7840_DEV_REG_DCR0_4}, }; enum { UMCS7840_BULK_RD_EP, UMCS7840_BULK_WR_EP, UMCS7840_N_TRANSFERS }; struct umcs7840_softc_oneport { struct usb_xfer *sc_xfer[UMCS7840_N_TRANSFERS]; /* Control structures * for two transfers */ uint8_t sc_lcr; /* local line control register */ uint8_t sc_mcr; /* local modem control register */ }; struct umcs7840_softc { struct ucom_super_softc sc_super_ucom; struct ucom_softc sc_ucom[UMCS7840_MAX_PORTS]; /* Need to be continuous * array, so indexed by * LOGICAL port * (subunit) number */ struct usb_xfer *sc_intr_xfer; /* Interrupt endpoint */ device_t sc_dev; /* Device for error prints */ struct usb_device *sc_udev; /* USB Device for all operations */ struct mtx sc_mtx; /* ucom requires this */ uint8_t sc_driver_done; /* Flag when enumeration is finished */ uint8_t sc_numports; /* Number of ports (subunits) */ struct umcs7840_softc_oneport sc_ports[UMCS7840_MAX_PORTS]; /* Indexed by PHYSICAL * port number. */ }; /* prototypes */ static usb_error_t umcs7840_get_reg_sync(struct umcs7840_softc *, uint8_t, uint8_t *); static usb_error_t umcs7840_set_reg_sync(struct umcs7840_softc *, uint8_t, uint8_t); static usb_error_t umcs7840_get_UART_reg_sync(struct umcs7840_softc *, uint8_t, uint8_t, uint8_t *); static usb_error_t umcs7840_set_UART_reg_sync(struct umcs7840_softc *, uint8_t, uint8_t, uint8_t); static usb_error_t umcs7840_set_baudrate(struct umcs7840_softc *, uint8_t, uint32_t); static usb_error_t umcs7840_calc_baudrate(uint32_t rate, uint16_t *, uint8_t *); static void umcs7840_free(struct ucom_softc *); static void umcs7840_cfg_get_status(struct ucom_softc *, uint8_t *, uint8_t *); static void umcs7840_cfg_set_dtr(struct ucom_softc *, uint8_t); static void umcs7840_cfg_set_rts(struct ucom_softc *, uint8_t); static void umcs7840_cfg_set_break(struct ucom_softc *, uint8_t); static void umcs7840_cfg_param(struct ucom_softc *, struct termios *); static void umcs7840_cfg_open(struct ucom_softc *); static void umcs7840_cfg_close(struct ucom_softc *); static int umcs7840_pre_param(struct ucom_softc *, struct termios *); static void umcs7840_start_read(struct ucom_softc *); static void umcs7840_stop_read(struct ucom_softc *); static void umcs7840_start_write(struct ucom_softc *); static void umcs7840_stop_write(struct ucom_softc *); static void umcs7840_poll(struct ucom_softc *ucom); static device_probe_t umcs7840_probe; static device_attach_t umcs7840_attach; static device_detach_t umcs7840_detach; static void umcs7840_free_softc(struct umcs7840_softc *); static usb_callback_t umcs7840_intr_callback; static usb_callback_t umcs7840_read_callback1; static usb_callback_t umcs7840_read_callback2; static usb_callback_t umcs7840_read_callback3; static usb_callback_t umcs7840_read_callback4; static usb_callback_t umcs7840_write_callback1; static usb_callback_t umcs7840_write_callback2; static usb_callback_t umcs7840_write_callback3; static usb_callback_t umcs7840_write_callback4; static void umcs7840_read_callbackN(struct usb_xfer *, usb_error_t, uint8_t); static void umcs7840_write_callbackN(struct usb_xfer *, usb_error_t, uint8_t); /* Indexed by LOGICAL port number (subunit), so two-port device uses 0 & 1 */ static usb_callback_t *umcs7840_rw_callbacks[UMCS7840_MAX_PORTS][UMCS7840_N_TRANSFERS] = { {&umcs7840_read_callback1, &umcs7840_write_callback1}, {&umcs7840_read_callback2, &umcs7840_write_callback2}, {&umcs7840_read_callback3, &umcs7840_write_callback3}, {&umcs7840_read_callback4, &umcs7840_write_callback4}, }; static const struct usb_config umcs7840_bulk_config_data[UMCS7840_N_TRANSFERS] = { [UMCS7840_BULK_RD_EP] = { .type = UE_BULK, .endpoint = 0x01, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = &umcs7840_read_callback1, .if_index = 0, }, [UMCS7840_BULK_WR_EP] = { .type = UE_BULK, .endpoint = 0x02, .direction = UE_DIR_OUT, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = &umcs7840_write_callback1, .if_index = 0, }, }; static const struct usb_config umcs7840_intr_config_data[1] = { [0] = { .type = UE_INTERRUPT, .endpoint = 0x09, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = &umcs7840_intr_callback, .if_index = 0, }, }; static struct ucom_callback umcs7840_callback = { .ucom_cfg_get_status = &umcs7840_cfg_get_status, .ucom_cfg_set_dtr = &umcs7840_cfg_set_dtr, .ucom_cfg_set_rts = &umcs7840_cfg_set_rts, .ucom_cfg_set_break = &umcs7840_cfg_set_break, .ucom_cfg_param = &umcs7840_cfg_param, .ucom_cfg_open = &umcs7840_cfg_open, .ucom_cfg_close = &umcs7840_cfg_close, .ucom_pre_param = &umcs7840_pre_param, .ucom_start_read = &umcs7840_start_read, .ucom_stop_read = &umcs7840_stop_read, .ucom_start_write = &umcs7840_start_write, .ucom_stop_write = &umcs7840_stop_write, .ucom_poll = &umcs7840_poll, .ucom_free = &umcs7840_free, }; static const STRUCT_USB_HOST_ID umcs7840_devs[] = { {USB_VPI(USB_VENDOR_MOSCHIP, USB_PRODUCT_MOSCHIP_MCS7820, 0)}, {USB_VPI(USB_VENDOR_MOSCHIP, USB_PRODUCT_MOSCHIP_MCS7840, 0)}, }; static device_method_t umcs7840_methods[] = { DEVMETHOD(device_probe, umcs7840_probe), DEVMETHOD(device_attach, umcs7840_attach), DEVMETHOD(device_detach, umcs7840_detach), DEVMETHOD_END }; static devclass_t umcs7840_devclass; static driver_t umcs7840_driver = { .name = "umcs7840", .methods = umcs7840_methods, .size = sizeof(struct umcs7840_softc), }; DRIVER_MODULE(umcs7840, uhub, umcs7840_driver, umcs7840_devclass, 0, 0); MODULE_DEPEND(umcs7840, ucom, 1, 1, 1); MODULE_DEPEND(umcs7840, usb, 1, 1, 1); MODULE_VERSION(umcs7840, UMCS7840_MODVER); static int umcs7840_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != MCS7840_CONFIG_INDEX) return (ENXIO); if (uaa->info.bIfaceIndex != MCS7840_IFACE_INDEX) return (ENXIO); return (usbd_lookup_id_by_uaa(umcs7840_devs, sizeof(umcs7840_devs), uaa)); } static int umcs7840_attach(device_t dev) { struct usb_config umcs7840_config_tmp[UMCS7840_N_TRANSFERS]; struct usb_attach_arg *uaa = device_get_ivars(dev); struct umcs7840_softc *sc = device_get_softc(dev); uint8_t iface_index = MCS7840_IFACE_INDEX; int error; int subunit; int n; uint8_t data; for (n = 0; n < UMCS7840_N_TRANSFERS; ++n) umcs7840_config_tmp[n] = umcs7840_bulk_config_data[n]; device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "umcs7840", NULL, MTX_DEF); ucom_ref(&sc->sc_super_ucom); sc->sc_dev = dev; sc->sc_udev = uaa->device; /* * Get number of ports * Documentation (full datasheet) says, that number of ports is * set as MCS7840_DEV_MODE_SELECT24S bit in MODE R/Only * register. But vendor driver uses these undocumented * register & bit. * * Experiments show, that MODE register can have `0' * (4 ports) bit on 2-port device, so use vendor driver's way. * * Also, see notes in header file for these constants. */ umcs7840_get_reg_sync(sc, MCS7840_DEV_REG_GPIO, &data); if (data & MCS7840_DEV_GPIO_4PORTS) { sc->sc_numports = 4; /* Store physical port numbers in sc_portno */ sc->sc_ucom[0].sc_portno = 0; sc->sc_ucom[1].sc_portno = 1; sc->sc_ucom[2].sc_portno = 2; sc->sc_ucom[3].sc_portno = 3; } else { sc->sc_numports = 2; /* Store physical port numbers in sc_portno */ sc->sc_ucom[0].sc_portno = 0; sc->sc_ucom[1].sc_portno = 2; /* '1' is skipped */ } device_printf(dev, "Chip mcs%04x, found %d active ports\n", uaa->info.idProduct, sc->sc_numports); if (!umcs7840_get_reg_sync(sc, MCS7840_DEV_REG_MODE, &data)) { device_printf(dev, "On-die confguration: RST: active %s, HRD: %s, PLL: %s, POR: %s, Ports: %s, EEPROM write %s, IrDA is %savailable\n", (data & MCS7840_DEV_MODE_RESET) ? "low" : "high", (data & MCS7840_DEV_MODE_SER_PRSNT) ? "yes" : "no", (data & MCS7840_DEV_MODE_PLLBYPASS) ? "bypassed" : "avail", (data & MCS7840_DEV_MODE_PORBYPASS) ? "bypassed" : "avail", (data & MCS7840_DEV_MODE_SELECT24S) ? "2" : "4", (data & MCS7840_DEV_MODE_EEPROMWR) ? "enabled" : "disabled", (data & MCS7840_DEV_MODE_IRDA) ? "" : "not "); } /* Setup all transfers */ for (subunit = 0; subunit < sc->sc_numports; ++subunit) { for (n = 0; n < UMCS7840_N_TRANSFERS; ++n) { /* Set endpoint address */ umcs7840_config_tmp[n].endpoint = umcs7840_bulk_config_data[n].endpoint + 2 * sc->sc_ucom[subunit].sc_portno; umcs7840_config_tmp[n].callback = umcs7840_rw_callbacks[subunit][n]; } error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_ports[sc->sc_ucom[subunit].sc_portno].sc_xfer, umcs7840_config_tmp, UMCS7840_N_TRANSFERS, sc, &sc->sc_mtx); if (error) { device_printf(dev, "allocating USB transfers failed for subunit %d of %d\n", subunit + 1, sc->sc_numports); goto detach; } } error = usbd_transfer_setup(uaa->device, &iface_index, &sc->sc_intr_xfer, umcs7840_intr_config_data, 1, sc, &sc->sc_mtx); if (error) { device_printf(dev, "allocating USB transfers failed for interrupt\n"); goto detach; } /* clear stall at first run */ mtx_lock(&sc->sc_mtx); for (subunit = 0; subunit < sc->sc_numports; ++subunit) { usbd_xfer_set_stall(sc->sc_ports[sc->sc_ucom[subunit].sc_portno].sc_xfer[UMCS7840_BULK_RD_EP]); usbd_xfer_set_stall(sc->sc_ports[sc->sc_ucom[subunit].sc_portno].sc_xfer[UMCS7840_BULK_WR_EP]); } mtx_unlock(&sc->sc_mtx); error = ucom_attach(&sc->sc_super_ucom, sc->sc_ucom, sc->sc_numports, sc, &umcs7840_callback, &sc->sc_mtx); if (error) goto detach; ucom_set_pnpinfo_usb(&sc->sc_super_ucom, dev); return (0); detach: umcs7840_detach(dev); return (ENXIO); } static int umcs7840_detach(device_t dev) { struct umcs7840_softc *sc = device_get_softc(dev); int subunit; ucom_detach(&sc->sc_super_ucom, sc->sc_ucom); for (subunit = 0; subunit < sc->sc_numports; ++subunit) usbd_transfer_unsetup(sc->sc_ports[sc->sc_ucom[subunit].sc_portno].sc_xfer, UMCS7840_N_TRANSFERS); usbd_transfer_unsetup(&sc->sc_intr_xfer, 1); device_claim_softc(dev); umcs7840_free_softc(sc); return (0); } UCOM_UNLOAD_DRAIN(umcs7840); static void umcs7840_free_softc(struct umcs7840_softc *sc) { if (ucom_unref(&sc->sc_super_ucom)) { mtx_destroy(&sc->sc_mtx); device_free_softc(sc); } } static void umcs7840_free(struct ucom_softc *ucom) { umcs7840_free_softc(ucom->sc_parent); } static void umcs7840_cfg_open(struct ucom_softc *ucom) { struct umcs7840_softc *sc = ucom->sc_parent; uint16_t pn = ucom->sc_portno; uint8_t data; /* If it very first open, finish global configuration */ if (!sc->sc_driver_done) { /* * USB enumeration is finished, pass internal memory to FIFOs * If it is done in the end of "attach", kernel panics. */ if (umcs7840_get_reg_sync(sc, MCS7840_DEV_REG_CONTROL1, &data)) return; data |= MCS7840_DEV_CONTROL1_DRIVER_DONE; if (umcs7840_set_reg_sync(sc, MCS7840_DEV_REG_CONTROL1, data)) return; sc->sc_driver_done = 1; } /* Toggle reset bit on-off */ if (umcs7840_get_reg_sync(sc, umcs7840_port_registers[pn].reg_sp, &data)) return; data |= MCS7840_DEV_SPx_UART_RESET; if (umcs7840_set_reg_sync(sc, umcs7840_port_registers[pn].reg_sp, data)) return; data &= ~MCS7840_DEV_SPx_UART_RESET; if (umcs7840_set_reg_sync(sc, umcs7840_port_registers[pn].reg_sp, data)) return; /* Set RS-232 mode */ if (umcs7840_set_UART_reg_sync(sc, pn, MCS7840_UART_REG_SCRATCHPAD, MCS7840_UART_SCRATCHPAD_RS232)) return; /* Disable RX on time of initialization */ if (umcs7840_get_reg_sync(sc, umcs7840_port_registers[pn].reg_control, &data)) return; data |= MCS7840_DEV_CONTROLx_RX_DISABLE; if (umcs7840_set_reg_sync(sc, umcs7840_port_registers[pn].reg_control, data)) return; /* Disable all interrupts */ if (umcs7840_set_UART_reg_sync(sc, pn, MCS7840_UART_REG_IER, 0)) return; /* Reset FIFO -- documented */ if (umcs7840_set_UART_reg_sync(sc, pn, MCS7840_UART_REG_FCR, 0)) return; if (umcs7840_set_UART_reg_sync(sc, pn, MCS7840_UART_REG_FCR, MCS7840_UART_FCR_ENABLE | MCS7840_UART_FCR_FLUSHRHR | MCS7840_UART_FCR_FLUSHTHR | MCS7840_UART_FCR_RTL_1_14)) return; /* Set 8 bit, no parity, 1 stop bit -- documented */ sc->sc_ports[pn].sc_lcr = MCS7840_UART_LCR_DATALEN8 | MCS7840_UART_LCR_STOPB1; if (umcs7840_set_UART_reg_sync(sc, pn, MCS7840_UART_REG_LCR, sc->sc_ports[pn].sc_lcr)) return; /* * Enable DTR/RTS on modem control, enable modem interrupts -- * documented */ sc->sc_ports[pn].sc_mcr = MCS7840_UART_MCR_DTR | MCS7840_UART_MCR_RTS | MCS7840_UART_MCR_IE; if (umcs7840_set_UART_reg_sync(sc, pn, MCS7840_UART_REG_MCR, sc->sc_ports[pn].sc_mcr)) return; /* Clearing Bulkin and Bulkout FIFO */ if (umcs7840_get_reg_sync(sc, umcs7840_port_registers[pn].reg_sp, &data)) return; data |= MCS7840_DEV_SPx_RESET_OUT_FIFO | MCS7840_DEV_SPx_RESET_IN_FIFO; if (umcs7840_set_reg_sync(sc, umcs7840_port_registers[pn].reg_sp, data)) return; data &= ~(MCS7840_DEV_SPx_RESET_OUT_FIFO | MCS7840_DEV_SPx_RESET_IN_FIFO); if (umcs7840_set_reg_sync(sc, umcs7840_port_registers[pn].reg_sp, data)) return; /* Set speed 9600 */ if (umcs7840_set_baudrate(sc, pn, 9600)) return; /* Finally enable all interrupts -- documented */ /* * Copied from vendor driver, I don't know why we should read LCR * here */ if (umcs7840_get_UART_reg_sync(sc, pn, MCS7840_UART_REG_LCR, &sc->sc_ports[pn].sc_lcr)) return; if (umcs7840_set_UART_reg_sync(sc, pn, MCS7840_UART_REG_IER, MCS7840_UART_IER_RXSTAT | MCS7840_UART_IER_MODEM)) return; /* Enable RX */ if (umcs7840_get_reg_sync(sc, umcs7840_port_registers[pn].reg_control, &data)) return; data &= ~MCS7840_DEV_CONTROLx_RX_DISABLE; if (umcs7840_set_reg_sync(sc, umcs7840_port_registers[pn].reg_control, data)) return; DPRINTF("Port %d has been opened\n", pn); } static void umcs7840_cfg_close(struct ucom_softc *ucom) { struct umcs7840_softc *sc = ucom->sc_parent; uint16_t pn = ucom->sc_portno; uint8_t data; umcs7840_stop_read(ucom); umcs7840_stop_write(ucom); umcs7840_set_UART_reg_sync(sc, pn, MCS7840_UART_REG_MCR, 0); umcs7840_set_UART_reg_sync(sc, pn, MCS7840_UART_REG_IER, 0); /* Disable RX */ if (umcs7840_get_reg_sync(sc, umcs7840_port_registers[pn].reg_control, &data)) return; data |= MCS7840_DEV_CONTROLx_RX_DISABLE; if (umcs7840_set_reg_sync(sc, umcs7840_port_registers[pn].reg_control, data)) return; DPRINTF("Port %d has been closed\n", pn); } static void umcs7840_cfg_set_dtr(struct ucom_softc *ucom, uint8_t onoff) { struct umcs7840_softc *sc = ucom->sc_parent; uint8_t pn = ucom->sc_portno; if (onoff) sc->sc_ports[pn].sc_mcr |= MCS7840_UART_MCR_DTR; else sc->sc_ports[pn].sc_mcr &= ~MCS7840_UART_MCR_DTR; umcs7840_set_UART_reg_sync(sc, pn, MCS7840_UART_REG_MCR, sc->sc_ports[pn].sc_mcr); DPRINTF("Port %d DTR set to: %s\n", pn, onoff ? "on" : "off"); } static void umcs7840_cfg_set_rts(struct ucom_softc *ucom, uint8_t onoff) { struct umcs7840_softc *sc = ucom->sc_parent; uint8_t pn = ucom->sc_portno; if (onoff) sc->sc_ports[pn].sc_mcr |= MCS7840_UART_MCR_RTS; else sc->sc_ports[pn].sc_mcr &= ~MCS7840_UART_MCR_RTS; umcs7840_set_UART_reg_sync(sc, pn, MCS7840_UART_REG_MCR, sc->sc_ports[pn].sc_mcr); DPRINTF("Port %d RTS set to: %s\n", pn, onoff ? "on" : "off"); } static void umcs7840_cfg_set_break(struct ucom_softc *ucom, uint8_t onoff) { struct umcs7840_softc *sc = ucom->sc_parent; uint8_t pn = ucom->sc_portno; if (onoff) sc->sc_ports[pn].sc_lcr |= MCS7840_UART_LCR_BREAK; else sc->sc_ports[pn].sc_lcr &= ~MCS7840_UART_LCR_BREAK; umcs7840_set_UART_reg_sync(sc, pn, MCS7840_UART_REG_LCR, sc->sc_ports[pn].sc_lcr); DPRINTF("Port %d BREAK set to: %s\n", pn, onoff ? "on" : "off"); } static void umcs7840_cfg_param(struct ucom_softc *ucom, struct termios *t) { struct umcs7840_softc *sc = ucom->sc_parent; uint8_t pn = ucom->sc_portno; uint8_t lcr = sc->sc_ports[pn].sc_lcr; uint8_t mcr = sc->sc_ports[pn].sc_mcr; DPRINTF("Port %d config:\n", pn); if (t->c_cflag & CSTOPB) { DPRINTF(" 2 stop bits\n"); lcr |= MCS7840_UART_LCR_STOPB2; } else { lcr |= MCS7840_UART_LCR_STOPB1; DPRINTF(" 1 stop bit\n"); } lcr &= ~MCS7840_UART_LCR_PARITYMASK; if (t->c_cflag & PARENB) { lcr |= MCS7840_UART_LCR_PARITYON; if (t->c_cflag & PARODD) { lcr = MCS7840_UART_LCR_PARITYODD; DPRINTF(" parity on - odd\n"); } else { lcr = MCS7840_UART_LCR_PARITYEVEN; DPRINTF(" parity on - even\n"); } } else { lcr &= ~MCS7840_UART_LCR_PARITYON; DPRINTF(" parity off\n"); } lcr &= ~MCS7840_UART_LCR_DATALENMASK; switch (t->c_cflag & CSIZE) { case CS5: lcr |= MCS7840_UART_LCR_DATALEN5; DPRINTF(" 5 bit\n"); break; case CS6: lcr |= MCS7840_UART_LCR_DATALEN6; DPRINTF(" 6 bit\n"); break; case CS7: lcr |= MCS7840_UART_LCR_DATALEN7; DPRINTF(" 7 bit\n"); break; case CS8: lcr |= MCS7840_UART_LCR_DATALEN8; DPRINTF(" 8 bit\n"); break; } if (t->c_cflag & CRTSCTS) { mcr |= MCS7840_UART_MCR_CTSRTS; DPRINTF(" CTS/RTS\n"); } else mcr &= ~MCS7840_UART_MCR_CTSRTS; if (t->c_cflag & (CDTR_IFLOW | CDSR_OFLOW)) { mcr |= MCS7840_UART_MCR_DTRDSR; DPRINTF(" DTR/DSR\n"); } else mcr &= ~MCS7840_UART_MCR_DTRDSR; sc->sc_ports[pn].sc_lcr = lcr; umcs7840_set_UART_reg_sync(sc, pn, MCS7840_UART_REG_LCR, sc->sc_ports[pn].sc_lcr); DPRINTF("Port %d LCR=%02x\n", pn, sc->sc_ports[pn].sc_lcr); sc->sc_ports[pn].sc_mcr = mcr; umcs7840_set_UART_reg_sync(sc, pn, MCS7840_UART_REG_MCR, sc->sc_ports[pn].sc_mcr); DPRINTF("Port %d MCR=%02x\n", pn, sc->sc_ports[pn].sc_mcr); umcs7840_set_baudrate(sc, pn, t->c_ospeed); } static int umcs7840_pre_param(struct ucom_softc *ucom, struct termios *t) { uint8_t clk; uint16_t divisor; if (umcs7840_calc_baudrate(t->c_ospeed, &divisor, &clk) || !divisor) return (EINVAL); return (0); } static void umcs7840_start_read(struct ucom_softc *ucom) { struct umcs7840_softc *sc = ucom->sc_parent; uint8_t pn = ucom->sc_portno; /* Start interrupt transfer */ usbd_transfer_start(sc->sc_intr_xfer); /* Start read transfer */ usbd_transfer_start(sc->sc_ports[pn].sc_xfer[UMCS7840_BULK_RD_EP]); } static void umcs7840_stop_read(struct ucom_softc *ucom) { struct umcs7840_softc *sc = ucom->sc_parent; uint8_t pn = ucom->sc_portno; /* Stop read transfer */ usbd_transfer_stop(sc->sc_ports[pn].sc_xfer[UMCS7840_BULK_RD_EP]); } static void umcs7840_start_write(struct ucom_softc *ucom) { struct umcs7840_softc *sc = ucom->sc_parent; uint8_t pn = ucom->sc_portno; /* Start interrupt transfer */ usbd_transfer_start(sc->sc_intr_xfer); /* Start write transfer */ usbd_transfer_start(sc->sc_ports[pn].sc_xfer[UMCS7840_BULK_WR_EP]); } static void umcs7840_stop_write(struct ucom_softc *ucom) { struct umcs7840_softc *sc = ucom->sc_parent; uint8_t pn = ucom->sc_portno; /* Stop write transfer */ usbd_transfer_stop(sc->sc_ports[pn].sc_xfer[UMCS7840_BULK_WR_EP]); } static void umcs7840_cfg_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr) { struct umcs7840_softc *sc = ucom->sc_parent; uint8_t pn = ucom->sc_portno; uint8_t hw_lsr = 0; /* local line status register */ uint8_t hw_msr = 0; /* local modem status register */ /* Read LSR & MSR */ umcs7840_get_UART_reg_sync(sc, pn, MCS7840_UART_REG_LSR, &hw_lsr); umcs7840_get_UART_reg_sync(sc, pn, MCS7840_UART_REG_MSR, &hw_msr); *lsr = hw_lsr; *msr = hw_msr; DPRINTF("Port %d status: LSR=%02x MSR=%02x\n", ucom->sc_portno, *lsr, *msr); } static void umcs7840_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct umcs7840_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint8_t buf[13]; int actlen; int subunit; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen == 5 || actlen == 13) { pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, buf, actlen); /* Check status of all ports */ for (subunit = 0; subunit < sc->sc_numports; ++subunit) { uint8_t pn = sc->sc_ucom[subunit].sc_portno; if (buf[pn] & MCS7840_UART_ISR_NOPENDING) continue; DPRINTF("Port %d has pending interrupt: %02x (FIFO: %02x)\n", pn, buf[pn] & MCS7840_UART_ISR_INTMASK, buf[pn] & (~MCS7840_UART_ISR_INTMASK)); switch (buf[pn] & MCS7840_UART_ISR_INTMASK) { case MCS7840_UART_ISR_RXERR: case MCS7840_UART_ISR_RXHASDATA: case MCS7840_UART_ISR_RXTIMEOUT: case MCS7840_UART_ISR_MSCHANGE: ucom_status_change(&sc->sc_ucom[subunit]); break; default: /* Do nothing */ break; } } } else device_printf(sc->sc_dev, "Invalid interrupt data length %d", actlen); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void umcs7840_read_callback1(struct usb_xfer *xfer, usb_error_t error) { umcs7840_read_callbackN(xfer, error, 0); } static void umcs7840_read_callback2(struct usb_xfer *xfer, usb_error_t error) { umcs7840_read_callbackN(xfer, error, 1); } static void umcs7840_read_callback3(struct usb_xfer *xfer, usb_error_t error) { umcs7840_read_callbackN(xfer, error, 2); } static void umcs7840_read_callback4(struct usb_xfer *xfer, usb_error_t error) { umcs7840_read_callbackN(xfer, error, 3); } static void umcs7840_read_callbackN(struct usb_xfer *xfer, usb_error_t error, uint8_t subunit) { struct umcs7840_softc *sc = usbd_xfer_softc(xfer); struct ucom_softc *ucom = &sc->sc_ucom[subunit]; struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); DPRINTF("Port %d read, state = %d, data length = %d\n", ucom->sc_portno, USB_GET_STATE(xfer), actlen); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); ucom_put_data(ucom, pc, 0, actlen); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void umcs7840_write_callback1(struct usb_xfer *xfer, usb_error_t error) { umcs7840_write_callbackN(xfer, error, 0); } static void umcs7840_write_callback2(struct usb_xfer *xfer, usb_error_t error) { umcs7840_write_callbackN(xfer, error, 1); } static void umcs7840_write_callback3(struct usb_xfer *xfer, usb_error_t error) { umcs7840_write_callbackN(xfer, error, 2); } static void umcs7840_write_callback4(struct usb_xfer *xfer, usb_error_t error) { umcs7840_write_callbackN(xfer, error, 3); } static void umcs7840_write_callbackN(struct usb_xfer *xfer, usb_error_t error, uint8_t subunit) { struct umcs7840_softc *sc = usbd_xfer_softc(xfer); struct ucom_softc *ucom = &sc->sc_ucom[subunit]; struct usb_page_cache *pc; uint32_t actlen; DPRINTF("Port %d write, state = %d\n", ucom->sc_portno, USB_GET_STATE(xfer)); switch (USB_GET_STATE(xfer)) { case USB_ST_SETUP: case USB_ST_TRANSFERRED: tr_setup: pc = usbd_xfer_get_frame(xfer, 0); if (ucom_get_data(ucom, pc, 0, usbd_xfer_max_len(xfer), &actlen)) { DPRINTF("Port %d write, has %d bytes\n", ucom->sc_portno, actlen); usbd_xfer_set_frame_len(xfer, 0, actlen); usbd_transfer_submit(xfer); } return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void umcs7840_poll(struct ucom_softc *ucom) { struct umcs7840_softc *sc = ucom->sc_parent; DPRINTF("Port %d poll\n", ucom->sc_portno); usbd_transfer_poll(sc->sc_ports[ucom->sc_portno].sc_xfer, UMCS7840_N_TRANSFERS); usbd_transfer_poll(&sc->sc_intr_xfer, 1); } static usb_error_t umcs7840_get_reg_sync(struct umcs7840_softc *sc, uint8_t reg, uint8_t *data) { struct usb_device_request req; usb_error_t err; uint16_t len; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = MCS7840_RDREQ; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, UMCS7840_READ_LENGTH); err = usbd_do_request_proc(sc->sc_udev, &sc->sc_super_ucom.sc_tq, &req, (void *)data, 0, &len, UMCS7840_CTRL_TIMEOUT); if (err == USB_ERR_NORMAL_COMPLETION && len != 1) { device_printf(sc->sc_dev, "Reading register %d failed: invalid length %d\n", reg, len); return (USB_ERR_INVAL); } else if (err) device_printf(sc->sc_dev, "Reading register %d failed: %s\n", reg, usbd_errstr(err)); return (err); } static usb_error_t umcs7840_set_reg_sync(struct umcs7840_softc *sc, uint8_t reg, uint8_t data) { struct usb_device_request req; usb_error_t err; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = MCS7840_WRREQ; USETW(req.wValue, data); USETW(req.wIndex, reg); USETW(req.wLength, 0); err = usbd_do_request_proc(sc->sc_udev, &sc->sc_super_ucom.sc_tq, &req, NULL, 0, NULL, UMCS7840_CTRL_TIMEOUT); if (err) device_printf(sc->sc_dev, "Writing register %d failed: %s\n", reg, usbd_errstr(err)); return (err); } static usb_error_t umcs7840_get_UART_reg_sync(struct umcs7840_softc *sc, uint8_t portno, uint8_t reg, uint8_t *data) { struct usb_device_request req; uint16_t wVal; usb_error_t err; uint16_t len; /* portno is port number */ wVal = ((uint16_t)(portno + 1)) << 8; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = MCS7840_RDREQ; USETW(req.wValue, wVal); USETW(req.wIndex, reg); USETW(req.wLength, UMCS7840_READ_LENGTH); err = usbd_do_request_proc(sc->sc_udev, &sc->sc_super_ucom.sc_tq, &req, (void *)data, 0, &len, UMCS7840_CTRL_TIMEOUT); if (err == USB_ERR_NORMAL_COMPLETION && len != 1) { device_printf(sc->sc_dev, "Reading UART%d register %d failed: invalid length %d\n", portno, reg, len); return (USB_ERR_INVAL); } else if (err) device_printf(sc->sc_dev, "Reading UART%d register %d failed: %s\n", portno, reg, usbd_errstr(err)); return (err); } static usb_error_t umcs7840_set_UART_reg_sync(struct umcs7840_softc *sc, uint8_t portno, uint8_t reg, uint8_t data) { struct usb_device_request req; usb_error_t err; uint16_t wVal; /* portno is port number */ wVal = ((uint16_t)(portno + 1)) << 8 | data; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = MCS7840_WRREQ; USETW(req.wValue, wVal); USETW(req.wIndex, reg); USETW(req.wLength, 0); err = usbd_do_request_proc(sc->sc_udev, &sc->sc_super_ucom.sc_tq, &req, NULL, 0, NULL, UMCS7840_CTRL_TIMEOUT); if (err) device_printf(sc->sc_dev, "Writing UART%d register %d failed: %s\n", portno, reg, usbd_errstr(err)); return (err); } static usb_error_t umcs7840_set_baudrate(struct umcs7840_softc *sc, uint8_t portno, uint32_t rate) { usb_error_t err; uint16_t divisor; uint8_t clk; uint8_t data; if (umcs7840_calc_baudrate(rate, &divisor, &clk)) { DPRINTF("Port %d bad speed: %d\n", portno, rate); return (-1); } if (divisor == 0 || (clk & MCS7840_DEV_SPx_CLOCK_MASK) != clk) { DPRINTF("Port %d bad speed calculation: %d\n", portno, rate); return (-1); } DPRINTF("Port %d set speed: %d (%02x / %d)\n", portno, rate, clk, divisor); /* Set clock source for standard BAUD frequences */ err = umcs7840_get_reg_sync(sc, umcs7840_port_registers[portno].reg_sp, &data); if (err) return (err); data &= MCS7840_DEV_SPx_CLOCK_MASK; data |= clk; err = umcs7840_set_reg_sync(sc, umcs7840_port_registers[portno].reg_sp, data); if (err) return (err); /* Set divider */ sc->sc_ports[portno].sc_lcr |= MCS7840_UART_LCR_DIVISORS; err = umcs7840_set_UART_reg_sync(sc, portno, MCS7840_UART_REG_LCR, sc->sc_ports[portno].sc_lcr); if (err) return (err); err = umcs7840_set_UART_reg_sync(sc, portno, MCS7840_UART_REG_DLL, (uint8_t)(divisor & 0xff)); if (err) return (err); err = umcs7840_set_UART_reg_sync(sc, portno, MCS7840_UART_REG_DLM, (uint8_t)((divisor >> 8) & 0xff)); if (err) return (err); /* Turn off access to DLL/DLM registers of UART */ sc->sc_ports[portno].sc_lcr &= ~MCS7840_UART_LCR_DIVISORS; err = umcs7840_set_UART_reg_sync(sc, portno, MCS7840_UART_REG_LCR, sc->sc_ports[portno].sc_lcr); if (err) return (err); return (0); } /* Maximum speeds for standard frequences, when PLL is not used */ static const uint32_t umcs7840_baudrate_divisors[] = {0, 115200, 230400, 403200, 460800, 806400, 921600, 1572864, 3145728,}; static const uint8_t umcs7840_baudrate_divisors_len = sizeof(umcs7840_baudrate_divisors) / sizeof(umcs7840_baudrate_divisors[0]); static usb_error_t umcs7840_calc_baudrate(uint32_t rate, uint16_t *divisor, uint8_t *clk) { uint8_t i = 0; if (rate > umcs7840_baudrate_divisors[umcs7840_baudrate_divisors_len - 1]) return (-1); for (i = 0; i < umcs7840_baudrate_divisors_len - 1 && !(rate > umcs7840_baudrate_divisors[i] && rate <= umcs7840_baudrate_divisors[i + 1]); ++i); if (rate == 0) *divisor = 1; /* XXX */ else *divisor = umcs7840_baudrate_divisors[i + 1] / rate; /* 0x00 .. 0x70 */ *clk = i << MCS7840_DEV_SPx_CLOCK_SHIFT; return (0); } Index: head/sys/dev/usb/serial/umodem.c =================================================================== --- head/sys/dev/usb/serial/umodem.c (revision 276700) +++ head/sys/dev/usb/serial/umodem.c (revision 276701) @@ -1,908 +1,908 @@ /* $NetBSD: umodem.c,v 1.45 2002/09/23 05:51:23 simonb Exp $ */ #include __FBSDID("$FreeBSD$"); /*- * Copyright (c) 2003, M. Warner Losh . * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /*- * Copyright (c) 1998 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Lennart Augustsson (lennart@augustsson.net) at * Carlstedt Research & Technology. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Comm Class spec: http://www.usb.org/developers/devclass_docs/usbccs10.pdf * http://www.usb.org/developers/devclass_docs/usbcdc11.pdf * http://www.usb.org/developers/devclass_docs/cdc_wmc10.zip */ /* * TODO: * - Add error recovery in various places; the big problem is what * to do in a callback if there is an error. * - Implement a Call Device for modems without multiplexed commands. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #include #define USB_DEBUG_VAR umodem_debug #include #include #include #include #ifdef USB_DEBUG static int umodem_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, umodem, CTLFLAG_RW, 0, "USB umodem"); -SYSCTL_INT(_hw_usb_umodem, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_umodem, OID_AUTO, debug, CTLFLAG_RWTUN, &umodem_debug, 0, "Debug level"); #endif static const STRUCT_USB_HOST_ID umodem_devs[] = { /* Generic Modem class match */ {USB_IFACE_CLASS(UICLASS_CDC), USB_IFACE_SUBCLASS(UISUBCLASS_ABSTRACT_CONTROL_MODEL), USB_IFACE_PROTOCOL(UIPROTO_CDC_AT)}, {USB_IFACE_CLASS(UICLASS_CDC), USB_IFACE_SUBCLASS(UISUBCLASS_ABSTRACT_CONTROL_MODEL), USB_IFACE_PROTOCOL(UIPROTO_CDC_NONE)}, /* Huawei Modem class match */ {USB_VENDOR(USB_VENDOR_HUAWEI),USB_IFACE_CLASS(UICLASS_CDC), USB_IFACE_SUBCLASS(UISUBCLASS_ABSTRACT_CONTROL_MODEL), USB_IFACE_PROTOCOL(0xFF)}, /* Kyocera AH-K3001V */ {USB_VPI(USB_VENDOR_KYOCERA, USB_PRODUCT_KYOCERA_AHK3001V, 1)}, {USB_VPI(USB_VENDOR_SIERRA, USB_PRODUCT_SIERRA_MC5720, 1)}, {USB_VPI(USB_VENDOR_CURITEL, USB_PRODUCT_CURITEL_PC5740, 1)}, }; /* * As speeds for umodem devices increase, these numbers will need to * be increased. They should be good for G3 speeds and below. * * TODO: The TTY buffers should be increased! */ #define UMODEM_BUF_SIZE 1024 enum { UMODEM_BULK_WR, UMODEM_BULK_RD, UMODEM_INTR_RD, UMODEM_N_TRANSFER, }; #define UMODEM_MODVER 1 /* module version */ struct umodem_softc { struct ucom_super_softc sc_super_ucom; struct ucom_softc sc_ucom; struct usb_xfer *sc_xfer[UMODEM_N_TRANSFER]; struct usb_device *sc_udev; struct mtx sc_mtx; uint16_t sc_line; uint8_t sc_lsr; /* local status register */ uint8_t sc_msr; /* modem status register */ uint8_t sc_ctrl_iface_no; uint8_t sc_data_iface_no; uint8_t sc_iface_index[2]; uint8_t sc_cm_over_data; uint8_t sc_cm_cap; /* CM capabilities */ uint8_t sc_acm_cap; /* ACM capabilities */ }; static device_probe_t umodem_probe; static device_attach_t umodem_attach; static device_detach_t umodem_detach; static void umodem_free_softc(struct umodem_softc *); static usb_callback_t umodem_intr_callback; static usb_callback_t umodem_write_callback; static usb_callback_t umodem_read_callback; static void umodem_free(struct ucom_softc *); static void umodem_start_read(struct ucom_softc *); static void umodem_stop_read(struct ucom_softc *); static void umodem_start_write(struct ucom_softc *); static void umodem_stop_write(struct ucom_softc *); static void umodem_get_caps(struct usb_attach_arg *, uint8_t *, uint8_t *); static void umodem_cfg_get_status(struct ucom_softc *, uint8_t *, uint8_t *); static int umodem_pre_param(struct ucom_softc *, struct termios *); static void umodem_cfg_param(struct ucom_softc *, struct termios *); static int umodem_ioctl(struct ucom_softc *, uint32_t, caddr_t, int, struct thread *); static void umodem_cfg_set_dtr(struct ucom_softc *, uint8_t); static void umodem_cfg_set_rts(struct ucom_softc *, uint8_t); static void umodem_cfg_set_break(struct ucom_softc *, uint8_t); static void *umodem_get_desc(struct usb_attach_arg *, uint8_t, uint8_t); static usb_error_t umodem_set_comm_feature(struct usb_device *, uint8_t, uint16_t, uint16_t); static void umodem_poll(struct ucom_softc *ucom); static void umodem_find_data_iface(struct usb_attach_arg *uaa, uint8_t, uint8_t *, uint8_t *); static const struct usb_config umodem_config[UMODEM_N_TRANSFER] = { [UMODEM_BULK_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .if_index = 0, .bufsize = UMODEM_BUF_SIZE, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = &umodem_write_callback, }, [UMODEM_BULK_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .if_index = 0, .bufsize = UMODEM_BUF_SIZE, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &umodem_read_callback, }, [UMODEM_INTR_RD] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .if_index = 1, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,.no_pipe_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = &umodem_intr_callback, }, }; static const struct ucom_callback umodem_callback = { .ucom_cfg_get_status = &umodem_cfg_get_status, .ucom_cfg_set_dtr = &umodem_cfg_set_dtr, .ucom_cfg_set_rts = &umodem_cfg_set_rts, .ucom_cfg_set_break = &umodem_cfg_set_break, .ucom_cfg_param = &umodem_cfg_param, .ucom_pre_param = &umodem_pre_param, .ucom_ioctl = &umodem_ioctl, .ucom_start_read = &umodem_start_read, .ucom_stop_read = &umodem_stop_read, .ucom_start_write = &umodem_start_write, .ucom_stop_write = &umodem_stop_write, .ucom_poll = &umodem_poll, .ucom_free = &umodem_free, }; static device_method_t umodem_methods[] = { DEVMETHOD(device_probe, umodem_probe), DEVMETHOD(device_attach, umodem_attach), DEVMETHOD(device_detach, umodem_detach), DEVMETHOD_END }; static devclass_t umodem_devclass; static driver_t umodem_driver = { .name = "umodem", .methods = umodem_methods, .size = sizeof(struct umodem_softc), }; DRIVER_MODULE(umodem, uhub, umodem_driver, umodem_devclass, NULL, 0); MODULE_DEPEND(umodem, ucom, 1, 1, 1); MODULE_DEPEND(umodem, usb, 1, 1, 1); MODULE_VERSION(umodem, UMODEM_MODVER); static int umodem_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); int error; DPRINTFN(11, "\n"); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); error = usbd_lookup_id_by_uaa(umodem_devs, sizeof(umodem_devs), uaa); if (error) return (error); return (BUS_PROBE_GENERIC); } static int umodem_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct umodem_softc *sc = device_get_softc(dev); struct usb_cdc_cm_descriptor *cmd; struct usb_cdc_union_descriptor *cud; uint8_t i; int error; device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "umodem", NULL, MTX_DEF); ucom_ref(&sc->sc_super_ucom); sc->sc_ctrl_iface_no = uaa->info.bIfaceNum; sc->sc_iface_index[1] = uaa->info.bIfaceIndex; sc->sc_udev = uaa->device; umodem_get_caps(uaa, &sc->sc_cm_cap, &sc->sc_acm_cap); /* get the data interface number */ cmd = umodem_get_desc(uaa, UDESC_CS_INTERFACE, UDESCSUB_CDC_CM); if ((cmd == NULL) || (cmd->bLength < sizeof(*cmd))) { cud = usbd_find_descriptor(uaa->device, NULL, uaa->info.bIfaceIndex, UDESC_CS_INTERFACE, 0xFF, UDESCSUB_CDC_UNION, 0xFF); if ((cud == NULL) || (cud->bLength < sizeof(*cud))) { DPRINTF("Missing descriptor. " "Assuming data interface is next.\n"); if (sc->sc_ctrl_iface_no == 0xFF) { goto detach; } else { uint8_t class_match = 0; /* set default interface number */ sc->sc_data_iface_no = 0xFF; /* try to find the data interface backwards */ umodem_find_data_iface(uaa, uaa->info.bIfaceIndex - 1, &sc->sc_data_iface_no, &class_match); /* try to find the data interface forwards */ umodem_find_data_iface(uaa, uaa->info.bIfaceIndex + 1, &sc->sc_data_iface_no, &class_match); /* check if nothing was found */ if (sc->sc_data_iface_no == 0xFF) goto detach; } } else { sc->sc_data_iface_no = cud->bSlaveInterface[0]; } } else { sc->sc_data_iface_no = cmd->bDataInterface; } device_printf(dev, "data interface %d, has %sCM over " "data, has %sbreak\n", sc->sc_data_iface_no, sc->sc_cm_cap & USB_CDC_CM_OVER_DATA ? "" : "no ", sc->sc_acm_cap & USB_CDC_ACM_HAS_BREAK ? "" : "no "); /* get the data interface too */ for (i = 0;; i++) { struct usb_interface *iface; struct usb_interface_descriptor *id; iface = usbd_get_iface(uaa->device, i); if (iface) { id = usbd_get_interface_descriptor(iface); if (id && (id->bInterfaceNumber == sc->sc_data_iface_no)) { sc->sc_iface_index[0] = i; usbd_set_parent_iface(uaa->device, i, uaa->info.bIfaceIndex); break; } } else { device_printf(dev, "no data interface\n"); goto detach; } } if (usb_test_quirk(uaa, UQ_ASSUME_CM_OVER_DATA)) { sc->sc_cm_over_data = 1; } else { if (sc->sc_cm_cap & USB_CDC_CM_OVER_DATA) { if (sc->sc_acm_cap & USB_CDC_ACM_HAS_FEATURE) { error = umodem_set_comm_feature (uaa->device, sc->sc_ctrl_iface_no, UCDC_ABSTRACT_STATE, UCDC_DATA_MULTIPLEXED); /* ignore any errors */ } sc->sc_cm_over_data = 1; } } error = usbd_transfer_setup(uaa->device, sc->sc_iface_index, sc->sc_xfer, umodem_config, UMODEM_N_TRANSFER, sc, &sc->sc_mtx); if (error) { goto detach; } /* clear stall at first run */ mtx_lock(&sc->sc_mtx); usbd_xfer_set_stall(sc->sc_xfer[UMODEM_BULK_WR]); usbd_xfer_set_stall(sc->sc_xfer[UMODEM_BULK_RD]); mtx_unlock(&sc->sc_mtx); error = ucom_attach(&sc->sc_super_ucom, &sc->sc_ucom, 1, sc, &umodem_callback, &sc->sc_mtx); if (error) { goto detach; } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, dev); return (0); detach: umodem_detach(dev); return (ENXIO); } static void umodem_find_data_iface(struct usb_attach_arg *uaa, uint8_t iface_index, uint8_t *p_data_no, uint8_t *p_match_class) { struct usb_interface_descriptor *id; struct usb_interface *iface; iface = usbd_get_iface(uaa->device, iface_index); /* check for end of interfaces */ if (iface == NULL) return; id = usbd_get_interface_descriptor(iface); /* check for non-matching interface class */ if (id->bInterfaceClass != UICLASS_CDC_DATA || id->bInterfaceSubClass != UISUBCLASS_DATA) { /* if we got a class match then return */ if (*p_match_class) return; } else { *p_match_class = 1; } DPRINTFN(11, "Match at index %u\n", iface_index); *p_data_no = id->bInterfaceNumber; } static void umodem_start_read(struct ucom_softc *ucom) { struct umodem_softc *sc = ucom->sc_parent; /* start interrupt endpoint, if any */ usbd_transfer_start(sc->sc_xfer[UMODEM_INTR_RD]); /* start read endpoint */ usbd_transfer_start(sc->sc_xfer[UMODEM_BULK_RD]); } static void umodem_stop_read(struct ucom_softc *ucom) { struct umodem_softc *sc = ucom->sc_parent; /* stop interrupt endpoint, if any */ usbd_transfer_stop(sc->sc_xfer[UMODEM_INTR_RD]); /* stop read endpoint */ usbd_transfer_stop(sc->sc_xfer[UMODEM_BULK_RD]); } static void umodem_start_write(struct ucom_softc *ucom) { struct umodem_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[UMODEM_BULK_WR]); } static void umodem_stop_write(struct ucom_softc *ucom) { struct umodem_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[UMODEM_BULK_WR]); } static void umodem_get_caps(struct usb_attach_arg *uaa, uint8_t *cm, uint8_t *acm) { struct usb_cdc_cm_descriptor *cmd; struct usb_cdc_acm_descriptor *cad; cmd = umodem_get_desc(uaa, UDESC_CS_INTERFACE, UDESCSUB_CDC_CM); if ((cmd == NULL) || (cmd->bLength < sizeof(*cmd))) { DPRINTF("no CM desc (faking one)\n"); *cm = USB_CDC_CM_DOES_CM | USB_CDC_CM_OVER_DATA; } else *cm = cmd->bmCapabilities; cad = umodem_get_desc(uaa, UDESC_CS_INTERFACE, UDESCSUB_CDC_ACM); if ((cad == NULL) || (cad->bLength < sizeof(*cad))) { DPRINTF("no ACM desc\n"); *acm = 0; } else *acm = cad->bmCapabilities; } static void umodem_cfg_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr) { struct umodem_softc *sc = ucom->sc_parent; DPRINTF("\n"); *lsr = sc->sc_lsr; *msr = sc->sc_msr; } static int umodem_pre_param(struct ucom_softc *ucom, struct termios *t) { return (0); /* we accept anything */ } static void umodem_cfg_param(struct ucom_softc *ucom, struct termios *t) { struct umodem_softc *sc = ucom->sc_parent; struct usb_cdc_line_state ls; struct usb_device_request req; DPRINTF("sc=%p\n", sc); memset(&ls, 0, sizeof(ls)); USETDW(ls.dwDTERate, t->c_ospeed); ls.bCharFormat = (t->c_cflag & CSTOPB) ? UCDC_STOP_BIT_2 : UCDC_STOP_BIT_1; ls.bParityType = (t->c_cflag & PARENB) ? ((t->c_cflag & PARODD) ? UCDC_PARITY_ODD : UCDC_PARITY_EVEN) : UCDC_PARITY_NONE; switch (t->c_cflag & CSIZE) { case CS5: ls.bDataBits = 5; break; case CS6: ls.bDataBits = 6; break; case CS7: ls.bDataBits = 7; break; case CS8: ls.bDataBits = 8; break; } DPRINTF("rate=%d fmt=%d parity=%d bits=%d\n", UGETDW(ls.dwDTERate), ls.bCharFormat, ls.bParityType, ls.bDataBits); req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SET_LINE_CODING; USETW(req.wValue, 0); req.wIndex[0] = sc->sc_ctrl_iface_no; req.wIndex[1] = 0; USETW(req.wLength, sizeof(ls)); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, &ls, 0, 1000); } static int umodem_ioctl(struct ucom_softc *ucom, uint32_t cmd, caddr_t data, int flag, struct thread *td) { struct umodem_softc *sc = ucom->sc_parent; int error = 0; DPRINTF("cmd=0x%08x\n", cmd); switch (cmd) { case USB_GET_CM_OVER_DATA: *(int *)data = sc->sc_cm_over_data; break; case USB_SET_CM_OVER_DATA: if (*(int *)data != sc->sc_cm_over_data) { /* XXX change it */ } break; default: DPRINTF("unknown\n"); error = ENOIOCTL; break; } return (error); } static void umodem_cfg_set_dtr(struct ucom_softc *ucom, uint8_t onoff) { struct umodem_softc *sc = ucom->sc_parent; struct usb_device_request req; DPRINTF("onoff=%d\n", onoff); if (onoff) sc->sc_line |= UCDC_LINE_DTR; else sc->sc_line &= ~UCDC_LINE_DTR; req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SET_CONTROL_LINE_STATE; USETW(req.wValue, sc->sc_line); req.wIndex[0] = sc->sc_ctrl_iface_no; req.wIndex[1] = 0; USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); } static void umodem_cfg_set_rts(struct ucom_softc *ucom, uint8_t onoff) { struct umodem_softc *sc = ucom->sc_parent; struct usb_device_request req; DPRINTF("onoff=%d\n", onoff); if (onoff) sc->sc_line |= UCDC_LINE_RTS; else sc->sc_line &= ~UCDC_LINE_RTS; req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SET_CONTROL_LINE_STATE; USETW(req.wValue, sc->sc_line); req.wIndex[0] = sc->sc_ctrl_iface_no; req.wIndex[1] = 0; USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); } static void umodem_cfg_set_break(struct ucom_softc *ucom, uint8_t onoff) { struct umodem_softc *sc = ucom->sc_parent; struct usb_device_request req; uint16_t temp; DPRINTF("onoff=%d\n", onoff); if (sc->sc_acm_cap & USB_CDC_ACM_HAS_BREAK) { temp = onoff ? UCDC_BREAK_ON : UCDC_BREAK_OFF; req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SEND_BREAK; USETW(req.wValue, temp); req.wIndex[0] = sc->sc_ctrl_iface_no; req.wIndex[1] = 0; USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); } } static void umodem_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct usb_cdc_notification pkt; struct umodem_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint16_t wLen; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen < 8) { DPRINTF("received short packet, " "%d bytes\n", actlen); goto tr_setup; } if (actlen > (int)sizeof(pkt)) { DPRINTF("truncating message\n"); actlen = sizeof(pkt); } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, &pkt, actlen); actlen -= 8; wLen = UGETW(pkt.wLength); if (actlen > wLen) { actlen = wLen; } if (pkt.bmRequestType != UCDC_NOTIFICATION) { DPRINTF("unknown message type, " "0x%02x, on notify pipe!\n", pkt.bmRequestType); goto tr_setup; } switch (pkt.bNotification) { case UCDC_N_SERIAL_STATE: /* * Set the serial state in ucom driver based on * the bits from the notify message */ if (actlen < 2) { DPRINTF("invalid notification " "length, %d bytes!\n", actlen); break; } DPRINTF("notify bytes = %02x%02x\n", pkt.data[0], pkt.data[1]); /* Currently, lsr is always zero. */ sc->sc_lsr = 0; sc->sc_msr = 0; if (pkt.data[0] & UCDC_N_SERIAL_RI) { sc->sc_msr |= SER_RI; } if (pkt.data[0] & UCDC_N_SERIAL_DSR) { sc->sc_msr |= SER_DSR; } if (pkt.data[0] & UCDC_N_SERIAL_DCD) { sc->sc_msr |= SER_DCD; } ucom_status_change(&sc->sc_ucom); break; default: DPRINTF("unknown notify message: 0x%02x\n", pkt.bNotification); break; } case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void umodem_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct umodem_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint32_t actlen; switch (USB_GET_STATE(xfer)) { case USB_ST_SETUP: case USB_ST_TRANSFERRED: tr_setup: pc = usbd_xfer_get_frame(xfer, 0); if (ucom_get_data(&sc->sc_ucom, pc, 0, UMODEM_BUF_SIZE, &actlen)) { usbd_xfer_set_frame_len(xfer, 0, actlen); usbd_transfer_submit(xfer); } return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void umodem_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct umodem_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTF("actlen=%d\n", actlen); pc = usbd_xfer_get_frame(xfer, 0); ucom_put_data(&sc->sc_ucom, pc, 0, actlen); case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void * umodem_get_desc(struct usb_attach_arg *uaa, uint8_t type, uint8_t subtype) { return (usbd_find_descriptor(uaa->device, NULL, uaa->info.bIfaceIndex, type, 0xFF, subtype, 0xFF)); } static usb_error_t umodem_set_comm_feature(struct usb_device *udev, uint8_t iface_no, uint16_t feature, uint16_t state) { struct usb_device_request req; struct usb_cdc_abstract_state ast; DPRINTF("feature=%d state=%d\n", feature, state); req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SET_COMM_FEATURE; USETW(req.wValue, feature); req.wIndex[0] = iface_no; req.wIndex[1] = 0; USETW(req.wLength, UCDC_ABSTRACT_STATE_LENGTH); USETW(ast.wState, state); return (usbd_do_request(udev, NULL, &req, &ast)); } static int umodem_detach(device_t dev) { struct umodem_softc *sc = device_get_softc(dev); DPRINTF("sc=%p\n", sc); ucom_detach(&sc->sc_super_ucom, &sc->sc_ucom); usbd_transfer_unsetup(sc->sc_xfer, UMODEM_N_TRANSFER); device_claim_softc(dev); umodem_free_softc(sc); return (0); } UCOM_UNLOAD_DRAIN(umodem); static void umodem_free_softc(struct umodem_softc *sc) { if (ucom_unref(&sc->sc_super_ucom)) { mtx_destroy(&sc->sc_mtx); device_free_softc(sc); } } static void umodem_free(struct ucom_softc *ucom) { umodem_free_softc(ucom->sc_parent); } static void umodem_poll(struct ucom_softc *ucom) { struct umodem_softc *sc = ucom->sc_parent; usbd_transfer_poll(sc->sc_xfer, UMODEM_N_TRANSFER); } Index: head/sys/dev/usb/serial/umoscom.c =================================================================== --- head/sys/dev/usb/serial/umoscom.c (revision 276700) +++ head/sys/dev/usb/serial/umoscom.c (revision 276701) @@ -1,731 +1,731 @@ /* $FreeBSD$ */ /* $OpenBSD: umoscom.c,v 1.2 2006/10/26 06:02:43 jsg Exp $ */ /* * Copyright (c) 2006 Jonathan Gray * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR umoscom_debug #include #include #include #ifdef USB_DEBUG static int umoscom_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, umoscom, CTLFLAG_RW, 0, "USB umoscom"); -SYSCTL_INT(_hw_usb_umoscom, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_umoscom, OID_AUTO, debug, CTLFLAG_RWTUN, &umoscom_debug, 0, "Debug level"); #endif #define UMOSCOM_BUFSIZE 1024 /* bytes */ #define UMOSCOM_CONFIG_INDEX 0 #define UMOSCOM_IFACE_INDEX 0 /* interrupt packet */ #define UMOSCOM_IIR_RLS 0x06 #define UMOSCOM_IIR_RDA 0x04 #define UMOSCOM_IIR_CTI 0x0c #define UMOSCOM_IIR_THR 0x02 #define UMOSCOM_IIR_MS 0x00 /* registers */ #define UMOSCOM_READ 0x0d #define UMOSCOM_WRITE 0x0e #define UMOSCOM_UART_REG 0x0300 #define UMOSCOM_VEND_REG 0x0000 #define UMOSCOM_TXBUF 0x00 /* Write */ #define UMOSCOM_RXBUF 0x00 /* Read */ #define UMOSCOM_INT 0x01 #define UMOSCOM_FIFO 0x02 /* Write */ #define UMOSCOM_ISR 0x02 /* Read */ #define UMOSCOM_LCR 0x03 #define UMOSCOM_MCR 0x04 #define UMOSCOM_LSR 0x05 #define UMOSCOM_MSR 0x06 #define UMOSCOM_SCRATCH 0x07 #define UMOSCOM_DIV_LO 0x08 #define UMOSCOM_DIV_HI 0x09 #define UMOSCOM_EFR 0x0a #define UMOSCOM_XON1 0x0b #define UMOSCOM_XON2 0x0c #define UMOSCOM_XOFF1 0x0d #define UMOSCOM_XOFF2 0x0e #define UMOSCOM_BAUDLO 0x00 #define UMOSCOM_BAUDHI 0x01 #define UMOSCOM_INT_RXEN 0x01 #define UMOSCOM_INT_TXEN 0x02 #define UMOSCOM_INT_RSEN 0x04 #define UMOSCOM_INT_MDMEM 0x08 #define UMOSCOM_INT_SLEEP 0x10 #define UMOSCOM_INT_XOFF 0x20 #define UMOSCOM_INT_RTS 0x40 #define UMOSCOM_FIFO_EN 0x01 #define UMOSCOM_FIFO_RXCLR 0x02 #define UMOSCOM_FIFO_TXCLR 0x04 #define UMOSCOM_FIFO_DMA_BLK 0x08 #define UMOSCOM_FIFO_TXLVL_MASK 0x30 #define UMOSCOM_FIFO_TXLVL_8 0x00 #define UMOSCOM_FIFO_TXLVL_16 0x10 #define UMOSCOM_FIFO_TXLVL_32 0x20 #define UMOSCOM_FIFO_TXLVL_56 0x30 #define UMOSCOM_FIFO_RXLVL_MASK 0xc0 #define UMOSCOM_FIFO_RXLVL_8 0x00 #define UMOSCOM_FIFO_RXLVL_16 0x40 #define UMOSCOM_FIFO_RXLVL_56 0x80 #define UMOSCOM_FIFO_RXLVL_80 0xc0 #define UMOSCOM_ISR_MDM 0x00 #define UMOSCOM_ISR_NONE 0x01 #define UMOSCOM_ISR_TX 0x02 #define UMOSCOM_ISR_RX 0x04 #define UMOSCOM_ISR_LINE 0x06 #define UMOSCOM_ISR_RXTIMEOUT 0x0c #define UMOSCOM_ISR_RX_XOFF 0x10 #define UMOSCOM_ISR_RTSCTS 0x20 #define UMOSCOM_ISR_FIFOEN 0xc0 #define UMOSCOM_LCR_DBITS(x) ((x) - 5) #define UMOSCOM_LCR_STOP_BITS_1 0x00 #define UMOSCOM_LCR_STOP_BITS_2 0x04 /* 2 if 6-8 bits/char or 1.5 if 5 */ #define UMOSCOM_LCR_PARITY_NONE 0x00 #define UMOSCOM_LCR_PARITY_ODD 0x08 #define UMOSCOM_LCR_PARITY_EVEN 0x18 #define UMOSCOM_LCR_BREAK 0x40 #define UMOSCOM_LCR_DIVLATCH_EN 0x80 #define UMOSCOM_MCR_DTR 0x01 #define UMOSCOM_MCR_RTS 0x02 #define UMOSCOM_MCR_LOOP 0x04 #define UMOSCOM_MCR_INTEN 0x08 #define UMOSCOM_MCR_LOOPBACK 0x10 #define UMOSCOM_MCR_XONANY 0x20 #define UMOSCOM_MCR_IRDA_EN 0x40 #define UMOSCOM_MCR_BAUD_DIV4 0x80 #define UMOSCOM_LSR_RXDATA 0x01 #define UMOSCOM_LSR_RXOVER 0x02 #define UMOSCOM_LSR_RXPAR_ERR 0x04 #define UMOSCOM_LSR_RXFRM_ERR 0x08 #define UMOSCOM_LSR_RXBREAK 0x10 #define UMOSCOM_LSR_TXEMPTY 0x20 #define UMOSCOM_LSR_TXALLEMPTY 0x40 #define UMOSCOM_LSR_TXFIFO_ERR 0x80 #define UMOSCOM_MSR_CTS_CHG 0x01 #define UMOSCOM_MSR_DSR_CHG 0x02 #define UMOSCOM_MSR_RI_CHG 0x04 #define UMOSCOM_MSR_CD_CHG 0x08 #define UMOSCOM_MSR_CTS 0x10 #define UMOSCOM_MSR_RTS 0x20 #define UMOSCOM_MSR_RI 0x40 #define UMOSCOM_MSR_CD 0x80 #define UMOSCOM_BAUD_REF 115200 enum { UMOSCOM_BULK_DT_WR, UMOSCOM_BULK_DT_RD, UMOSCOM_INTR_DT_RD, UMOSCOM_N_TRANSFER, }; struct umoscom_softc { struct ucom_super_softc sc_super_ucom; struct ucom_softc sc_ucom; struct usb_xfer *sc_xfer[UMOSCOM_N_TRANSFER]; struct usb_device *sc_udev; struct mtx sc_mtx; uint8_t sc_mcr; uint8_t sc_lcr; }; /* prototypes */ static device_probe_t umoscom_probe; static device_attach_t umoscom_attach; static device_detach_t umoscom_detach; static void umoscom_free_softc(struct umoscom_softc *); static usb_callback_t umoscom_write_callback; static usb_callback_t umoscom_read_callback; static usb_callback_t umoscom_intr_callback; static void umoscom_free(struct ucom_softc *); static void umoscom_cfg_open(struct ucom_softc *); static void umoscom_cfg_close(struct ucom_softc *); static void umoscom_cfg_set_break(struct ucom_softc *, uint8_t); static void umoscom_cfg_set_dtr(struct ucom_softc *, uint8_t); static void umoscom_cfg_set_rts(struct ucom_softc *, uint8_t); static int umoscom_pre_param(struct ucom_softc *, struct termios *); static void umoscom_cfg_param(struct ucom_softc *, struct termios *); static void umoscom_cfg_get_status(struct ucom_softc *, uint8_t *, uint8_t *); static void umoscom_cfg_write(struct umoscom_softc *, uint16_t, uint16_t); static uint8_t umoscom_cfg_read(struct umoscom_softc *, uint16_t); static void umoscom_start_read(struct ucom_softc *); static void umoscom_stop_read(struct ucom_softc *); static void umoscom_start_write(struct ucom_softc *); static void umoscom_stop_write(struct ucom_softc *); static void umoscom_poll(struct ucom_softc *ucom); static const struct usb_config umoscom_config_data[UMOSCOM_N_TRANSFER] = { [UMOSCOM_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = UMOSCOM_BUFSIZE, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = &umoscom_write_callback, }, [UMOSCOM_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = UMOSCOM_BUFSIZE, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &umoscom_read_callback, }, [UMOSCOM_INTR_DT_RD] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = &umoscom_intr_callback, }, }; static const struct ucom_callback umoscom_callback = { /* configuration callbacks */ .ucom_cfg_get_status = &umoscom_cfg_get_status, .ucom_cfg_set_dtr = &umoscom_cfg_set_dtr, .ucom_cfg_set_rts = &umoscom_cfg_set_rts, .ucom_cfg_set_break = &umoscom_cfg_set_break, .ucom_cfg_param = &umoscom_cfg_param, .ucom_cfg_open = &umoscom_cfg_open, .ucom_cfg_close = &umoscom_cfg_close, /* other callbacks */ .ucom_pre_param = &umoscom_pre_param, .ucom_start_read = &umoscom_start_read, .ucom_stop_read = &umoscom_stop_read, .ucom_start_write = &umoscom_start_write, .ucom_stop_write = &umoscom_stop_write, .ucom_poll = &umoscom_poll, .ucom_free = &umoscom_free, }; static device_method_t umoscom_methods[] = { DEVMETHOD(device_probe, umoscom_probe), DEVMETHOD(device_attach, umoscom_attach), DEVMETHOD(device_detach, umoscom_detach), DEVMETHOD_END }; static devclass_t umoscom_devclass; static driver_t umoscom_driver = { .name = "umoscom", .methods = umoscom_methods, .size = sizeof(struct umoscom_softc), }; DRIVER_MODULE(umoscom, uhub, umoscom_driver, umoscom_devclass, NULL, 0); MODULE_DEPEND(umoscom, ucom, 1, 1, 1); MODULE_DEPEND(umoscom, usb, 1, 1, 1); MODULE_VERSION(umoscom, 1); static const STRUCT_USB_HOST_ID umoscom_devs[] = { {USB_VPI(USB_VENDOR_MOSCHIP, USB_PRODUCT_MOSCHIP_MCS7703, 0)} }; static int umoscom_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) { return (ENXIO); } if (uaa->info.bConfigIndex != UMOSCOM_CONFIG_INDEX) { return (ENXIO); } if (uaa->info.bIfaceIndex != UMOSCOM_IFACE_INDEX) { return (ENXIO); } return (usbd_lookup_id_by_uaa(umoscom_devs, sizeof(umoscom_devs), uaa)); } static int umoscom_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct umoscom_softc *sc = device_get_softc(dev); int error; uint8_t iface_index; sc->sc_udev = uaa->device; sc->sc_mcr = 0x08; /* enable interrupts */ /* XXX the device doesn't provide any ID string, so set a static one */ device_set_desc(dev, "MOSCHIP USB Serial Port Adapter"); device_printf(dev, "\n"); mtx_init(&sc->sc_mtx, "umoscom", NULL, MTX_DEF); ucom_ref(&sc->sc_super_ucom); iface_index = UMOSCOM_IFACE_INDEX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, umoscom_config_data, UMOSCOM_N_TRANSFER, sc, &sc->sc_mtx); if (error) { goto detach; } /* clear stall at first run */ mtx_lock(&sc->sc_mtx); usbd_xfer_set_stall(sc->sc_xfer[UMOSCOM_BULK_DT_WR]); usbd_xfer_set_stall(sc->sc_xfer[UMOSCOM_BULK_DT_RD]); mtx_unlock(&sc->sc_mtx); error = ucom_attach(&sc->sc_super_ucom, &sc->sc_ucom, 1, sc, &umoscom_callback, &sc->sc_mtx); if (error) { goto detach; } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, dev); return (0); detach: device_printf(dev, "attach error: %s\n", usbd_errstr(error)); umoscom_detach(dev); return (ENXIO); } static int umoscom_detach(device_t dev) { struct umoscom_softc *sc = device_get_softc(dev); ucom_detach(&sc->sc_super_ucom, &sc->sc_ucom); usbd_transfer_unsetup(sc->sc_xfer, UMOSCOM_N_TRANSFER); device_claim_softc(dev); umoscom_free_softc(sc); return (0); } UCOM_UNLOAD_DRAIN(umoscom); static void umoscom_free_softc(struct umoscom_softc *sc) { if (ucom_unref(&sc->sc_super_ucom)) { mtx_destroy(&sc->sc_mtx); device_free_softc(sc); } } static void umoscom_free(struct ucom_softc *ucom) { umoscom_free_softc(ucom->sc_parent); } static void umoscom_cfg_open(struct ucom_softc *ucom) { struct umoscom_softc *sc = ucom->sc_parent; DPRINTF("\n"); /* Purge FIFOs or odd things happen */ umoscom_cfg_write(sc, UMOSCOM_FIFO, 0x00 | UMOSCOM_UART_REG); /* Enable FIFO */ umoscom_cfg_write(sc, UMOSCOM_FIFO, UMOSCOM_FIFO_EN | UMOSCOM_FIFO_RXCLR | UMOSCOM_FIFO_TXCLR | UMOSCOM_FIFO_DMA_BLK | UMOSCOM_FIFO_RXLVL_MASK | UMOSCOM_UART_REG); /* Enable Interrupt Registers */ umoscom_cfg_write(sc, UMOSCOM_INT, 0x0C | UMOSCOM_UART_REG); /* Magic */ umoscom_cfg_write(sc, 0x01, 0x08); /* Magic */ umoscom_cfg_write(sc, 0x00, 0x02); } static void umoscom_cfg_close(struct ucom_softc *ucom) { return; } static void umoscom_cfg_set_break(struct ucom_softc *ucom, uint8_t onoff) { struct umoscom_softc *sc = ucom->sc_parent; uint16_t val; val = sc->sc_lcr; if (onoff) val |= UMOSCOM_LCR_BREAK; umoscom_cfg_write(sc, UMOSCOM_LCR, val | UMOSCOM_UART_REG); } static void umoscom_cfg_set_dtr(struct ucom_softc *ucom, uint8_t onoff) { struct umoscom_softc *sc = ucom->sc_parent; if (onoff) sc->sc_mcr |= UMOSCOM_MCR_DTR; else sc->sc_mcr &= ~UMOSCOM_MCR_DTR; umoscom_cfg_write(sc, UMOSCOM_MCR, sc->sc_mcr | UMOSCOM_UART_REG); } static void umoscom_cfg_set_rts(struct ucom_softc *ucom, uint8_t onoff) { struct umoscom_softc *sc = ucom->sc_parent; if (onoff) sc->sc_mcr |= UMOSCOM_MCR_RTS; else sc->sc_mcr &= ~UMOSCOM_MCR_RTS; umoscom_cfg_write(sc, UMOSCOM_MCR, sc->sc_mcr | UMOSCOM_UART_REG); } static int umoscom_pre_param(struct ucom_softc *ucom, struct termios *t) { if ((t->c_ospeed <= 1) || (t->c_ospeed > 115200)) return (EINVAL); return (0); } static void umoscom_cfg_param(struct ucom_softc *ucom, struct termios *t) { struct umoscom_softc *sc = ucom->sc_parent; uint16_t data; DPRINTF("speed=%d\n", t->c_ospeed); data = ((uint32_t)UMOSCOM_BAUD_REF) / ((uint32_t)t->c_ospeed); if (data == 0) { DPRINTF("invalid baud rate!\n"); return; } umoscom_cfg_write(sc, UMOSCOM_LCR, UMOSCOM_LCR_DIVLATCH_EN | UMOSCOM_UART_REG); umoscom_cfg_write(sc, UMOSCOM_BAUDLO, (data & 0xFF) | UMOSCOM_UART_REG); umoscom_cfg_write(sc, UMOSCOM_BAUDHI, ((data >> 8) & 0xFF) | UMOSCOM_UART_REG); if (t->c_cflag & CSTOPB) data = UMOSCOM_LCR_STOP_BITS_2; else data = UMOSCOM_LCR_STOP_BITS_1; if (t->c_cflag & PARENB) { if (t->c_cflag & PARODD) data |= UMOSCOM_LCR_PARITY_ODD; else data |= UMOSCOM_LCR_PARITY_EVEN; } else data |= UMOSCOM_LCR_PARITY_NONE; switch (t->c_cflag & CSIZE) { case CS5: data |= UMOSCOM_LCR_DBITS(5); break; case CS6: data |= UMOSCOM_LCR_DBITS(6); break; case CS7: data |= UMOSCOM_LCR_DBITS(7); break; case CS8: data |= UMOSCOM_LCR_DBITS(8); break; } sc->sc_lcr = data; umoscom_cfg_write(sc, UMOSCOM_LCR, data | UMOSCOM_UART_REG); } static void umoscom_cfg_get_status(struct ucom_softc *ucom, uint8_t *p_lsr, uint8_t *p_msr) { struct umoscom_softc *sc = ucom->sc_parent; uint8_t lsr; uint8_t msr; DPRINTFN(5, "\n"); /* read status registers */ lsr = umoscom_cfg_read(sc, UMOSCOM_LSR); msr = umoscom_cfg_read(sc, UMOSCOM_MSR); /* translate bits */ if (msr & UMOSCOM_MSR_CTS) *p_msr |= SER_CTS; if (msr & UMOSCOM_MSR_CD) *p_msr |= SER_DCD; if (msr & UMOSCOM_MSR_RI) *p_msr |= SER_RI; if (msr & UMOSCOM_MSR_RTS) *p_msr |= SER_DSR; } static void umoscom_cfg_write(struct umoscom_softc *sc, uint16_t reg, uint16_t val) { struct usb_device_request req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = UMOSCOM_WRITE; USETW(req.wValue, val); USETW(req.wIndex, reg); USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); } static uint8_t umoscom_cfg_read(struct umoscom_softc *sc, uint16_t reg) { struct usb_device_request req; uint8_t val; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = UMOSCOM_READ; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, 1); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, &val, 0, 1000); DPRINTF("reg=0x%04x, val=0x%02x\n", reg, val); return (val); } static void umoscom_start_read(struct ucom_softc *ucom) { struct umoscom_softc *sc = ucom->sc_parent; #if 0 /* start interrupt endpoint */ usbd_transfer_start(sc->sc_xfer[UMOSCOM_INTR_DT_RD]); #endif /* start read endpoint */ usbd_transfer_start(sc->sc_xfer[UMOSCOM_BULK_DT_RD]); } static void umoscom_stop_read(struct ucom_softc *ucom) { struct umoscom_softc *sc = ucom->sc_parent; /* stop interrupt transfer */ usbd_transfer_stop(sc->sc_xfer[UMOSCOM_INTR_DT_RD]); /* stop read endpoint */ usbd_transfer_stop(sc->sc_xfer[UMOSCOM_BULK_DT_RD]); } static void umoscom_start_write(struct ucom_softc *ucom) { struct umoscom_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[UMOSCOM_BULK_DT_WR]); } static void umoscom_stop_write(struct ucom_softc *ucom) { struct umoscom_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[UMOSCOM_BULK_DT_WR]); } static void umoscom_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct umoscom_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint32_t actlen; switch (USB_GET_STATE(xfer)) { case USB_ST_SETUP: case USB_ST_TRANSFERRED: tr_setup: DPRINTF("\n"); pc = usbd_xfer_get_frame(xfer, 0); if (ucom_get_data(&sc->sc_ucom, pc, 0, UMOSCOM_BUFSIZE, &actlen)) { usbd_xfer_set_frame_len(xfer, 0, actlen); usbd_transfer_submit(xfer); } return; default: /* Error */ if (error != USB_ERR_CANCELLED) { DPRINTFN(0, "transfer failed\n"); /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void umoscom_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct umoscom_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTF("got %d bytes\n", actlen); pc = usbd_xfer_get_frame(xfer, 0); ucom_put_data(&sc->sc_ucom, pc, 0, actlen); case USB_ST_SETUP: tr_setup: DPRINTF("\n"); usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { DPRINTFN(0, "transfer failed\n"); /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void umoscom_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct umoscom_softc *sc = usbd_xfer_softc(xfer); int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen < 2) { DPRINTF("too short message\n"); goto tr_setup; } ucom_status_change(&sc->sc_ucom); case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { DPRINTFN(0, "transfer failed\n"); /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void umoscom_poll(struct ucom_softc *ucom) { struct umoscom_softc *sc = ucom->sc_parent; usbd_transfer_poll(sc->sc_xfer, UMOSCOM_N_TRANSFER); } Index: head/sys/dev/usb/serial/uplcom.c =================================================================== --- head/sys/dev/usb/serial/uplcom.c (revision 276700) +++ head/sys/dev/usb/serial/uplcom.c (revision 276701) @@ -1,932 +1,932 @@ /* $NetBSD: uplcom.c,v 1.21 2001/11/13 06:24:56 lukem Exp $ */ #include __FBSDID("$FreeBSD$"); /*- * Copyright (c) 2001-2003, 2005 Shunsuke Akiyama . * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /*- * Copyright (c) 2001 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Ichiro FUKUHARA (ichiro@ichiro.org). * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * This driver supports several USB-to-RS232 serial adapters driven by * Prolific PL-2303, PL-2303X and probably PL-2303HX USB-to-RS232 * bridge chip. The adapters are sold under many different brand * names. * * Datasheets are available at Prolific www site at * http://www.prolific.com.tw. The datasheets don't contain full * programming information for the chip. * * PL-2303HX is probably programmed the same as PL-2303X. * * There are several differences between PL-2303 and PL-2303(H)X. * PL-2303(H)X can do higher bitrate in bulk mode, has _probably_ * different command for controlling CRTSCTS and needs special * sequence of commands for initialization which aren't also * documented in the datasheet. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR uplcom_debug #include #include #include #ifdef USB_DEBUG static int uplcom_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, uplcom, CTLFLAG_RW, 0, "USB uplcom"); -SYSCTL_INT(_hw_usb_uplcom, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_uplcom, OID_AUTO, debug, CTLFLAG_RWTUN, &uplcom_debug, 0, "Debug level"); #endif #define UPLCOM_MODVER 1 /* module version */ #define UPLCOM_CONFIG_INDEX 0 #define UPLCOM_IFACE_INDEX 0 #define UPLCOM_SECOND_IFACE_INDEX 1 #ifndef UPLCOM_INTR_INTERVAL #define UPLCOM_INTR_INTERVAL 0 /* default */ #endif #define UPLCOM_BULK_BUF_SIZE 1024 /* bytes */ #define UPLCOM_SET_REQUEST 0x01 #define UPLCOM_SET_CRTSCTS 0x41 #define UPLCOM_SET_CRTSCTS_PL2303X 0x61 #define RSAQ_STATUS_CTS 0x80 #define RSAQ_STATUS_DSR 0x02 #define RSAQ_STATUS_DCD 0x01 #define TYPE_PL2303 0 #define TYPE_PL2303HX 1 enum { UPLCOM_BULK_DT_WR, UPLCOM_BULK_DT_RD, UPLCOM_INTR_DT_RD, UPLCOM_N_TRANSFER, }; struct uplcom_softc { struct ucom_super_softc sc_super_ucom; struct ucom_softc sc_ucom; struct usb_xfer *sc_xfer[UPLCOM_N_TRANSFER]; struct usb_device *sc_udev; struct mtx sc_mtx; uint16_t sc_line; uint8_t sc_lsr; /* local status register */ uint8_t sc_msr; /* uplcom status register */ uint8_t sc_chiptype; /* type of chip */ uint8_t sc_ctrl_iface_no; uint8_t sc_data_iface_no; uint8_t sc_iface_index[2]; }; /* prototypes */ static usb_error_t uplcom_reset(struct uplcom_softc *, struct usb_device *); static usb_error_t uplcom_pl2303_do(struct usb_device *, int8_t, uint8_t, uint16_t, uint16_t, uint16_t); static int uplcom_pl2303_init(struct usb_device *, uint8_t); static void uplcom_free(struct ucom_softc *); static void uplcom_cfg_set_dtr(struct ucom_softc *, uint8_t); static void uplcom_cfg_set_rts(struct ucom_softc *, uint8_t); static void uplcom_cfg_set_break(struct ucom_softc *, uint8_t); static int uplcom_pre_param(struct ucom_softc *, struct termios *); static void uplcom_cfg_param(struct ucom_softc *, struct termios *); static void uplcom_start_read(struct ucom_softc *); static void uplcom_stop_read(struct ucom_softc *); static void uplcom_start_write(struct ucom_softc *); static void uplcom_stop_write(struct ucom_softc *); static void uplcom_cfg_get_status(struct ucom_softc *, uint8_t *, uint8_t *); static void uplcom_poll(struct ucom_softc *ucom); static device_probe_t uplcom_probe; static device_attach_t uplcom_attach; static device_detach_t uplcom_detach; static void uplcom_free_softc(struct uplcom_softc *); static usb_callback_t uplcom_intr_callback; static usb_callback_t uplcom_write_callback; static usb_callback_t uplcom_read_callback; static const struct usb_config uplcom_config_data[UPLCOM_N_TRANSFER] = { [UPLCOM_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = UPLCOM_BULK_BUF_SIZE, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = &uplcom_write_callback, .if_index = 0, }, [UPLCOM_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = UPLCOM_BULK_BUF_SIZE, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &uplcom_read_callback, .if_index = 0, }, [UPLCOM_INTR_DT_RD] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = &uplcom_intr_callback, .if_index = 1, }, }; static struct ucom_callback uplcom_callback = { .ucom_cfg_get_status = &uplcom_cfg_get_status, .ucom_cfg_set_dtr = &uplcom_cfg_set_dtr, .ucom_cfg_set_rts = &uplcom_cfg_set_rts, .ucom_cfg_set_break = &uplcom_cfg_set_break, .ucom_cfg_param = &uplcom_cfg_param, .ucom_pre_param = &uplcom_pre_param, .ucom_start_read = &uplcom_start_read, .ucom_stop_read = &uplcom_stop_read, .ucom_start_write = &uplcom_start_write, .ucom_stop_write = &uplcom_stop_write, .ucom_poll = &uplcom_poll, .ucom_free = &uplcom_free, }; #define UPLCOM_DEV(v,p) \ { USB_VENDOR(USB_VENDOR_##v), USB_PRODUCT(USB_PRODUCT_##v##_##p) } static const STRUCT_USB_HOST_ID uplcom_devs[] = { UPLCOM_DEV(ACERP, S81), /* BenQ S81 phone */ UPLCOM_DEV(ADLINK, ND6530), /* ADLINK ND-6530 USB-Serial */ UPLCOM_DEV(ALCATEL, OT535), /* Alcatel One Touch 535/735 */ UPLCOM_DEV(ALCOR, AU9720), /* Alcor AU9720 USB 2.0-RS232 */ UPLCOM_DEV(ANCHOR, SERIAL), /* Anchor Serial adapter */ UPLCOM_DEV(ATEN, UC232A), /* PLANEX USB-RS232 URS-03 */ UPLCOM_DEV(BELKIN, F5U257), /* Belkin F5U257 USB to Serial */ UPLCOM_DEV(COREGA, CGUSBRS232R), /* Corega CG-USBRS232R */ UPLCOM_DEV(EPSON, CRESSI_EDY), /* Cressi Edy diving computer */ UPLCOM_DEV(EPSON, N2ITION3), /* Zeagle N2iTion3 diving computer */ UPLCOM_DEV(ELECOM, UCSGT), /* ELECOM UC-SGT Serial Adapter */ UPLCOM_DEV(ELECOM, UCSGT0), /* ELECOM UC-SGT Serial Adapter */ UPLCOM_DEV(HAL, IMR001), /* HAL Corporation Crossam2+USB */ UPLCOM_DEV(HP, LD220), /* HP LD220 POS Display */ UPLCOM_DEV(IODATA, USBRSAQ), /* I/O DATA USB-RSAQ */ UPLCOM_DEV(IODATA, USBRSAQ5), /* I/O DATA USB-RSAQ5 */ UPLCOM_DEV(ITEGNO, WM1080A), /* iTegno WM1080A GSM/GFPRS modem */ UPLCOM_DEV(ITEGNO, WM2080A), /* iTegno WM2080A CDMA modem */ UPLCOM_DEV(LEADTEK, 9531), /* Leadtek 9531 GPS */ UPLCOM_DEV(MICROSOFT, 700WX), /* Microsoft Palm 700WX */ UPLCOM_DEV(MOBILEACTION, MA620), /* Mobile Action MA-620 Infrared Adapter */ UPLCOM_DEV(NETINDEX, WS002IN), /* Willcom W-S002IN */ UPLCOM_DEV(NOKIA2, CA42), /* Nokia CA-42 cable */ UPLCOM_DEV(OTI, DKU5), /* OTI DKU-5 cable */ UPLCOM_DEV(PANASONIC, TYTP50P6S), /* Panasonic TY-TP50P6-S flat screen */ UPLCOM_DEV(PLX, CA42), /* PLX CA-42 clone cable */ UPLCOM_DEV(PROLIFIC, ALLTRONIX_GPRS), /* Alltronix ACM003U00 modem */ UPLCOM_DEV(PROLIFIC, ALDIGA_AL11U), /* AlDiga AL-11U modem */ UPLCOM_DEV(PROLIFIC, DCU11), /* DCU-11 Phone Cable */ UPLCOM_DEV(PROLIFIC, HCR331), /* HCR331 Card Reader */ UPLCOM_DEV(PROLIFIC, MICROMAX_610U), /* Micromax 610U modem */ UPLCOM_DEV(PROLIFIC, MOTOROLA), /* Motorola cable */ UPLCOM_DEV(PROLIFIC, PHAROS), /* Prolific Pharos */ UPLCOM_DEV(PROLIFIC, PL2303), /* Generic adapter */ UPLCOM_DEV(PROLIFIC, RSAQ2), /* I/O DATA USB-RSAQ2 */ UPLCOM_DEV(PROLIFIC, RSAQ3), /* I/O DATA USB-RSAQ3 */ UPLCOM_DEV(PROLIFIC, UIC_MSR206), /* UIC MSR206 Card Reader */ UPLCOM_DEV(PROLIFIC2, PL2303), /* Prolific adapter */ UPLCOM_DEV(RADIOSHACK, USBCABLE), /* Radio Shack USB Adapter */ UPLCOM_DEV(RATOC, REXUSB60), /* RATOC REX-USB60 */ UPLCOM_DEV(SAGEM, USBSERIAL), /* Sagem USB-Serial Controller */ UPLCOM_DEV(SAMSUNG, I330), /* Samsung I330 phone cradle */ UPLCOM_DEV(SANWA, KB_USB2), /* Sanwa KB-USB2 Multimeter cable */ UPLCOM_DEV(SIEMENS3, EF81), /* Siemens EF81 */ UPLCOM_DEV(SIEMENS3, SX1), /* Siemens SX1 */ UPLCOM_DEV(SIEMENS3, X65), /* Siemens X65 */ UPLCOM_DEV(SIEMENS3, X75), /* Siemens X75 */ UPLCOM_DEV(SITECOM, SERIAL), /* Sitecom USB to Serial */ UPLCOM_DEV(SMART, PL2303), /* SMART Technologies USB to Serial */ UPLCOM_DEV(SONY, QN3), /* Sony QN3 phone cable */ UPLCOM_DEV(SONYERICSSON, DATAPILOT), /* Sony Ericsson Datapilot */ UPLCOM_DEV(SONYERICSSON, DCU10), /* Sony Ericsson DCU-10 Cable */ UPLCOM_DEV(SOURCENEXT, KEIKAI8), /* SOURCENEXT KeikaiDenwa 8 */ UPLCOM_DEV(SOURCENEXT, KEIKAI8_CHG), /* SOURCENEXT KeikaiDenwa 8 with charger */ UPLCOM_DEV(SPEEDDRAGON, MS3303H), /* Speed Dragon USB-Serial */ UPLCOM_DEV(SYNTECH, CPT8001C), /* Syntech CPT-8001C Barcode scanner */ UPLCOM_DEV(TDK, UHA6400), /* TDK USB-PHS Adapter UHA6400 */ UPLCOM_DEV(TDK, UPA9664), /* TDK USB-PHS Adapter UPA9664 */ UPLCOM_DEV(TRIPPLITE, U209), /* Tripp-Lite U209-000-R USB to Serial */ UPLCOM_DEV(YCCABLE, PL2303), /* YC Cable USB-Serial */ }; #undef UPLCOM_DEV static device_method_t uplcom_methods[] = { DEVMETHOD(device_probe, uplcom_probe), DEVMETHOD(device_attach, uplcom_attach), DEVMETHOD(device_detach, uplcom_detach), DEVMETHOD_END }; static devclass_t uplcom_devclass; static driver_t uplcom_driver = { .name = "uplcom", .methods = uplcom_methods, .size = sizeof(struct uplcom_softc), }; DRIVER_MODULE(uplcom, uhub, uplcom_driver, uplcom_devclass, NULL, 0); MODULE_DEPEND(uplcom, ucom, 1, 1, 1); MODULE_DEPEND(uplcom, usb, 1, 1, 1); MODULE_VERSION(uplcom, UPLCOM_MODVER); static int uplcom_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); DPRINTFN(11, "\n"); if (uaa->usb_mode != USB_MODE_HOST) { return (ENXIO); } if (uaa->info.bConfigIndex != UPLCOM_CONFIG_INDEX) { return (ENXIO); } if (uaa->info.bIfaceIndex != UPLCOM_IFACE_INDEX) { return (ENXIO); } return (usbd_lookup_id_by_uaa(uplcom_devs, sizeof(uplcom_devs), uaa)); } static int uplcom_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct uplcom_softc *sc = device_get_softc(dev); struct usb_interface *iface; struct usb_interface_descriptor *id; struct usb_device_descriptor *dd; int error; DPRINTFN(11, "\n"); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "uplcom", NULL, MTX_DEF); ucom_ref(&sc->sc_super_ucom); DPRINTF("sc = %p\n", sc); sc->sc_udev = uaa->device; /* Determine the chip type. This algorithm is taken from Linux. */ dd = usbd_get_device_descriptor(sc->sc_udev); if (dd->bDeviceClass == 0x02) sc->sc_chiptype = TYPE_PL2303; else if (dd->bMaxPacketSize == 0x40) sc->sc_chiptype = TYPE_PL2303HX; else sc->sc_chiptype = TYPE_PL2303; DPRINTF("chiptype: %s\n", (sc->sc_chiptype == TYPE_PL2303HX) ? "2303X" : "2303"); /* * USB-RSAQ1 has two interface * * USB-RSAQ1 | USB-RSAQ2 * -----------------+----------------- * Interface 0 |Interface 0 * Interrupt(0x81) | Interrupt(0x81) * -----------------+ BulkIN(0x02) * Interface 1 | BulkOUT(0x83) * BulkIN(0x02) | * BulkOUT(0x83) | */ sc->sc_ctrl_iface_no = uaa->info.bIfaceNum; sc->sc_iface_index[1] = UPLCOM_IFACE_INDEX; iface = usbd_get_iface(uaa->device, UPLCOM_SECOND_IFACE_INDEX); if (iface) { id = usbd_get_interface_descriptor(iface); if (id == NULL) { device_printf(dev, "no interface descriptor (2)\n"); goto detach; } sc->sc_data_iface_no = id->bInterfaceNumber; sc->sc_iface_index[0] = UPLCOM_SECOND_IFACE_INDEX; usbd_set_parent_iface(uaa->device, UPLCOM_SECOND_IFACE_INDEX, uaa->info.bIfaceIndex); } else { sc->sc_data_iface_no = sc->sc_ctrl_iface_no; sc->sc_iface_index[0] = UPLCOM_IFACE_INDEX; } error = usbd_transfer_setup(uaa->device, sc->sc_iface_index, sc->sc_xfer, uplcom_config_data, UPLCOM_N_TRANSFER, sc, &sc->sc_mtx); if (error) { DPRINTF("one or more missing USB endpoints, " "error=%s\n", usbd_errstr(error)); goto detach; } error = uplcom_reset(sc, uaa->device); if (error) { device_printf(dev, "reset failed, error=%s\n", usbd_errstr(error)); goto detach; } if (sc->sc_chiptype != TYPE_PL2303HX) { /* HX variants seem to lock up after a clear stall request. */ mtx_lock(&sc->sc_mtx); usbd_xfer_set_stall(sc->sc_xfer[UPLCOM_BULK_DT_WR]); usbd_xfer_set_stall(sc->sc_xfer[UPLCOM_BULK_DT_RD]); mtx_unlock(&sc->sc_mtx); } else { if (uplcom_pl2303_do(sc->sc_udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 8, 0, 0) || uplcom_pl2303_do(sc->sc_udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 9, 0, 0)) { goto detach; } } error = ucom_attach(&sc->sc_super_ucom, &sc->sc_ucom, 1, sc, &uplcom_callback, &sc->sc_mtx); if (error) { goto detach; } /* * do the initialization during attach so that the system does not * sleep during open: */ if (uplcom_pl2303_init(uaa->device, sc->sc_chiptype)) { device_printf(dev, "init failed\n"); goto detach; } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, dev); return (0); detach: uplcom_detach(dev); return (ENXIO); } static int uplcom_detach(device_t dev) { struct uplcom_softc *sc = device_get_softc(dev); DPRINTF("sc=%p\n", sc); ucom_detach(&sc->sc_super_ucom, &sc->sc_ucom); usbd_transfer_unsetup(sc->sc_xfer, UPLCOM_N_TRANSFER); device_claim_softc(dev); uplcom_free_softc(sc); return (0); } UCOM_UNLOAD_DRAIN(uplcom); static void uplcom_free_softc(struct uplcom_softc *sc) { if (ucom_unref(&sc->sc_super_ucom)) { mtx_destroy(&sc->sc_mtx); device_free_softc(sc); } } static void uplcom_free(struct ucom_softc *ucom) { uplcom_free_softc(ucom->sc_parent); } static usb_error_t uplcom_reset(struct uplcom_softc *sc, struct usb_device *udev) { struct usb_device_request req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = UPLCOM_SET_REQUEST; USETW(req.wValue, 0); req.wIndex[0] = sc->sc_data_iface_no; req.wIndex[1] = 0; USETW(req.wLength, 0); return (usbd_do_request(udev, NULL, &req, NULL)); } static usb_error_t uplcom_pl2303_do(struct usb_device *udev, int8_t req_type, uint8_t request, uint16_t value, uint16_t index, uint16_t length) { struct usb_device_request req; usb_error_t err; uint8_t buf[4]; req.bmRequestType = req_type; req.bRequest = request; USETW(req.wValue, value); USETW(req.wIndex, index); USETW(req.wLength, length); err = usbd_do_request(udev, NULL, &req, buf); if (err) { DPRINTF("error=%s\n", usbd_errstr(err)); return (1); } return (0); } static int uplcom_pl2303_init(struct usb_device *udev, uint8_t chiptype) { int err; if (uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8484, 0, 1) || uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x0404, 0, 0) || uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8484, 0, 1) || uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8383, 0, 1) || uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8484, 0, 1) || uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x0404, 1, 0) || uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8484, 0, 1) || uplcom_pl2303_do(udev, UT_READ_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0x8383, 0, 1) || uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 0, 1, 0) || uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 1, 0, 0)) return (EIO); if (chiptype == TYPE_PL2303HX) err = uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 2, 0x44, 0); else err = uplcom_pl2303_do(udev, UT_WRITE_VENDOR_DEVICE, UPLCOM_SET_REQUEST, 2, 0x24, 0); if (err) return (EIO); return (0); } static void uplcom_cfg_set_dtr(struct ucom_softc *ucom, uint8_t onoff) { struct uplcom_softc *sc = ucom->sc_parent; struct usb_device_request req; DPRINTF("onoff = %d\n", onoff); if (onoff) sc->sc_line |= UCDC_LINE_DTR; else sc->sc_line &= ~UCDC_LINE_DTR; req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SET_CONTROL_LINE_STATE; USETW(req.wValue, sc->sc_line); req.wIndex[0] = sc->sc_data_iface_no; req.wIndex[1] = 0; USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); } static void uplcom_cfg_set_rts(struct ucom_softc *ucom, uint8_t onoff) { struct uplcom_softc *sc = ucom->sc_parent; struct usb_device_request req; DPRINTF("onoff = %d\n", onoff); if (onoff) sc->sc_line |= UCDC_LINE_RTS; else sc->sc_line &= ~UCDC_LINE_RTS; req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SET_CONTROL_LINE_STATE; USETW(req.wValue, sc->sc_line); req.wIndex[0] = sc->sc_data_iface_no; req.wIndex[1] = 0; USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); } static void uplcom_cfg_set_break(struct ucom_softc *ucom, uint8_t onoff) { struct uplcom_softc *sc = ucom->sc_parent; struct usb_device_request req; uint16_t temp; DPRINTF("onoff = %d\n", onoff); temp = (onoff ? UCDC_BREAK_ON : UCDC_BREAK_OFF); req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SEND_BREAK; USETW(req.wValue, temp); req.wIndex[0] = sc->sc_data_iface_no; req.wIndex[1] = 0; USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); } static const uint32_t uplcom_rates[] = { 75, 150, 300, 600, 1200, 1800, 2400, 3600, 4800, 7200, 9600, 14400, 19200, 28800, 38400, 57600, 115200, /* * Higher speeds are probably possible. PL2303X supports up to * 6Mb and can set any rate */ 230400, 460800, 614400, 921600, 1228800 }; #define N_UPLCOM_RATES (sizeof(uplcom_rates)/sizeof(uplcom_rates[0])) static int uplcom_pre_param(struct ucom_softc *ucom, struct termios *t) { struct uplcom_softc *sc = ucom->sc_parent; uint8_t i; DPRINTF("\n"); /** * Check requested baud rate. * * The PL2303 can only set specific baud rates, up to 1228800 baud. * The PL2303X can set any baud rate up to 6Mb. * The PL2303HX rev. D can set any baud rate up to 12Mb. * * XXX: We currently cannot identify the PL2303HX rev. D, so treat * it the same as the PL2303X. */ if (sc->sc_chiptype != TYPE_PL2303HX) { for (i = 0; i < N_UPLCOM_RATES; i++) { if (uplcom_rates[i] == t->c_ospeed) return (0); } } else { if (t->c_ospeed <= 6000000) return (0); } DPRINTF("uplcom_param: bad baud rate (%d)\n", t->c_ospeed); return (EIO); } static void uplcom_cfg_param(struct ucom_softc *ucom, struct termios *t) { struct uplcom_softc *sc = ucom->sc_parent; struct usb_cdc_line_state ls; struct usb_device_request req; DPRINTF("sc = %p\n", sc); memset(&ls, 0, sizeof(ls)); USETDW(ls.dwDTERate, t->c_ospeed); if (t->c_cflag & CSTOPB) { ls.bCharFormat = UCDC_STOP_BIT_2; } else { ls.bCharFormat = UCDC_STOP_BIT_1; } if (t->c_cflag & PARENB) { if (t->c_cflag & PARODD) { ls.bParityType = UCDC_PARITY_ODD; } else { ls.bParityType = UCDC_PARITY_EVEN; } } else { ls.bParityType = UCDC_PARITY_NONE; } switch (t->c_cflag & CSIZE) { case CS5: ls.bDataBits = 5; break; case CS6: ls.bDataBits = 6; break; case CS7: ls.bDataBits = 7; break; case CS8: ls.bDataBits = 8; break; } DPRINTF("rate=%d fmt=%d parity=%d bits=%d\n", UGETDW(ls.dwDTERate), ls.bCharFormat, ls.bParityType, ls.bDataBits); req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UCDC_SET_LINE_CODING; USETW(req.wValue, 0); req.wIndex[0] = sc->sc_data_iface_no; req.wIndex[1] = 0; USETW(req.wLength, UCDC_LINE_STATE_LENGTH); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, &ls, 0, 1000); if (t->c_cflag & CRTSCTS) { DPRINTF("crtscts = on\n"); req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = UPLCOM_SET_REQUEST; USETW(req.wValue, 0); if (sc->sc_chiptype == TYPE_PL2303HX) USETW(req.wIndex, UPLCOM_SET_CRTSCTS_PL2303X); else USETW(req.wIndex, UPLCOM_SET_CRTSCTS); USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); } else { req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = UPLCOM_SET_REQUEST; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, 0); ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); } } static void uplcom_start_read(struct ucom_softc *ucom) { struct uplcom_softc *sc = ucom->sc_parent; /* start interrupt endpoint */ usbd_transfer_start(sc->sc_xfer[UPLCOM_INTR_DT_RD]); /* start read endpoint */ usbd_transfer_start(sc->sc_xfer[UPLCOM_BULK_DT_RD]); } static void uplcom_stop_read(struct ucom_softc *ucom) { struct uplcom_softc *sc = ucom->sc_parent; /* stop interrupt endpoint */ usbd_transfer_stop(sc->sc_xfer[UPLCOM_INTR_DT_RD]); /* stop read endpoint */ usbd_transfer_stop(sc->sc_xfer[UPLCOM_BULK_DT_RD]); } static void uplcom_start_write(struct ucom_softc *ucom) { struct uplcom_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[UPLCOM_BULK_DT_WR]); } static void uplcom_stop_write(struct ucom_softc *ucom) { struct uplcom_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[UPLCOM_BULK_DT_WR]); } static void uplcom_cfg_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr) { struct uplcom_softc *sc = ucom->sc_parent; DPRINTF("\n"); *lsr = sc->sc_lsr; *msr = sc->sc_msr; } static void uplcom_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct uplcom_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint8_t buf[9]; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTF("actlen = %u\n", actlen); if (actlen >= 9) { pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, buf, sizeof(buf)); DPRINTF("status = 0x%02x\n", buf[8]); sc->sc_lsr = 0; sc->sc_msr = 0; if (buf[8] & RSAQ_STATUS_CTS) { sc->sc_msr |= SER_CTS; } if (buf[8] & RSAQ_STATUS_DSR) { sc->sc_msr |= SER_DSR; } if (buf[8] & RSAQ_STATUS_DCD) { sc->sc_msr |= SER_DCD; } ucom_status_change(&sc->sc_ucom); } case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void uplcom_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct uplcom_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint32_t actlen; switch (USB_GET_STATE(xfer)) { case USB_ST_SETUP: case USB_ST_TRANSFERRED: tr_setup: pc = usbd_xfer_get_frame(xfer, 0); if (ucom_get_data(&sc->sc_ucom, pc, 0, UPLCOM_BULK_BUF_SIZE, &actlen)) { DPRINTF("actlen = %d\n", actlen); usbd_xfer_set_frame_len(xfer, 0, actlen); usbd_transfer_submit(xfer); } return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void uplcom_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct uplcom_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); ucom_put_data(&sc->sc_ucom, pc, 0, actlen); case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void uplcom_poll(struct ucom_softc *ucom) { struct uplcom_softc *sc = ucom->sc_parent; usbd_transfer_poll(sc->sc_xfer, UPLCOM_N_TRANSFER); } Index: head/sys/dev/usb/serial/usb_serial.c =================================================================== --- head/sys/dev/usb/serial/usb_serial.c (revision 276700) +++ head/sys/dev/usb/serial/usb_serial.c (revision 276701) @@ -1,1676 +1,1676 @@ /* $NetBSD: ucom.c,v 1.40 2001/11/13 06:24:54 lukem Exp $ */ /*- * Copyright (c) 2001-2003, 2005, 2008 * Shunsuke Akiyama . * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /*- * Copyright (c) 1998, 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Lennart Augustsson (lennart@augustsson.net) at * Carlstedt Research & Technology. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define USB_DEBUG_VAR ucom_debug #include #include #include #include #include "opt_gdb.h" static SYSCTL_NODE(_hw_usb, OID_AUTO, ucom, CTLFLAG_RW, 0, "USB ucom"); #ifdef USB_DEBUG static int ucom_debug = 0; -SYSCTL_INT(_hw_usb_ucom, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_ucom, OID_AUTO, debug, CTLFLAG_RWTUN, &ucom_debug, 0, "ucom debug level"); #endif #define UCOM_CONS_BUFSIZE 1024 static uint8_t ucom_cons_rx_buf[UCOM_CONS_BUFSIZE]; static uint8_t ucom_cons_tx_buf[UCOM_CONS_BUFSIZE]; static unsigned int ucom_cons_rx_low = 0; static unsigned int ucom_cons_rx_high = 0; static unsigned int ucom_cons_tx_low = 0; static unsigned int ucom_cons_tx_high = 0; static int ucom_cons_unit = -1; static int ucom_cons_subunit = 0; static int ucom_cons_baud = 9600; static struct ucom_softc *ucom_cons_softc = NULL; SYSCTL_INT(_hw_usb_ucom, OID_AUTO, cons_unit, CTLFLAG_RWTUN, &ucom_cons_unit, 0, "console unit number"); SYSCTL_INT(_hw_usb_ucom, OID_AUTO, cons_subunit, CTLFLAG_RWTUN, &ucom_cons_subunit, 0, "console subunit number"); SYSCTL_INT(_hw_usb_ucom, OID_AUTO, cons_baud, CTLFLAG_RWTUN, &ucom_cons_baud, 0, "console baud rate"); static usb_proc_callback_t ucom_cfg_start_transfers; static usb_proc_callback_t ucom_cfg_open; static usb_proc_callback_t ucom_cfg_close; static usb_proc_callback_t ucom_cfg_line_state; static usb_proc_callback_t ucom_cfg_status_change; static usb_proc_callback_t ucom_cfg_param; static int ucom_unit_alloc(void); static void ucom_unit_free(int); static int ucom_attach_tty(struct ucom_super_softc *, struct ucom_softc *); static void ucom_detach_tty(struct ucom_super_softc *, struct ucom_softc *); static void ucom_queue_command(struct ucom_softc *, usb_proc_callback_t *, struct termios *pt, struct usb_proc_msg *t0, struct usb_proc_msg *t1); static void ucom_shutdown(struct ucom_softc *); static void ucom_ring(struct ucom_softc *, uint8_t); static void ucom_break(struct ucom_softc *, uint8_t); static void ucom_dtr(struct ucom_softc *, uint8_t); static void ucom_rts(struct ucom_softc *, uint8_t); static tsw_open_t ucom_open; static tsw_close_t ucom_close; static tsw_ioctl_t ucom_ioctl; static tsw_modem_t ucom_modem; static tsw_param_t ucom_param; static tsw_outwakeup_t ucom_outwakeup; static tsw_inwakeup_t ucom_inwakeup; static tsw_free_t ucom_free; static struct ttydevsw ucom_class = { .tsw_flags = TF_INITLOCK | TF_CALLOUT, .tsw_open = ucom_open, .tsw_close = ucom_close, .tsw_outwakeup = ucom_outwakeup, .tsw_inwakeup = ucom_inwakeup, .tsw_ioctl = ucom_ioctl, .tsw_param = ucom_param, .tsw_modem = ucom_modem, .tsw_free = ucom_free, }; MODULE_DEPEND(ucom, usb, 1, 1, 1); MODULE_VERSION(ucom, 1); #define UCOM_UNIT_MAX 128 /* maximum number of units */ #define UCOM_TTY_PREFIX "U" static struct unrhdr *ucom_unrhdr; static struct mtx ucom_mtx; static int ucom_close_refs; static void ucom_init(void *arg) { DPRINTF("\n"); ucom_unrhdr = new_unrhdr(0, UCOM_UNIT_MAX - 1, NULL); mtx_init(&ucom_mtx, "UCOM MTX", NULL, MTX_DEF); } SYSINIT(ucom_init, SI_SUB_KLD - 1, SI_ORDER_ANY, ucom_init, NULL); static void ucom_uninit(void *arg) { struct unrhdr *hdr; hdr = ucom_unrhdr; ucom_unrhdr = NULL; DPRINTF("\n"); if (hdr != NULL) delete_unrhdr(hdr); mtx_destroy(&ucom_mtx); } SYSUNINIT(ucom_uninit, SI_SUB_KLD - 3, SI_ORDER_ANY, ucom_uninit, NULL); /* * Mark a unit number (the X in cuaUX) as in use. * * Note that devices using a different naming scheme (see ucom_tty_name() * callback) still use this unit allocation. */ static int ucom_unit_alloc(void) { int unit; /* sanity checks */ if (ucom_unrhdr == NULL) { DPRINTF("ucom_unrhdr is NULL\n"); return (-1); } unit = alloc_unr(ucom_unrhdr); DPRINTF("unit %d is allocated\n", unit); return (unit); } /* * Mark the unit number as not in use. */ static void ucom_unit_free(int unit) { /* sanity checks */ if (unit < 0 || unit >= UCOM_UNIT_MAX || ucom_unrhdr == NULL) { DPRINTF("cannot free unit number\n"); return; } DPRINTF("unit %d is freed\n", unit); free_unr(ucom_unrhdr, unit); } /* * Setup a group of one or more serial ports. * * The mutex pointed to by "mtx" is applied before all * callbacks are called back. Also "mtx" must be applied * before calling into the ucom-layer! */ int ucom_attach(struct ucom_super_softc *ssc, struct ucom_softc *sc, int subunits, void *parent, const struct ucom_callback *callback, struct mtx *mtx) { int subunit; int error = 0; if ((sc == NULL) || (subunits <= 0) || (callback == NULL) || (mtx == NULL)) { return (EINVAL); } /* allocate a uniq unit number */ ssc->sc_unit = ucom_unit_alloc(); if (ssc->sc_unit == -1) return (ENOMEM); /* generate TTY name string */ snprintf(ssc->sc_ttyname, sizeof(ssc->sc_ttyname), UCOM_TTY_PREFIX "%d", ssc->sc_unit); /* create USB request handling process */ error = usb_proc_create(&ssc->sc_tq, mtx, "ucom", USB_PRI_MED); if (error) { ucom_unit_free(ssc->sc_unit); return (error); } ssc->sc_subunits = subunits; ssc->sc_flag = UCOM_FLAG_ATTACHED | UCOM_FLAG_FREE_UNIT; if (callback->ucom_free == NULL) ssc->sc_flag |= UCOM_FLAG_WAIT_REFS; /* increment reference count */ ucom_ref(ssc); for (subunit = 0; subunit < ssc->sc_subunits; subunit++) { sc[subunit].sc_subunit = subunit; sc[subunit].sc_super = ssc; sc[subunit].sc_mtx = mtx; sc[subunit].sc_parent = parent; sc[subunit].sc_callback = callback; error = ucom_attach_tty(ssc, &sc[subunit]); if (error) { ucom_detach(ssc, &sc[0]); return (error); } /* increment reference count */ ucom_ref(ssc); /* set subunit attached */ sc[subunit].sc_flag |= UCOM_FLAG_ATTACHED; } DPRINTF("tp = %p, unit = %d, subunits = %d\n", sc->sc_tty, ssc->sc_unit, ssc->sc_subunits); return (0); } /* * The following function will do nothing if the structure pointed to * by "ssc" and "sc" is zero or has already been detached. */ void ucom_detach(struct ucom_super_softc *ssc, struct ucom_softc *sc) { int subunit; if (!(ssc->sc_flag & UCOM_FLAG_ATTACHED)) return; /* not initialized */ if (ssc->sc_sysctl_ttyname != NULL) { sysctl_remove_oid(ssc->sc_sysctl_ttyname, 1, 0); ssc->sc_sysctl_ttyname = NULL; } if (ssc->sc_sysctl_ttyports != NULL) { sysctl_remove_oid(ssc->sc_sysctl_ttyports, 1, 0); ssc->sc_sysctl_ttyports = NULL; } usb_proc_drain(&ssc->sc_tq); for (subunit = 0; subunit < ssc->sc_subunits; subunit++) { if (sc[subunit].sc_flag & UCOM_FLAG_ATTACHED) { ucom_detach_tty(ssc, &sc[subunit]); /* avoid duplicate detach */ sc[subunit].sc_flag &= ~UCOM_FLAG_ATTACHED; } } usb_proc_free(&ssc->sc_tq); ucom_unref(ssc); if (ssc->sc_flag & UCOM_FLAG_WAIT_REFS) ucom_drain(ssc); /* make sure we don't detach twice */ ssc->sc_flag &= ~UCOM_FLAG_ATTACHED; } void ucom_drain(struct ucom_super_softc *ssc) { mtx_lock(&ucom_mtx); while (ssc->sc_refs > 0) { printf("ucom: Waiting for a TTY device to close.\n"); usb_pause_mtx(&ucom_mtx, hz); } mtx_unlock(&ucom_mtx); } void ucom_drain_all(void *arg) { mtx_lock(&ucom_mtx); while (ucom_close_refs > 0) { printf("ucom: Waiting for all detached TTY " "devices to have open fds closed.\n"); usb_pause_mtx(&ucom_mtx, hz); } mtx_unlock(&ucom_mtx); } static int ucom_attach_tty(struct ucom_super_softc *ssc, struct ucom_softc *sc) { struct tty *tp; char buf[32]; /* temporary TTY device name buffer */ tp = tty_alloc_mutex(&ucom_class, sc, sc->sc_mtx); if (tp == NULL) return (ENOMEM); /* Check if the client has a custom TTY name */ buf[0] = '\0'; if (sc->sc_callback->ucom_tty_name) { sc->sc_callback->ucom_tty_name(sc, buf, sizeof(buf), ssc->sc_unit, sc->sc_subunit); } if (buf[0] == 0) { /* Use default TTY name */ if (ssc->sc_subunits > 1) { /* multiple modems in one */ snprintf(buf, sizeof(buf), UCOM_TTY_PREFIX "%u.%u", ssc->sc_unit, sc->sc_subunit); } else { /* single modem */ snprintf(buf, sizeof(buf), UCOM_TTY_PREFIX "%u", ssc->sc_unit); } } tty_makedev(tp, NULL, "%s", buf); sc->sc_tty = tp; DPRINTF("ttycreate: %s\n", buf); /* Check if this device should be a console */ if ((ucom_cons_softc == NULL) && (ssc->sc_unit == ucom_cons_unit) && (sc->sc_subunit == ucom_cons_subunit)) { DPRINTF("unit %d subunit %d is console", ssc->sc_unit, sc->sc_subunit); ucom_cons_softc = sc; tty_init_console(tp, ucom_cons_baud); UCOM_MTX_LOCK(ucom_cons_softc); ucom_cons_rx_low = 0; ucom_cons_rx_high = 0; ucom_cons_tx_low = 0; ucom_cons_tx_high = 0; sc->sc_flag |= UCOM_FLAG_CONSOLE; ucom_open(ucom_cons_softc->sc_tty); ucom_param(ucom_cons_softc->sc_tty, &tp->t_termios_init_in); UCOM_MTX_UNLOCK(ucom_cons_softc); } return (0); } static void ucom_detach_tty(struct ucom_super_softc *ssc, struct ucom_softc *sc) { struct tty *tp = sc->sc_tty; DPRINTF("sc = %p, tp = %p\n", sc, sc->sc_tty); if (sc->sc_flag & UCOM_FLAG_CONSOLE) { UCOM_MTX_LOCK(ucom_cons_softc); ucom_close(ucom_cons_softc->sc_tty); sc->sc_flag &= ~UCOM_FLAG_CONSOLE; UCOM_MTX_UNLOCK(ucom_cons_softc); ucom_cons_softc = NULL; } /* the config thread has been stopped when we get here */ UCOM_MTX_LOCK(sc); sc->sc_flag |= UCOM_FLAG_GONE; sc->sc_flag &= ~(UCOM_FLAG_HL_READY | UCOM_FLAG_LL_READY); UCOM_MTX_UNLOCK(sc); if (tp) { mtx_lock(&ucom_mtx); ucom_close_refs++; mtx_unlock(&ucom_mtx); tty_lock(tp); ucom_close(tp); /* close, if any */ tty_rel_gone(tp); UCOM_MTX_LOCK(sc); /* * make sure that read and write transfers are stopped */ if (sc->sc_callback->ucom_stop_read) (sc->sc_callback->ucom_stop_read) (sc); if (sc->sc_callback->ucom_stop_write) (sc->sc_callback->ucom_stop_write) (sc); UCOM_MTX_UNLOCK(sc); } } void ucom_set_pnpinfo_usb(struct ucom_super_softc *ssc, device_t dev) { char buf[64]; uint8_t iface_index; struct usb_attach_arg *uaa; snprintf(buf, sizeof(buf), "ttyname=" UCOM_TTY_PREFIX "%d ttyports=%d", ssc->sc_unit, ssc->sc_subunits); /* Store the PNP info in the first interface for the device */ uaa = device_get_ivars(dev); iface_index = uaa->info.bIfaceIndex; if (usbd_set_pnpinfo(uaa->device, iface_index, buf) != 0) device_printf(dev, "Could not set PNP info\n"); /* * The following information is also replicated in the PNP-info * string which is registered above: */ if (ssc->sc_sysctl_ttyname == NULL) { ssc->sc_sysctl_ttyname = SYSCTL_ADD_STRING(NULL, SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "ttyname", CTLFLAG_RD, ssc->sc_ttyname, 0, "TTY device basename"); } if (ssc->sc_sysctl_ttyports == NULL) { ssc->sc_sysctl_ttyports = SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "ttyports", CTLFLAG_RD, NULL, ssc->sc_subunits, "Number of ports"); } } static void ucom_queue_command(struct ucom_softc *sc, usb_proc_callback_t *fn, struct termios *pt, struct usb_proc_msg *t0, struct usb_proc_msg *t1) { struct ucom_super_softc *ssc = sc->sc_super; struct ucom_param_task *task; UCOM_MTX_ASSERT(sc, MA_OWNED); if (usb_proc_is_gone(&ssc->sc_tq)) { DPRINTF("proc is gone\n"); return; /* nothing to do */ } /* * NOTE: The task cannot get executed before we drop the * "sc_mtx" mutex. It is safe to update fields in the message * structure after that the message got queued. */ task = (struct ucom_param_task *) usb_proc_msignal(&ssc->sc_tq, t0, t1); /* Setup callback and softc pointers */ task->hdr.pm_callback = fn; task->sc = sc; /* * Make a copy of the termios. This field is only present if * the "pt" field is not NULL. */ if (pt != NULL) task->termios_copy = *pt; /* * Closing the device should be synchronous. */ if (fn == ucom_cfg_close) usb_proc_mwait(&ssc->sc_tq, t0, t1); /* * In case of multiple configure requests, * keep track of the last one! */ if (fn == ucom_cfg_start_transfers) sc->sc_last_start_xfer = &task->hdr; } static void ucom_shutdown(struct ucom_softc *sc) { struct tty *tp = sc->sc_tty; UCOM_MTX_ASSERT(sc, MA_OWNED); DPRINTF("\n"); /* * Hang up if necessary: */ if (tp->t_termios.c_cflag & HUPCL) { ucom_modem(tp, 0, SER_DTR); } } /* * Return values: * 0: normal * else: taskqueue is draining or gone */ uint8_t ucom_cfg_is_gone(struct ucom_softc *sc) { struct ucom_super_softc *ssc = sc->sc_super; return (usb_proc_is_gone(&ssc->sc_tq)); } static void ucom_cfg_start_transfers(struct usb_proc_msg *_task) { struct ucom_cfg_task *task = (struct ucom_cfg_task *)_task; struct ucom_softc *sc = task->sc; if (!(sc->sc_flag & UCOM_FLAG_LL_READY)) { return; } if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) { /* TTY device closed */ return; } if (_task == sc->sc_last_start_xfer) sc->sc_flag |= UCOM_FLAG_GP_DATA; if (sc->sc_callback->ucom_start_read) { (sc->sc_callback->ucom_start_read) (sc); } if (sc->sc_callback->ucom_start_write) { (sc->sc_callback->ucom_start_write) (sc); } } static void ucom_start_transfers(struct ucom_softc *sc) { if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) { return; } /* * Make sure that data transfers are started in both * directions: */ if (sc->sc_callback->ucom_start_read) { (sc->sc_callback->ucom_start_read) (sc); } if (sc->sc_callback->ucom_start_write) { (sc->sc_callback->ucom_start_write) (sc); } } static void ucom_cfg_open(struct usb_proc_msg *_task) { struct ucom_cfg_task *task = (struct ucom_cfg_task *)_task; struct ucom_softc *sc = task->sc; DPRINTF("\n"); if (sc->sc_flag & UCOM_FLAG_LL_READY) { /* already opened */ } else { sc->sc_flag |= UCOM_FLAG_LL_READY; if (sc->sc_callback->ucom_cfg_open) { (sc->sc_callback->ucom_cfg_open) (sc); /* wait a little */ usb_pause_mtx(sc->sc_mtx, hz / 10); } } } static int ucom_open(struct tty *tp) { struct ucom_softc *sc = tty_softc(tp); int error; UCOM_MTX_ASSERT(sc, MA_OWNED); if (sc->sc_flag & UCOM_FLAG_GONE) { return (ENXIO); } if (sc->sc_flag & UCOM_FLAG_HL_READY) { /* already opened */ return (0); } DPRINTF("tp = %p\n", tp); if (sc->sc_callback->ucom_pre_open) { /* * give the lower layer a chance to disallow TTY open, for * example if the device is not present: */ error = (sc->sc_callback->ucom_pre_open) (sc); if (error) { return (error); } } sc->sc_flag |= UCOM_FLAG_HL_READY; /* Disable transfers */ sc->sc_flag &= ~UCOM_FLAG_GP_DATA; sc->sc_lsr = 0; sc->sc_msr = 0; sc->sc_mcr = 0; /* reset programmed line state */ sc->sc_pls_curr = 0; sc->sc_pls_set = 0; sc->sc_pls_clr = 0; /* reset jitter buffer */ sc->sc_jitterbuf_in = 0; sc->sc_jitterbuf_out = 0; ucom_queue_command(sc, ucom_cfg_open, NULL, &sc->sc_open_task[0].hdr, &sc->sc_open_task[1].hdr); /* Queue transfer enable command last */ ucom_queue_command(sc, ucom_cfg_start_transfers, NULL, &sc->sc_start_task[0].hdr, &sc->sc_start_task[1].hdr); ucom_modem(tp, SER_DTR | SER_RTS, 0); ucom_ring(sc, 0); ucom_break(sc, 0); ucom_status_change(sc); return (0); } static void ucom_cfg_close(struct usb_proc_msg *_task) { struct ucom_cfg_task *task = (struct ucom_cfg_task *)_task; struct ucom_softc *sc = task->sc; DPRINTF("\n"); if (sc->sc_flag & UCOM_FLAG_LL_READY) { sc->sc_flag &= ~UCOM_FLAG_LL_READY; if (sc->sc_callback->ucom_cfg_close) (sc->sc_callback->ucom_cfg_close) (sc); } else { /* already closed */ } } static void ucom_close(struct tty *tp) { struct ucom_softc *sc = tty_softc(tp); UCOM_MTX_ASSERT(sc, MA_OWNED); DPRINTF("tp=%p\n", tp); if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) { DPRINTF("tp=%p already closed\n", tp); return; } ucom_shutdown(sc); ucom_queue_command(sc, ucom_cfg_close, NULL, &sc->sc_close_task[0].hdr, &sc->sc_close_task[1].hdr); sc->sc_flag &= ~(UCOM_FLAG_HL_READY | UCOM_FLAG_RTS_IFLOW); if (sc->sc_callback->ucom_stop_read) { (sc->sc_callback->ucom_stop_read) (sc); } } static void ucom_inwakeup(struct tty *tp) { struct ucom_softc *sc = tty_softc(tp); uint16_t pos; if (sc == NULL) return; UCOM_MTX_ASSERT(sc, MA_OWNED); DPRINTF("tp=%p\n", tp); if (ttydisc_can_bypass(tp) != 0 || (sc->sc_flag & UCOM_FLAG_HL_READY) == 0 || (sc->sc_flag & UCOM_FLAG_INWAKEUP) != 0) { return; } /* prevent recursion */ sc->sc_flag |= UCOM_FLAG_INWAKEUP; pos = sc->sc_jitterbuf_out; while (sc->sc_jitterbuf_in != pos) { int c; c = (char)sc->sc_jitterbuf[pos]; if (ttydisc_rint(tp, c, 0) == -1) break; pos++; if (pos >= UCOM_JITTERBUF_SIZE) pos -= UCOM_JITTERBUF_SIZE; } sc->sc_jitterbuf_out = pos; /* clear RTS in async fashion */ if ((sc->sc_jitterbuf_in == pos) && (sc->sc_flag & UCOM_FLAG_RTS_IFLOW)) ucom_rts(sc, 0); sc->sc_flag &= ~UCOM_FLAG_INWAKEUP; } static int ucom_ioctl(struct tty *tp, u_long cmd, caddr_t data, struct thread *td) { struct ucom_softc *sc = tty_softc(tp); int error; UCOM_MTX_ASSERT(sc, MA_OWNED); if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) { return (EIO); } DPRINTF("cmd = 0x%08lx\n", cmd); switch (cmd) { #if 0 case TIOCSRING: ucom_ring(sc, 1); error = 0; break; case TIOCCRING: ucom_ring(sc, 0); error = 0; break; #endif case TIOCSBRK: ucom_break(sc, 1); error = 0; break; case TIOCCBRK: ucom_break(sc, 0); error = 0; break; default: if (sc->sc_callback->ucom_ioctl) { error = (sc->sc_callback->ucom_ioctl) (sc, cmd, data, 0, td); } else { error = ENOIOCTL; } break; } return (error); } static int ucom_modem(struct tty *tp, int sigon, int sigoff) { struct ucom_softc *sc = tty_softc(tp); uint8_t onoff; UCOM_MTX_ASSERT(sc, MA_OWNED); if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) { return (0); } if ((sigon == 0) && (sigoff == 0)) { if (sc->sc_mcr & SER_DTR) { sigon |= SER_DTR; } if (sc->sc_mcr & SER_RTS) { sigon |= SER_RTS; } if (sc->sc_msr & SER_CTS) { sigon |= SER_CTS; } if (sc->sc_msr & SER_DCD) { sigon |= SER_DCD; } if (sc->sc_msr & SER_DSR) { sigon |= SER_DSR; } if (sc->sc_msr & SER_RI) { sigon |= SER_RI; } return (sigon); } if (sigon & SER_DTR) { sc->sc_mcr |= SER_DTR; } if (sigoff & SER_DTR) { sc->sc_mcr &= ~SER_DTR; } if (sigon & SER_RTS) { sc->sc_mcr |= SER_RTS; } if (sigoff & SER_RTS) { sc->sc_mcr &= ~SER_RTS; } onoff = (sc->sc_mcr & SER_DTR) ? 1 : 0; ucom_dtr(sc, onoff); onoff = (sc->sc_mcr & SER_RTS) ? 1 : 0; ucom_rts(sc, onoff); return (0); } static void ucom_cfg_line_state(struct usb_proc_msg *_task) { struct ucom_cfg_task *task = (struct ucom_cfg_task *)_task; struct ucom_softc *sc = task->sc; uint8_t notch_bits; uint8_t any_bits; uint8_t prev_value; uint8_t last_value; uint8_t mask; if (!(sc->sc_flag & UCOM_FLAG_LL_READY)) { return; } mask = 0; /* compute callback mask */ if (sc->sc_callback->ucom_cfg_set_dtr) mask |= UCOM_LS_DTR; if (sc->sc_callback->ucom_cfg_set_rts) mask |= UCOM_LS_RTS; if (sc->sc_callback->ucom_cfg_set_break) mask |= UCOM_LS_BREAK; if (sc->sc_callback->ucom_cfg_set_ring) mask |= UCOM_LS_RING; /* compute the bits we are to program */ notch_bits = (sc->sc_pls_set & sc->sc_pls_clr) & mask; any_bits = (sc->sc_pls_set | sc->sc_pls_clr) & mask; prev_value = sc->sc_pls_curr ^ notch_bits; last_value = sc->sc_pls_curr; /* reset programmed line state */ sc->sc_pls_curr = 0; sc->sc_pls_set = 0; sc->sc_pls_clr = 0; /* ensure that we don't lose any levels */ if (notch_bits & UCOM_LS_DTR) sc->sc_callback->ucom_cfg_set_dtr(sc, (prev_value & UCOM_LS_DTR) ? 1 : 0); if (notch_bits & UCOM_LS_RTS) sc->sc_callback->ucom_cfg_set_rts(sc, (prev_value & UCOM_LS_RTS) ? 1 : 0); if (notch_bits & UCOM_LS_BREAK) sc->sc_callback->ucom_cfg_set_break(sc, (prev_value & UCOM_LS_BREAK) ? 1 : 0); if (notch_bits & UCOM_LS_RING) sc->sc_callback->ucom_cfg_set_ring(sc, (prev_value & UCOM_LS_RING) ? 1 : 0); /* set last value */ if (any_bits & UCOM_LS_DTR) sc->sc_callback->ucom_cfg_set_dtr(sc, (last_value & UCOM_LS_DTR) ? 1 : 0); if (any_bits & UCOM_LS_RTS) sc->sc_callback->ucom_cfg_set_rts(sc, (last_value & UCOM_LS_RTS) ? 1 : 0); if (any_bits & UCOM_LS_BREAK) sc->sc_callback->ucom_cfg_set_break(sc, (last_value & UCOM_LS_BREAK) ? 1 : 0); if (any_bits & UCOM_LS_RING) sc->sc_callback->ucom_cfg_set_ring(sc, (last_value & UCOM_LS_RING) ? 1 : 0); } static void ucom_line_state(struct ucom_softc *sc, uint8_t set_bits, uint8_t clear_bits) { UCOM_MTX_ASSERT(sc, MA_OWNED); if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) { return; } DPRINTF("on=0x%02x, off=0x%02x\n", set_bits, clear_bits); /* update current programmed line state */ sc->sc_pls_curr |= set_bits; sc->sc_pls_curr &= ~clear_bits; sc->sc_pls_set |= set_bits; sc->sc_pls_clr |= clear_bits; /* defer driver programming */ ucom_queue_command(sc, ucom_cfg_line_state, NULL, &sc->sc_line_state_task[0].hdr, &sc->sc_line_state_task[1].hdr); } static void ucom_ring(struct ucom_softc *sc, uint8_t onoff) { DPRINTF("onoff = %d\n", onoff); if (onoff) ucom_line_state(sc, UCOM_LS_RING, 0); else ucom_line_state(sc, 0, UCOM_LS_RING); } static void ucom_break(struct ucom_softc *sc, uint8_t onoff) { DPRINTF("onoff = %d\n", onoff); if (onoff) ucom_line_state(sc, UCOM_LS_BREAK, 0); else ucom_line_state(sc, 0, UCOM_LS_BREAK); } static void ucom_dtr(struct ucom_softc *sc, uint8_t onoff) { DPRINTF("onoff = %d\n", onoff); if (onoff) ucom_line_state(sc, UCOM_LS_DTR, 0); else ucom_line_state(sc, 0, UCOM_LS_DTR); } static void ucom_rts(struct ucom_softc *sc, uint8_t onoff) { DPRINTF("onoff = %d\n", onoff); if (onoff) ucom_line_state(sc, UCOM_LS_RTS, 0); else ucom_line_state(sc, 0, UCOM_LS_RTS); } static void ucom_cfg_status_change(struct usb_proc_msg *_task) { struct ucom_cfg_task *task = (struct ucom_cfg_task *)_task; struct ucom_softc *sc = task->sc; struct tty *tp; uint8_t new_msr; uint8_t new_lsr; uint8_t onoff; uint8_t lsr_delta; tp = sc->sc_tty; UCOM_MTX_ASSERT(sc, MA_OWNED); if (!(sc->sc_flag & UCOM_FLAG_LL_READY)) { return; } if (sc->sc_callback->ucom_cfg_get_status == NULL) { return; } /* get status */ new_msr = 0; new_lsr = 0; (sc->sc_callback->ucom_cfg_get_status) (sc, &new_lsr, &new_msr); if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) { /* TTY device closed */ return; } onoff = ((sc->sc_msr ^ new_msr) & SER_DCD); lsr_delta = (sc->sc_lsr ^ new_lsr); sc->sc_msr = new_msr; sc->sc_lsr = new_lsr; if (onoff) { onoff = (sc->sc_msr & SER_DCD) ? 1 : 0; DPRINTF("DCD changed to %d\n", onoff); ttydisc_modem(tp, onoff); } if ((lsr_delta & ULSR_BI) && (sc->sc_lsr & ULSR_BI)) { DPRINTF("BREAK detected\n"); ttydisc_rint(tp, 0, TRE_BREAK); ttydisc_rint_done(tp); } if ((lsr_delta & ULSR_FE) && (sc->sc_lsr & ULSR_FE)) { DPRINTF("Frame error detected\n"); ttydisc_rint(tp, 0, TRE_FRAMING); ttydisc_rint_done(tp); } if ((lsr_delta & ULSR_PE) && (sc->sc_lsr & ULSR_PE)) { DPRINTF("Parity error detected\n"); ttydisc_rint(tp, 0, TRE_PARITY); ttydisc_rint_done(tp); } } void ucom_status_change(struct ucom_softc *sc) { UCOM_MTX_ASSERT(sc, MA_OWNED); if (sc->sc_flag & UCOM_FLAG_CONSOLE) return; /* not supported */ if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) { return; } DPRINTF("\n"); ucom_queue_command(sc, ucom_cfg_status_change, NULL, &sc->sc_status_task[0].hdr, &sc->sc_status_task[1].hdr); } static void ucom_cfg_param(struct usb_proc_msg *_task) { struct ucom_param_task *task = (struct ucom_param_task *)_task; struct ucom_softc *sc = task->sc; if (!(sc->sc_flag & UCOM_FLAG_LL_READY)) { return; } if (sc->sc_callback->ucom_cfg_param == NULL) { return; } (sc->sc_callback->ucom_cfg_param) (sc, &task->termios_copy); /* wait a little */ usb_pause_mtx(sc->sc_mtx, hz / 10); } static int ucom_param(struct tty *tp, struct termios *t) { struct ucom_softc *sc = tty_softc(tp); uint8_t opened; int error; UCOM_MTX_ASSERT(sc, MA_OWNED); opened = 0; error = 0; if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) { /* XXX the TTY layer should call "open()" first! */ /* * Not quite: Its ordering is partly backwards, but * some parameters must be set early in ttydev_open(), * possibly before calling ttydevsw_open(). */ error = ucom_open(tp); if (error) goto done; opened = 1; } DPRINTF("sc = %p\n", sc); /* Check requested parameters. */ if (t->c_ispeed && (t->c_ispeed != t->c_ospeed)) { /* XXX c_ospeed == 0 is perfectly valid. */ DPRINTF("mismatch ispeed and ospeed\n"); error = EINVAL; goto done; } t->c_ispeed = t->c_ospeed; if (sc->sc_callback->ucom_pre_param) { /* Let the lower layer verify the parameters */ error = (sc->sc_callback->ucom_pre_param) (sc, t); if (error) { DPRINTF("callback error = %d\n", error); goto done; } } /* Disable transfers */ sc->sc_flag &= ~UCOM_FLAG_GP_DATA; /* Queue baud rate programming command first */ ucom_queue_command(sc, ucom_cfg_param, t, &sc->sc_param_task[0].hdr, &sc->sc_param_task[1].hdr); /* Queue transfer enable command last */ ucom_queue_command(sc, ucom_cfg_start_transfers, NULL, &sc->sc_start_task[0].hdr, &sc->sc_start_task[1].hdr); if (t->c_cflag & CRTS_IFLOW) { sc->sc_flag |= UCOM_FLAG_RTS_IFLOW; } else if (sc->sc_flag & UCOM_FLAG_RTS_IFLOW) { sc->sc_flag &= ~UCOM_FLAG_RTS_IFLOW; ucom_modem(tp, SER_RTS, 0); } done: if (error) { if (opened) { ucom_close(tp); } } return (error); } static void ucom_outwakeup(struct tty *tp) { struct ucom_softc *sc = tty_softc(tp); UCOM_MTX_ASSERT(sc, MA_OWNED); DPRINTF("sc = %p\n", sc); if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) { /* The higher layer is not ready */ return; } ucom_start_transfers(sc); } /*------------------------------------------------------------------------* * ucom_get_data * * Return values: * 0: No data is available. * Else: Data is available. *------------------------------------------------------------------------*/ uint8_t ucom_get_data(struct ucom_softc *sc, struct usb_page_cache *pc, uint32_t offset, uint32_t len, uint32_t *actlen) { struct usb_page_search res; struct tty *tp = sc->sc_tty; uint32_t cnt; uint32_t offset_orig; UCOM_MTX_ASSERT(sc, MA_OWNED); if (sc->sc_flag & UCOM_FLAG_CONSOLE) { unsigned int temp; /* get total TX length */ temp = ucom_cons_tx_high - ucom_cons_tx_low; temp %= UCOM_CONS_BUFSIZE; /* limit TX length */ if (temp > (UCOM_CONS_BUFSIZE - ucom_cons_tx_low)) temp = (UCOM_CONS_BUFSIZE - ucom_cons_tx_low); if (temp > len) temp = len; /* copy in data */ usbd_copy_in(pc, offset, ucom_cons_tx_buf + ucom_cons_tx_low, temp); /* update counters */ ucom_cons_tx_low += temp; ucom_cons_tx_low %= UCOM_CONS_BUFSIZE; /* store actual length */ *actlen = temp; return (temp ? 1 : 0); } if (tty_gone(tp) || !(sc->sc_flag & UCOM_FLAG_GP_DATA)) { actlen[0] = 0; return (0); /* multiport device polling */ } offset_orig = offset; while (len != 0) { usbd_get_page(pc, offset, &res); if (res.length > len) { res.length = len; } /* copy data directly into USB buffer */ cnt = ttydisc_getc(tp, res.buffer, res.length); offset += cnt; len -= cnt; if (cnt < res.length) { /* end of buffer */ break; } } actlen[0] = offset - offset_orig; DPRINTF("cnt=%d\n", actlen[0]); if (actlen[0] == 0) { return (0); } return (1); } void ucom_put_data(struct ucom_softc *sc, struct usb_page_cache *pc, uint32_t offset, uint32_t len) { struct usb_page_search res; struct tty *tp = sc->sc_tty; char *buf; uint32_t cnt; UCOM_MTX_ASSERT(sc, MA_OWNED); if (sc->sc_flag & UCOM_FLAG_CONSOLE) { unsigned int temp; /* get maximum RX length */ temp = (UCOM_CONS_BUFSIZE - 1) - ucom_cons_rx_high + ucom_cons_rx_low; temp %= UCOM_CONS_BUFSIZE; /* limit RX length */ if (temp > (UCOM_CONS_BUFSIZE - ucom_cons_rx_high)) temp = (UCOM_CONS_BUFSIZE - ucom_cons_rx_high); if (temp > len) temp = len; /* copy out data */ usbd_copy_out(pc, offset, ucom_cons_rx_buf + ucom_cons_rx_high, temp); /* update counters */ ucom_cons_rx_high += temp; ucom_cons_rx_high %= UCOM_CONS_BUFSIZE; return; } if (tty_gone(tp)) return; /* multiport device polling */ if (len == 0) return; /* no data */ /* set a flag to prevent recursation ? */ while (len > 0) { usbd_get_page(pc, offset, &res); if (res.length > len) { res.length = len; } len -= res.length; offset += res.length; /* pass characters to tty layer */ buf = res.buffer; cnt = res.length; /* first check if we can pass the buffer directly */ if (ttydisc_can_bypass(tp)) { /* clear any jitter buffer */ sc->sc_jitterbuf_in = 0; sc->sc_jitterbuf_out = 0; if (ttydisc_rint_bypass(tp, buf, cnt) != cnt) { DPRINTF("tp=%p, data lost\n", tp); } continue; } /* need to loop */ for (cnt = 0; cnt != res.length; cnt++) { if (sc->sc_jitterbuf_in != sc->sc_jitterbuf_out || ttydisc_rint(tp, buf[cnt], 0) == -1) { uint16_t end; uint16_t pos; pos = sc->sc_jitterbuf_in; end = sc->sc_jitterbuf_out + UCOM_JITTERBUF_SIZE - 1; if (end >= UCOM_JITTERBUF_SIZE) end -= UCOM_JITTERBUF_SIZE; for (; cnt != res.length; cnt++) { if (pos == end) break; sc->sc_jitterbuf[pos] = buf[cnt]; pos++; if (pos >= UCOM_JITTERBUF_SIZE) pos -= UCOM_JITTERBUF_SIZE; } sc->sc_jitterbuf_in = pos; /* set RTS in async fashion */ if (sc->sc_flag & UCOM_FLAG_RTS_IFLOW) ucom_rts(sc, 1); DPRINTF("tp=%p, lost %d " "chars\n", tp, res.length - cnt); break; } } } ttydisc_rint_done(tp); } static void ucom_free(void *xsc) { struct ucom_softc *sc = xsc; if (sc->sc_callback->ucom_free != NULL) sc->sc_callback->ucom_free(sc); else ucom_unref(sc->sc_super); mtx_lock(&ucom_mtx); ucom_close_refs--; mtx_unlock(&ucom_mtx); } static cn_probe_t ucom_cnprobe; static cn_init_t ucom_cninit; static cn_term_t ucom_cnterm; static cn_getc_t ucom_cngetc; static cn_putc_t ucom_cnputc; static cn_grab_t ucom_cngrab; static cn_ungrab_t ucom_cnungrab; CONSOLE_DRIVER(ucom); static void ucom_cnprobe(struct consdev *cp) { if (ucom_cons_unit != -1) cp->cn_pri = CN_NORMAL; else cp->cn_pri = CN_DEAD; strlcpy(cp->cn_name, "ucom", sizeof(cp->cn_name)); } static void ucom_cninit(struct consdev *cp) { } static void ucom_cnterm(struct consdev *cp) { } static void ucom_cngrab(struct consdev *cp) { } static void ucom_cnungrab(struct consdev *cp) { } static int ucom_cngetc(struct consdev *cd) { struct ucom_softc *sc = ucom_cons_softc; int c; if (sc == NULL) return (-1); UCOM_MTX_LOCK(sc); if (ucom_cons_rx_low != ucom_cons_rx_high) { c = ucom_cons_rx_buf[ucom_cons_rx_low]; ucom_cons_rx_low ++; ucom_cons_rx_low %= UCOM_CONS_BUFSIZE; } else { c = -1; } /* start USB transfers */ ucom_outwakeup(sc->sc_tty); UCOM_MTX_UNLOCK(sc); /* poll if necessary */ if (kdb_active && sc->sc_callback->ucom_poll) (sc->sc_callback->ucom_poll) (sc); return (c); } static void ucom_cnputc(struct consdev *cd, int c) { struct ucom_softc *sc = ucom_cons_softc; unsigned int temp; if (sc == NULL) return; repeat: UCOM_MTX_LOCK(sc); /* compute maximum TX length */ temp = (UCOM_CONS_BUFSIZE - 1) - ucom_cons_tx_high + ucom_cons_tx_low; temp %= UCOM_CONS_BUFSIZE; if (temp) { ucom_cons_tx_buf[ucom_cons_tx_high] = c; ucom_cons_tx_high ++; ucom_cons_tx_high %= UCOM_CONS_BUFSIZE; } /* start USB transfers */ ucom_outwakeup(sc->sc_tty); UCOM_MTX_UNLOCK(sc); /* poll if necessary */ if (kdb_active && sc->sc_callback->ucom_poll) { (sc->sc_callback->ucom_poll) (sc); /* simple flow control */ if (temp == 0) goto repeat; } } /*------------------------------------------------------------------------* * ucom_ref * * This function will increment the super UCOM reference count. *------------------------------------------------------------------------*/ void ucom_ref(struct ucom_super_softc *ssc) { mtx_lock(&ucom_mtx); ssc->sc_refs++; mtx_unlock(&ucom_mtx); } /*------------------------------------------------------------------------* * ucom_free_unit * * This function will free the super UCOM's allocated unit * number. This function can be called on a zero-initialized * structure. This function can be called multiple times. *------------------------------------------------------------------------*/ static void ucom_free_unit(struct ucom_super_softc *ssc) { if (!(ssc->sc_flag & UCOM_FLAG_FREE_UNIT)) return; ucom_unit_free(ssc->sc_unit); ssc->sc_flag &= ~UCOM_FLAG_FREE_UNIT; } /*------------------------------------------------------------------------* * ucom_unref * * This function will decrement the super UCOM reference count. * * Return values: * 0: UCOM structures are still referenced. * Else: UCOM structures are no longer referenced. *------------------------------------------------------------------------*/ int ucom_unref(struct ucom_super_softc *ssc) { int retval; mtx_lock(&ucom_mtx); retval = (ssc->sc_refs < 2); ssc->sc_refs--; mtx_unlock(&ucom_mtx); if (retval) ucom_free_unit(ssc); return (retval); } #if defined(GDB) #include static gdb_probe_f ucom_gdbprobe; static gdb_init_f ucom_gdbinit; static gdb_term_f ucom_gdbterm; static gdb_getc_f ucom_gdbgetc; static gdb_putc_f ucom_gdbputc; GDB_DBGPORT(sio, ucom_gdbprobe, ucom_gdbinit, ucom_gdbterm, ucom_gdbgetc, ucom_gdbputc); static int ucom_gdbprobe(void) { return ((ucom_cons_softc != NULL) ? 0 : -1); } static void ucom_gdbinit(void) { } static void ucom_gdbterm(void) { } static void ucom_gdbputc(int c) { ucom_cnputc(NULL, c); } static int ucom_gdbgetc(void) { return (ucom_cngetc(NULL)); } #endif Index: head/sys/dev/usb/serial/uslcom.c =================================================================== --- head/sys/dev/usb/serial/uslcom.c (revision 276700) +++ head/sys/dev/usb/serial/uslcom.c (revision 276701) @@ -1,942 +1,942 @@ /* $OpenBSD: uslcom.c,v 1.17 2007/11/24 10:52:12 jsg Exp $ */ #include __FBSDID("$FreeBSD$"); /* * Copyright (c) 2006 Jonathan Gray * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* * Driver for Silicon Laboratories CP2101/CP2102/CP2103/CP2104/CP2105 * USB-Serial adapters. Based on datasheet AN571, publicly available from * http://www.silabs.com/Support%20Documents/TechnicalDocs/AN571.pdf */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR uslcom_debug #include #include #include #ifdef USB_DEBUG static int uslcom_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, uslcom, CTLFLAG_RW, 0, "USB uslcom"); -SYSCTL_INT(_hw_usb_uslcom, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_uslcom, OID_AUTO, debug, CTLFLAG_RWTUN, &uslcom_debug, 0, "Debug level"); #endif #define USLCOM_BULK_BUF_SIZE 1024 #define USLCOM_CONFIG_INDEX 0 /* Request types */ #define USLCOM_WRITE 0x41 #define USLCOM_READ 0xc1 /* Request codes */ #define USLCOM_IFC_ENABLE 0x00 #define USLCOM_SET_BAUDDIV 0x01 #define USLCOM_SET_LINE_CTL 0x03 #define USLCOM_SET_BREAK 0x05 #define USLCOM_SET_MHS 0x07 #define USLCOM_GET_MDMSTS 0x08 #define USLCOM_SET_FLOW 0x13 #define USLCOM_SET_BAUDRATE 0x1e #define USLCOM_VENDOR_SPECIFIC 0xff /* USLCOM_IFC_ENABLE values */ #define USLCOM_IFC_ENABLE_DIS 0x00 #define USLCOM_IFC_ENABLE_EN 0x01 /* USLCOM_SET_MHS/USLCOM_GET_MDMSTS values */ #define USLCOM_MHS_DTR_ON 0x0001 #define USLCOM_MHS_DTR_SET 0x0100 #define USLCOM_MHS_RTS_ON 0x0002 #define USLCOM_MHS_RTS_SET 0x0200 #define USLCOM_MHS_CTS 0x0010 #define USLCOM_MHS_DSR 0x0020 #define USLCOM_MHS_RI 0x0040 #define USLCOM_MHS_DCD 0x0080 /* USLCOM_SET_BAUDDIV values */ #define USLCOM_BAUDDIV_REF 3686400 /* 3.6864 MHz */ /* USLCOM_SET_LINE_CTL values */ #define USLCOM_STOP_BITS_1 0x00 #define USLCOM_STOP_BITS_2 0x02 #define USLCOM_PARITY_NONE 0x00 #define USLCOM_PARITY_ODD 0x10 #define USLCOM_PARITY_EVEN 0x20 #define USLCOM_SET_DATA_BITS(x) ((x) << 8) /* USLCOM_SET_BREAK values */ #define USLCOM_SET_BREAK_OFF 0x00 #define USLCOM_SET_BREAK_ON 0x01 /* USLCOM_SET_FLOW values - 1st word */ #define USLCOM_FLOW_DTR_ON 0x00000001 /* DTR static active */ #define USLCOM_FLOW_CTS_HS 0x00000008 /* CTS handshake */ /* USLCOM_SET_FLOW values - 2nd word */ #define USLCOM_FLOW_RTS_ON 0x00000040 /* RTS static active */ #define USLCOM_FLOW_RTS_HS 0x00000080 /* RTS handshake */ /* USLCOM_VENDOR_SPECIFIC values */ #define USLCOM_GET_PARTNUM 0x370B #define USLCOM_WRITE_LATCH 0x37E1 #define USLCOM_READ_LATCH 0x00C2 /* USLCOM_GET_PARTNUM values from hardware */ #define USLCOM_PARTNUM_CP2101 1 #define USLCOM_PARTNUM_CP2102 2 #define USLCOM_PARTNUM_CP2103 3 #define USLCOM_PARTNUM_CP2104 4 #define USLCOM_PARTNUM_CP2105 5 enum { USLCOM_BULK_DT_WR, USLCOM_BULK_DT_RD, USLCOM_CTRL_DT_RD, USLCOM_N_TRANSFER, }; struct uslcom_softc { struct ucom_super_softc sc_super_ucom; struct ucom_softc sc_ucom; struct usb_callout sc_watchdog; struct usb_xfer *sc_xfer[USLCOM_N_TRANSFER]; struct usb_device *sc_udev; struct mtx sc_mtx; uint8_t sc_msr; uint8_t sc_lsr; uint8_t sc_iface_no; uint8_t sc_partnum; }; static device_probe_t uslcom_probe; static device_attach_t uslcom_attach; static device_detach_t uslcom_detach; static void uslcom_free_softc(struct uslcom_softc *); static usb_callback_t uslcom_write_callback; static usb_callback_t uslcom_read_callback; static usb_callback_t uslcom_control_callback; static void uslcom_free(struct ucom_softc *); static void uslcom_open(struct ucom_softc *); static void uslcom_close(struct ucom_softc *); static uint8_t uslcom_get_partnum(struct uslcom_softc *); static void uslcom_set_dtr(struct ucom_softc *, uint8_t); static void uslcom_set_rts(struct ucom_softc *, uint8_t); static void uslcom_set_break(struct ucom_softc *, uint8_t); static int uslcom_ioctl(struct ucom_softc *, uint32_t, caddr_t, int, struct thread *); static int uslcom_pre_param(struct ucom_softc *, struct termios *); static void uslcom_param(struct ucom_softc *, struct termios *); static void uslcom_get_status(struct ucom_softc *, uint8_t *, uint8_t *); static void uslcom_start_read(struct ucom_softc *); static void uslcom_stop_read(struct ucom_softc *); static void uslcom_start_write(struct ucom_softc *); static void uslcom_stop_write(struct ucom_softc *); static void uslcom_poll(struct ucom_softc *ucom); static const struct usb_config uslcom_config[USLCOM_N_TRANSFER] = { [USLCOM_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = USLCOM_BULK_BUF_SIZE, .flags = {.pipe_bof = 1,}, .callback = &uslcom_write_callback, }, [USLCOM_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = USLCOM_BULK_BUF_SIZE, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &uslcom_read_callback, }, [USLCOM_CTRL_DT_RD] = { .type = UE_CONTROL, .endpoint = 0x00, .direction = UE_DIR_ANY, .bufsize = sizeof(struct usb_device_request) + 8, .flags = {.pipe_bof = 1,}, .callback = &uslcom_control_callback, .timeout = 1000, /* 1 second timeout */ }, }; static struct ucom_callback uslcom_callback = { .ucom_cfg_open = &uslcom_open, .ucom_cfg_close = &uslcom_close, .ucom_cfg_get_status = &uslcom_get_status, .ucom_cfg_set_dtr = &uslcom_set_dtr, .ucom_cfg_set_rts = &uslcom_set_rts, .ucom_cfg_set_break = &uslcom_set_break, .ucom_ioctl = &uslcom_ioctl, .ucom_cfg_param = &uslcom_param, .ucom_pre_param = &uslcom_pre_param, .ucom_start_read = &uslcom_start_read, .ucom_stop_read = &uslcom_stop_read, .ucom_start_write = &uslcom_start_write, .ucom_stop_write = &uslcom_stop_write, .ucom_poll = &uslcom_poll, .ucom_free = &uslcom_free, }; static const STRUCT_USB_HOST_ID uslcom_devs[] = { #define USLCOM_DEV(v,p) { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) } USLCOM_DEV(BALTECH, CARDREADER), USLCOM_DEV(CLIPSAL, 5000CT2), USLCOM_DEV(CLIPSAL, 5500PACA), USLCOM_DEV(CLIPSAL, 5500PCU), USLCOM_DEV(CLIPSAL, 560884), USLCOM_DEV(CLIPSAL, 5800PC), USLCOM_DEV(CLIPSAL, C5000CT2), USLCOM_DEV(CLIPSAL, L51xx), USLCOM_DEV(DATAAPEX, MULTICOM), USLCOM_DEV(DELL, DW700), USLCOM_DEV(DIGIANSWER, ZIGBEE802154), USLCOM_DEV(DYNASTREAM, ANTDEVBOARD), USLCOM_DEV(DYNASTREAM, ANTDEVBOARD2), USLCOM_DEV(DYNASTREAM, ANT2USB), USLCOM_DEV(ELV, USBI2C), USLCOM_DEV(FESTO, CMSP), USLCOM_DEV(FESTO, CPX_USB), USLCOM_DEV(FOXCONN, PIRELLI_DP_L10), USLCOM_DEV(FOXCONN, TCOM_TC_300), USLCOM_DEV(GEMALTO, PROXPU), USLCOM_DEV(JABLOTRON, PC60B), USLCOM_DEV(KAMSTRUP, OPTICALEYE), USLCOM_DEV(KAMSTRUP, MBUS_250D), USLCOM_DEV(LAKESHORE, 121), USLCOM_DEV(LAKESHORE, 218A), USLCOM_DEV(LAKESHORE, 219), USLCOM_DEV(LAKESHORE, 233), USLCOM_DEV(LAKESHORE, 235), USLCOM_DEV(LAKESHORE, 335), USLCOM_DEV(LAKESHORE, 336), USLCOM_DEV(LAKESHORE, 350), USLCOM_DEV(LAKESHORE, 371), USLCOM_DEV(LAKESHORE, 411), USLCOM_DEV(LAKESHORE, 425), USLCOM_DEV(LAKESHORE, 455A), USLCOM_DEV(LAKESHORE, 465), USLCOM_DEV(LAKESHORE, 475A), USLCOM_DEV(LAKESHORE, 625A), USLCOM_DEV(LAKESHORE, 642A), USLCOM_DEV(LAKESHORE, 648), USLCOM_DEV(LAKESHORE, 737), USLCOM_DEV(LAKESHORE, 776), USLCOM_DEV(LINKINSTRUMENTS, MSO19), USLCOM_DEV(LINKINSTRUMENTS, MSO28), USLCOM_DEV(LINKINSTRUMENTS, MSO28_2), USLCOM_DEV(MEI, CASHFLOW_SC), USLCOM_DEV(MEI, S2000), USLCOM_DEV(NETGEAR, M4100), USLCOM_DEV(OWEN, AC4), USLCOM_DEV(OWL, CM_160), USLCOM_DEV(PHILIPS, ACE1001), USLCOM_DEV(PLX, CA42), USLCOM_DEV(RENESAS, RX610), USLCOM_DEV(SEL, C662), USLCOM_DEV(SILABS, AC_SERV_CAN), USLCOM_DEV(SILABS, AC_SERV_CIS), USLCOM_DEV(SILABS, AC_SERV_IBUS), USLCOM_DEV(SILABS, AC_SERV_OBD), USLCOM_DEV(SILABS, AEROCOMM), USLCOM_DEV(SILABS, AMBER_AMB2560), USLCOM_DEV(SILABS, ARGUSISP), USLCOM_DEV(SILABS, ARKHAM_DS101_A), USLCOM_DEV(SILABS, ARKHAM_DS101_M), USLCOM_DEV(SILABS, ARYGON_MIFARE), USLCOM_DEV(SILABS, AVIT_USB_TTL), USLCOM_DEV(SILABS, B_G_H3000), USLCOM_DEV(SILABS, BALLUFF_RFID), USLCOM_DEV(SILABS, BEI_VCP), USLCOM_DEV(SILABS, BSM7DUSB), USLCOM_DEV(SILABS, BURNSIDE), USLCOM_DEV(SILABS, C2_EDGE_MODEM), USLCOM_DEV(SILABS, CP2102), USLCOM_DEV(SILABS, CP210X_2), USLCOM_DEV(SILABS, CP210X_3), USLCOM_DEV(SILABS, CP210X_4), USLCOM_DEV(SILABS, CRUMB128), USLCOM_DEV(SILABS, CYGNAL), USLCOM_DEV(SILABS, CYGNAL_DEBUG), USLCOM_DEV(SILABS, CYGNAL_GPS), USLCOM_DEV(SILABS, DEGREE), USLCOM_DEV(SILABS, DEKTEK_DTAPLUS), USLCOM_DEV(SILABS, EMS_C1007), USLCOM_DEV(SILABS, HAMLINKUSB), USLCOM_DEV(SILABS, HELICOM), USLCOM_DEV(SILABS, IMS_USB_RS422), USLCOM_DEV(SILABS, INFINITY_MIC), USLCOM_DEV(SILABS, INGENI_ZIGBEE), USLCOM_DEV(SILABS, INSYS_MODEM), USLCOM_DEV(SILABS, IRZ_SG10), USLCOM_DEV(SILABS, KYOCERA_GPS), USLCOM_DEV(SILABS, LIPOWSKY_HARP), USLCOM_DEV(SILABS, LIPOWSKY_JTAG), USLCOM_DEV(SILABS, LIPOWSKY_LIN), USLCOM_DEV(SILABS, MC35PU), USLCOM_DEV(SILABS, MMB_ZIGBEE), USLCOM_DEV(SILABS, MJS_TOSLINK), USLCOM_DEV(SILABS, MSD_DASHHAWK), USLCOM_DEV(SILABS, MULTIPLEX_RC), USLCOM_DEV(SILABS, OPTRIS_MSPRO), USLCOM_DEV(SILABS, POLOLU), USLCOM_DEV(SILABS, PROCYON_AVS), USLCOM_DEV(SILABS, SB_PARAMOUNT_ME), USLCOM_DEV(SILABS, SUUNTO), USLCOM_DEV(SILABS, TAMSMASTER), USLCOM_DEV(SILABS, TELEGESIS_ETRX2), USLCOM_DEV(SILABS, TRACIENT), USLCOM_DEV(SILABS, TRAQMATE), USLCOM_DEV(SILABS, USBCOUNT50), USLCOM_DEV(SILABS, USBPULSE100), USLCOM_DEV(SILABS, USBSCOPE50), USLCOM_DEV(SILABS, USBWAVE12), USLCOM_DEV(SILABS, V_PREON32), USLCOM_DEV(SILABS, VSTABI), USLCOM_DEV(SILABS, WAVIT), USLCOM_DEV(SILABS, WMRBATT), USLCOM_DEV(SILABS, WMRRIGBLASTER), USLCOM_DEV(SILABS, WMRRIGTALK), USLCOM_DEV(SILABS, ZEPHYR_BIO), USLCOM_DEV(SILABS2, DCU11CLONE), USLCOM_DEV(SILABS3, GPRS_MODEM), USLCOM_DEV(SILABS4, 100EU_MODEM), USLCOM_DEV(SYNTECH, CYPHERLAB100), USLCOM_DEV(USI, MC60), USLCOM_DEV(VAISALA, CABLE), USLCOM_DEV(WAGO, SERVICECABLE), USLCOM_DEV(WAVESENSE, JAZZ), USLCOM_DEV(WESTMOUNTAIN, RIGBLASTER_ADVANTAGE), USLCOM_DEV(WIENERPLEINBAUS, PL512), USLCOM_DEV(WIENERPLEINBAUS, RCM), USLCOM_DEV(WIENERPLEINBAUS, MPOD), USLCOM_DEV(WIENERPLEINBAUS, CML), #undef USLCOM_DEV }; static device_method_t uslcom_methods[] = { DEVMETHOD(device_probe, uslcom_probe), DEVMETHOD(device_attach, uslcom_attach), DEVMETHOD(device_detach, uslcom_detach), DEVMETHOD_END }; static devclass_t uslcom_devclass; static driver_t uslcom_driver = { .name = "uslcom", .methods = uslcom_methods, .size = sizeof(struct uslcom_softc), }; DRIVER_MODULE(uslcom, uhub, uslcom_driver, uslcom_devclass, NULL, 0); MODULE_DEPEND(uslcom, ucom, 1, 1, 1); MODULE_DEPEND(uslcom, usb, 1, 1, 1); MODULE_VERSION(uslcom, 1); static void uslcom_watchdog(void *arg) { struct uslcom_softc *sc = arg; mtx_assert(&sc->sc_mtx, MA_OWNED); usbd_transfer_start(sc->sc_xfer[USLCOM_CTRL_DT_RD]); usb_callout_reset(&sc->sc_watchdog, hz / 4, &uslcom_watchdog, sc); } static int uslcom_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); DPRINTFN(11, "\n"); if (uaa->usb_mode != USB_MODE_HOST) { return (ENXIO); } if (uaa->info.bConfigIndex != USLCOM_CONFIG_INDEX) { return (ENXIO); } return (usbd_lookup_id_by_uaa(uslcom_devs, sizeof(uslcom_devs), uaa)); } static int uslcom_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct uslcom_softc *sc = device_get_softc(dev); int error; DPRINTFN(11, "\n"); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "uslcom", NULL, MTX_DEF); ucom_ref(&sc->sc_super_ucom); usb_callout_init_mtx(&sc->sc_watchdog, &sc->sc_mtx, 0); sc->sc_udev = uaa->device; /* use the interface number from the USB interface descriptor */ sc->sc_iface_no = uaa->info.bIfaceNum; error = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex, sc->sc_xfer, uslcom_config, USLCOM_N_TRANSFER, sc, &sc->sc_mtx); if (error) { DPRINTF("one or more missing USB endpoints, " "error=%s\n", usbd_errstr(error)); goto detach; } /* clear stall at first run */ mtx_lock(&sc->sc_mtx); usbd_xfer_set_stall(sc->sc_xfer[USLCOM_BULK_DT_WR]); usbd_xfer_set_stall(sc->sc_xfer[USLCOM_BULK_DT_RD]); mtx_unlock(&sc->sc_mtx); sc->sc_partnum = uslcom_get_partnum(sc); error = ucom_attach(&sc->sc_super_ucom, &sc->sc_ucom, 1, sc, &uslcom_callback, &sc->sc_mtx); if (error) { goto detach; } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, dev); return (0); detach: uslcom_detach(dev); return (ENXIO); } static int uslcom_detach(device_t dev) { struct uslcom_softc *sc = device_get_softc(dev); DPRINTF("sc=%p\n", sc); ucom_detach(&sc->sc_super_ucom, &sc->sc_ucom); usbd_transfer_unsetup(sc->sc_xfer, USLCOM_N_TRANSFER); usb_callout_drain(&sc->sc_watchdog); device_claim_softc(dev); uslcom_free_softc(sc); return (0); } UCOM_UNLOAD_DRAIN(uslcom); static void uslcom_free_softc(struct uslcom_softc *sc) { if (ucom_unref(&sc->sc_super_ucom)) { mtx_destroy(&sc->sc_mtx); device_free_softc(sc); } } static void uslcom_free(struct ucom_softc *ucom) { uslcom_free_softc(ucom->sc_parent); } static void uslcom_open(struct ucom_softc *ucom) { struct uslcom_softc *sc = ucom->sc_parent; struct usb_device_request req; req.bmRequestType = USLCOM_WRITE; req.bRequest = USLCOM_IFC_ENABLE; USETW(req.wValue, USLCOM_IFC_ENABLE_EN); USETW(req.wIndex, sc->sc_iface_no); USETW(req.wLength, 0); if (ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000)) { DPRINTF("UART enable failed (ignored)\n"); } /* start polling status */ uslcom_watchdog(sc); } static void uslcom_close(struct ucom_softc *ucom) { struct uslcom_softc *sc = ucom->sc_parent; struct usb_device_request req; /* stop polling status */ usb_callout_stop(&sc->sc_watchdog); req.bmRequestType = USLCOM_WRITE; req.bRequest = USLCOM_IFC_ENABLE; USETW(req.wValue, USLCOM_IFC_ENABLE_DIS); USETW(req.wIndex, sc->sc_iface_no); USETW(req.wLength, 0); if (ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000)) { DPRINTF("UART disable failed (ignored)\n"); } } static uint8_t uslcom_get_partnum(struct uslcom_softc *sc) { struct usb_device_request req; uint8_t partnum; /* Find specific chip type */ partnum = 0; req.bmRequestType = USLCOM_READ; req.bRequest = USLCOM_VENDOR_SPECIFIC; USETW(req.wValue, USLCOM_GET_PARTNUM); USETW(req.wIndex, sc->sc_iface_no); USETW(req.wLength, sizeof(partnum)); if (usbd_do_request_flags(sc->sc_udev, NULL, &req, &partnum, 0, NULL, 1000)) { DPRINTF("GET_PARTNUM failed\n"); } return(partnum); } static void uslcom_set_dtr(struct ucom_softc *ucom, uint8_t onoff) { struct uslcom_softc *sc = ucom->sc_parent; struct usb_device_request req; uint16_t ctl; DPRINTF("onoff = %d\n", onoff); ctl = onoff ? USLCOM_MHS_DTR_ON : 0; ctl |= USLCOM_MHS_DTR_SET; req.bmRequestType = USLCOM_WRITE; req.bRequest = USLCOM_SET_MHS; USETW(req.wValue, ctl); USETW(req.wIndex, sc->sc_iface_no); USETW(req.wLength, 0); if (ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000)) { DPRINTF("Setting DTR failed (ignored)\n"); } } static void uslcom_set_rts(struct ucom_softc *ucom, uint8_t onoff) { struct uslcom_softc *sc = ucom->sc_parent; struct usb_device_request req; uint16_t ctl; DPRINTF("onoff = %d\n", onoff); ctl = onoff ? USLCOM_MHS_RTS_ON : 0; ctl |= USLCOM_MHS_RTS_SET; req.bmRequestType = USLCOM_WRITE; req.bRequest = USLCOM_SET_MHS; USETW(req.wValue, ctl); USETW(req.wIndex, sc->sc_iface_no); USETW(req.wLength, 0); if (ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000)) { DPRINTF("Setting DTR failed (ignored)\n"); } } static int uslcom_pre_param(struct ucom_softc *ucom, struct termios *t) { if (t->c_ospeed <= 0 || t->c_ospeed > 921600) return (EINVAL); return (0); } static void uslcom_param(struct ucom_softc *ucom, struct termios *t) { struct uslcom_softc *sc = ucom->sc_parent; struct usb_device_request req; uint32_t baudrate, flowctrl[4]; uint16_t data; DPRINTF("\n"); baudrate = t->c_ospeed; req.bmRequestType = USLCOM_WRITE; req.bRequest = USLCOM_SET_BAUDRATE; USETW(req.wValue, 0); USETW(req.wIndex, sc->sc_iface_no); USETW(req.wLength, sizeof(baudrate)); if (ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, &baudrate, 0, 1000)) { DPRINTF("Set baudrate failed (ignored)\n"); } if (t->c_cflag & CSTOPB) data = USLCOM_STOP_BITS_2; else data = USLCOM_STOP_BITS_1; if (t->c_cflag & PARENB) { if (t->c_cflag & PARODD) data |= USLCOM_PARITY_ODD; else data |= USLCOM_PARITY_EVEN; } else data |= USLCOM_PARITY_NONE; switch (t->c_cflag & CSIZE) { case CS5: data |= USLCOM_SET_DATA_BITS(5); break; case CS6: data |= USLCOM_SET_DATA_BITS(6); break; case CS7: data |= USLCOM_SET_DATA_BITS(7); break; case CS8: data |= USLCOM_SET_DATA_BITS(8); break; } req.bmRequestType = USLCOM_WRITE; req.bRequest = USLCOM_SET_LINE_CTL; USETW(req.wValue, data); USETW(req.wIndex, sc->sc_iface_no); USETW(req.wLength, 0); if (ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000)) { DPRINTF("Set format failed (ignored)\n"); } if (t->c_cflag & CRTSCTS) { flowctrl[0] = htole32(USLCOM_FLOW_DTR_ON | USLCOM_FLOW_CTS_HS); flowctrl[1] = htole32(USLCOM_FLOW_RTS_HS); } else { flowctrl[0] = htole32(USLCOM_FLOW_DTR_ON); flowctrl[1] = htole32(USLCOM_FLOW_RTS_ON); } flowctrl[2] = 0; flowctrl[3] = 0; req.bmRequestType = USLCOM_WRITE; req.bRequest = USLCOM_SET_FLOW; USETW(req.wValue, 0); USETW(req.wIndex, sc->sc_iface_no); USETW(req.wLength, sizeof(flowctrl)); if (ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, flowctrl, 0, 1000)) { DPRINTF("Set flowcontrol failed (ignored)\n"); } } static void uslcom_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr) { struct uslcom_softc *sc = ucom->sc_parent; DPRINTF("\n"); *lsr = sc->sc_lsr; *msr = sc->sc_msr; } static void uslcom_set_break(struct ucom_softc *ucom, uint8_t onoff) { struct uslcom_softc *sc = ucom->sc_parent; struct usb_device_request req; uint16_t brk = onoff ? USLCOM_SET_BREAK_ON : USLCOM_SET_BREAK_OFF; req.bmRequestType = USLCOM_WRITE; req.bRequest = USLCOM_SET_BREAK; USETW(req.wValue, brk); USETW(req.wIndex, sc->sc_iface_no); USETW(req.wLength, 0); if (ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000)) { DPRINTF("Set BREAK failed (ignored)\n"); } } static int uslcom_ioctl(struct ucom_softc *ucom, uint32_t cmd, caddr_t data, int flag, struct thread *td) { struct uslcom_softc *sc = ucom->sc_parent; struct usb_device_request req; int error = 0; uint8_t latch; DPRINTF("cmd=0x%08x\n", cmd); switch (cmd) { case USB_GET_GPIO: if (sc->sc_partnum < USLCOM_PARTNUM_CP2103) { error = ENODEV; break; } req.bmRequestType = USLCOM_READ; req.bRequest = USLCOM_VENDOR_SPECIFIC; USETW(req.wValue, USLCOM_READ_LATCH); USETW(req.wIndex, sc->sc_iface_no); USETW(req.wLength, sizeof(latch)); if (ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, &latch, 0, 1000)) { DPRINTF("Get LATCH failed\n"); error = EIO; } *(int *)data = latch; break; case USB_SET_GPIO: if (sc->sc_partnum < USLCOM_PARTNUM_CP2103) error = ENODEV; else if ((sc->sc_partnum == USLCOM_PARTNUM_CP2103) || (sc->sc_partnum == USLCOM_PARTNUM_CP2104)) { req.bmRequestType = USLCOM_WRITE; req.bRequest = USLCOM_VENDOR_SPECIFIC; USETW(req.wValue, USLCOM_WRITE_LATCH); USETW(req.wIndex, (*(int *)data)); USETW(req.wLength, 0); if (ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000)) { DPRINTF("Set LATCH failed\n"); error = EIO; } } else error = ENODEV; /* Not yet */ break; default: DPRINTF("Unknown IOCTL\n"); error = ENOIOCTL; break; } return (error); } static void uslcom_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct uslcom_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint32_t actlen; switch (USB_GET_STATE(xfer)) { case USB_ST_SETUP: case USB_ST_TRANSFERRED: tr_setup: pc = usbd_xfer_get_frame(xfer, 0); if (ucom_get_data(&sc->sc_ucom, pc, 0, USLCOM_BULK_BUF_SIZE, &actlen)) { DPRINTF("actlen = %d\n", actlen); usbd_xfer_set_frame_len(xfer, 0, actlen); usbd_transfer_submit(xfer); } return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void uslcom_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct uslcom_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); ucom_put_data(&sc->sc_ucom, pc, 0, actlen); case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void uslcom_control_callback(struct usb_xfer *xfer, usb_error_t error) { struct uslcom_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; struct usb_device_request req; uint8_t msr = 0; uint8_t buf; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 1); usbd_copy_out(pc, 0, &buf, sizeof(buf)); if (buf & USLCOM_MHS_CTS) msr |= SER_CTS; if (buf & USLCOM_MHS_DSR) msr |= SER_DSR; if (buf & USLCOM_MHS_RI) msr |= SER_RI; if (buf & USLCOM_MHS_DCD) msr |= SER_DCD; if (msr != sc->sc_msr) { DPRINTF("status change msr=0x%02x " "(was 0x%02x)\n", msr, sc->sc_msr); sc->sc_msr = msr; ucom_status_change(&sc->sc_ucom); } break; case USB_ST_SETUP: req.bmRequestType = USLCOM_READ; req.bRequest = USLCOM_GET_MDMSTS; USETW(req.wValue, 0); USETW(req.wIndex, sc->sc_iface_no); USETW(req.wLength, sizeof(buf)); usbd_xfer_set_frames(xfer, 2); usbd_xfer_set_frame_len(xfer, 0, sizeof(req)); usbd_xfer_set_frame_len(xfer, 1, sizeof(buf)); pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, &req, sizeof(req)); usbd_transfer_submit(xfer); break; default: /* error */ if (error != USB_ERR_CANCELLED) DPRINTF("error=%s\n", usbd_errstr(error)); break; } } static void uslcom_start_read(struct ucom_softc *ucom) { struct uslcom_softc *sc = ucom->sc_parent; /* start read endpoint */ usbd_transfer_start(sc->sc_xfer[USLCOM_BULK_DT_RD]); } static void uslcom_stop_read(struct ucom_softc *ucom) { struct uslcom_softc *sc = ucom->sc_parent; /* stop read endpoint */ usbd_transfer_stop(sc->sc_xfer[USLCOM_BULK_DT_RD]); } static void uslcom_start_write(struct ucom_softc *ucom) { struct uslcom_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[USLCOM_BULK_DT_WR]); } static void uslcom_stop_write(struct ucom_softc *ucom) { struct uslcom_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[USLCOM_BULK_DT_WR]); } static void uslcom_poll(struct ucom_softc *ucom) { struct uslcom_softc *sc = ucom->sc_parent; usbd_transfer_poll(sc->sc_xfer, USLCOM_N_TRANSFER); } Index: head/sys/dev/usb/serial/uvisor.c =================================================================== --- head/sys/dev/usb/serial/uvisor.c (revision 276700) +++ head/sys/dev/usb/serial/uvisor.c (revision 276701) @@ -1,676 +1,676 @@ /* $NetBSD: uvisor.c,v 1.9 2001/01/23 14:04:14 augustss Exp $ */ /* $FreeBSD$ */ /* Also already merged from NetBSD: * $NetBSD: uvisor.c,v 1.12 2001/11/13 06:24:57 lukem Exp $ * $NetBSD: uvisor.c,v 1.13 2002/02/11 15:11:49 augustss Exp $ * $NetBSD: uvisor.c,v 1.14 2002/02/27 23:00:03 augustss Exp $ * $NetBSD: uvisor.c,v 1.15 2002/06/16 15:01:31 augustss Exp $ * $NetBSD: uvisor.c,v 1.16 2002/07/11 21:14:36 augustss Exp $ * $NetBSD: uvisor.c,v 1.17 2002/08/13 11:38:15 augustss Exp $ * $NetBSD: uvisor.c,v 1.18 2003/02/05 00:50:14 augustss Exp $ * $NetBSD: uvisor.c,v 1.19 2003/02/07 18:12:37 augustss Exp $ * $NetBSD: uvisor.c,v 1.20 2003/04/11 01:30:10 simonb Exp $ */ /*- * Copyright (c) 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Lennart Augustsson (lennart@augustsson.net) at * Carlstedt Research & Technology. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Handspring Visor (Palmpilot compatible PDA) driver */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR uvisor_debug #include #include #include #ifdef USB_DEBUG static int uvisor_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, uvisor, CTLFLAG_RW, 0, "USB uvisor"); -SYSCTL_INT(_hw_usb_uvisor, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_uvisor, OID_AUTO, debug, CTLFLAG_RWTUN, &uvisor_debug, 0, "Debug level"); #endif #define UVISOR_CONFIG_INDEX 0 #define UVISOR_IFACE_INDEX 0 /* * The following buffer sizes are hardcoded due to the way the Palm * firmware works. It looks like the device is not short terminating * the data transferred. */ #define UVISORIBUFSIZE 0 /* Use wMaxPacketSize */ #define UVISOROBUFSIZE 32 /* bytes */ #define UVISOROFRAMES 32 /* units */ /* From the Linux driver */ /* * UVISOR_REQUEST_BYTES_AVAILABLE asks the visor for the number of bytes that * are available to be transfered to the host for the specified endpoint. * Currently this is not used, and always returns 0x0001 */ #define UVISOR_REQUEST_BYTES_AVAILABLE 0x01 /* * UVISOR_CLOSE_NOTIFICATION is set to the device to notify it that the host * is now closing the pipe. An empty packet is sent in response. */ #define UVISOR_CLOSE_NOTIFICATION 0x02 /* * UVISOR_GET_CONNECTION_INFORMATION is sent by the host during enumeration to * get the endpoints used by the connection. */ #define UVISOR_GET_CONNECTION_INFORMATION 0x03 /* * UVISOR_GET_CONNECTION_INFORMATION returns data in the following format */ #define UVISOR_MAX_CONN 8 struct uvisor_connection_info { uWord num_ports; struct { uByte port_function_id; uByte port; } __packed connections[UVISOR_MAX_CONN]; } __packed; #define UVISOR_CONNECTION_INFO_SIZE 18 /* struct uvisor_connection_info.connection[x].port defines: */ #define UVISOR_ENDPOINT_1 0x01 #define UVISOR_ENDPOINT_2 0x02 /* struct uvisor_connection_info.connection[x].port_function_id defines: */ #define UVISOR_FUNCTION_GENERIC 0x00 #define UVISOR_FUNCTION_DEBUGGER 0x01 #define UVISOR_FUNCTION_HOTSYNC 0x02 #define UVISOR_FUNCTION_CONSOLE 0x03 #define UVISOR_FUNCTION_REMOTE_FILE_SYS 0x04 /* * Unknown PalmOS stuff. */ #define UVISOR_GET_PALM_INFORMATION 0x04 #define UVISOR_GET_PALM_INFORMATION_LEN 0x44 struct uvisor_palm_connection_info { uByte num_ports; uByte endpoint_numbers_different; uWord reserved1; struct { uDWord port_function_id; uByte port; uByte end_point_info; uWord reserved; } __packed connections[UVISOR_MAX_CONN]; } __packed; enum { UVISOR_BULK_DT_WR, UVISOR_BULK_DT_RD, UVISOR_N_TRANSFER, }; struct uvisor_softc { struct ucom_super_softc sc_super_ucom; struct ucom_softc sc_ucom; struct usb_xfer *sc_xfer[UVISOR_N_TRANSFER]; struct usb_device *sc_udev; struct mtx sc_mtx; uint16_t sc_flag; #define UVISOR_FLAG_PALM4 0x0001 #define UVISOR_FLAG_VISOR 0x0002 #define UVISOR_FLAG_PALM35 0x0004 #define UVISOR_FLAG_SEND_NOTIFY 0x0008 uint8_t sc_iface_no; uint8_t sc_iface_index; }; /* prototypes */ static device_probe_t uvisor_probe; static device_attach_t uvisor_attach; static device_detach_t uvisor_detach; static void uvisor_free_softc(struct uvisor_softc *); static usb_callback_t uvisor_write_callback; static usb_callback_t uvisor_read_callback; static usb_error_t uvisor_init(struct uvisor_softc *, struct usb_device *, struct usb_config *); static void uvisor_free(struct ucom_softc *); static void uvisor_cfg_open(struct ucom_softc *); static void uvisor_cfg_close(struct ucom_softc *); static void uvisor_start_read(struct ucom_softc *); static void uvisor_stop_read(struct ucom_softc *); static void uvisor_start_write(struct ucom_softc *); static void uvisor_stop_write(struct ucom_softc *); static const struct usb_config uvisor_config[UVISOR_N_TRANSFER] = { [UVISOR_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = UVISOROBUFSIZE * UVISOROFRAMES, .frames = UVISOROFRAMES, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = &uvisor_write_callback, }, [UVISOR_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = UVISORIBUFSIZE, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &uvisor_read_callback, }, }; static const struct ucom_callback uvisor_callback = { .ucom_cfg_open = &uvisor_cfg_open, .ucom_cfg_close = &uvisor_cfg_close, .ucom_start_read = &uvisor_start_read, .ucom_stop_read = &uvisor_stop_read, .ucom_start_write = &uvisor_start_write, .ucom_stop_write = &uvisor_stop_write, .ucom_free = &uvisor_free, }; static device_method_t uvisor_methods[] = { DEVMETHOD(device_probe, uvisor_probe), DEVMETHOD(device_attach, uvisor_attach), DEVMETHOD(device_detach, uvisor_detach), DEVMETHOD_END }; static devclass_t uvisor_devclass; static driver_t uvisor_driver = { .name = "uvisor", .methods = uvisor_methods, .size = sizeof(struct uvisor_softc), }; DRIVER_MODULE(uvisor, uhub, uvisor_driver, uvisor_devclass, NULL, 0); MODULE_DEPEND(uvisor, ucom, 1, 1, 1); MODULE_DEPEND(uvisor, usb, 1, 1, 1); MODULE_VERSION(uvisor, 1); static const STRUCT_USB_HOST_ID uvisor_devs[] = { #define UVISOR_DEV(v,p,i) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, i) } UVISOR_DEV(ACEECA, MEZ1000, UVISOR_FLAG_PALM4), UVISOR_DEV(ALPHASMART, DANA_SYNC, UVISOR_FLAG_PALM4), UVISOR_DEV(GARMIN, IQUE_3600, UVISOR_FLAG_PALM4), UVISOR_DEV(FOSSIL, WRISTPDA, UVISOR_FLAG_PALM4), UVISOR_DEV(HANDSPRING, VISOR, UVISOR_FLAG_VISOR), UVISOR_DEV(HANDSPRING, TREO, UVISOR_FLAG_PALM4), UVISOR_DEV(HANDSPRING, TREO600, UVISOR_FLAG_PALM4), UVISOR_DEV(PALM, M500, UVISOR_FLAG_PALM4), UVISOR_DEV(PALM, M505, UVISOR_FLAG_PALM4), UVISOR_DEV(PALM, M515, UVISOR_FLAG_PALM4), UVISOR_DEV(PALM, I705, UVISOR_FLAG_PALM4), UVISOR_DEV(PALM, M125, UVISOR_FLAG_PALM4), UVISOR_DEV(PALM, M130, UVISOR_FLAG_PALM4), UVISOR_DEV(PALM, TUNGSTEN_Z, UVISOR_FLAG_PALM4), UVISOR_DEV(PALM, TUNGSTEN_T, UVISOR_FLAG_PALM4), UVISOR_DEV(PALM, ZIRE, UVISOR_FLAG_PALM4), UVISOR_DEV(PALM, ZIRE31, UVISOR_FLAG_PALM4), UVISOR_DEV(SAMSUNG, I500, UVISOR_FLAG_PALM4), UVISOR_DEV(SONY, CLIE_40, 0), UVISOR_DEV(SONY, CLIE_41, 0), UVISOR_DEV(SONY, CLIE_S360, UVISOR_FLAG_PALM4), UVISOR_DEV(SONY, CLIE_NX60, UVISOR_FLAG_PALM4), UVISOR_DEV(SONY, CLIE_35, UVISOR_FLAG_PALM35), /* UVISOR_DEV(SONY, CLIE_25, UVISOR_FLAG_PALM4 ), */ UVISOR_DEV(SONY, CLIE_TJ37, UVISOR_FLAG_PALM4), /* UVISOR_DEV(SONY, CLIE_TH55, UVISOR_FLAG_PALM4 ), See PR 80935 */ UVISOR_DEV(TAPWAVE, ZODIAC, UVISOR_FLAG_PALM4), #undef UVISOR_DEV }; static int uvisor_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) { return (ENXIO); } if (uaa->info.bConfigIndex != UVISOR_CONFIG_INDEX) { return (ENXIO); } if (uaa->info.bIfaceIndex != UVISOR_IFACE_INDEX) { return (ENXIO); } return (usbd_lookup_id_by_uaa(uvisor_devs, sizeof(uvisor_devs), uaa)); } static int uvisor_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct uvisor_softc *sc = device_get_softc(dev); struct usb_config uvisor_config_copy[UVISOR_N_TRANSFER]; int error; DPRINTF("sc=%p\n", sc); memcpy(uvisor_config_copy, uvisor_config, sizeof(uvisor_config_copy)); device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "uvisor", NULL, MTX_DEF); ucom_ref(&sc->sc_super_ucom); sc->sc_udev = uaa->device; /* configure the device */ sc->sc_flag = USB_GET_DRIVER_INFO(uaa); sc->sc_iface_no = uaa->info.bIfaceNum; sc->sc_iface_index = UVISOR_IFACE_INDEX; error = uvisor_init(sc, uaa->device, uvisor_config_copy); if (error) { DPRINTF("init failed, error=%s\n", usbd_errstr(error)); goto detach; } error = usbd_transfer_setup(uaa->device, &sc->sc_iface_index, sc->sc_xfer, uvisor_config_copy, UVISOR_N_TRANSFER, sc, &sc->sc_mtx); if (error) { DPRINTF("could not allocate all pipes\n"); goto detach; } error = ucom_attach(&sc->sc_super_ucom, &sc->sc_ucom, 1, sc, &uvisor_callback, &sc->sc_mtx); if (error) { DPRINTF("ucom_attach failed\n"); goto detach; } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, dev); return (0); detach: uvisor_detach(dev); return (ENXIO); } static int uvisor_detach(device_t dev) { struct uvisor_softc *sc = device_get_softc(dev); DPRINTF("sc=%p\n", sc); ucom_detach(&sc->sc_super_ucom, &sc->sc_ucom); usbd_transfer_unsetup(sc->sc_xfer, UVISOR_N_TRANSFER); device_claim_softc(dev); uvisor_free_softc(sc); return (0); } UCOM_UNLOAD_DRAIN(uvisor); static void uvisor_free_softc(struct uvisor_softc *sc) { if (ucom_unref(&sc->sc_super_ucom)) { mtx_destroy(&sc->sc_mtx); device_free_softc(sc); } } static void uvisor_free(struct ucom_softc *ucom) { uvisor_free_softc(ucom->sc_parent); } static usb_error_t uvisor_init(struct uvisor_softc *sc, struct usb_device *udev, struct usb_config *config) { usb_error_t err = 0; struct usb_device_request req; struct uvisor_connection_info coninfo; struct uvisor_palm_connection_info pconinfo; uint16_t actlen; uint8_t buffer[256]; if (sc->sc_flag & UVISOR_FLAG_VISOR) { DPRINTF("getting connection info\n"); req.bmRequestType = UT_READ_VENDOR_ENDPOINT; req.bRequest = UVISOR_GET_CONNECTION_INFORMATION; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, UVISOR_CONNECTION_INFO_SIZE); err = usbd_do_request_flags(udev, NULL, &req, &coninfo, USB_SHORT_XFER_OK, &actlen, USB_DEFAULT_TIMEOUT); if (err) { goto done; } } #ifdef USB_DEBUG if (sc->sc_flag & UVISOR_FLAG_VISOR) { uint16_t i, np; const char *desc; np = UGETW(coninfo.num_ports); if (np > UVISOR_MAX_CONN) { np = UVISOR_MAX_CONN; } DPRINTF("Number of ports: %d\n", np); for (i = 0; i < np; ++i) { switch (coninfo.connections[i].port_function_id) { case UVISOR_FUNCTION_GENERIC: desc = "Generic"; break; case UVISOR_FUNCTION_DEBUGGER: desc = "Debugger"; break; case UVISOR_FUNCTION_HOTSYNC: desc = "HotSync"; break; case UVISOR_FUNCTION_REMOTE_FILE_SYS: desc = "Remote File System"; break; default: desc = "unknown"; break; } DPRINTF("Port %d is for %s\n", coninfo.connections[i].port, desc); } } #endif if (sc->sc_flag & UVISOR_FLAG_PALM4) { uint8_t port; /* Palm OS 4.0 Hack */ req.bmRequestType = UT_READ_VENDOR_ENDPOINT; req.bRequest = UVISOR_GET_PALM_INFORMATION; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, UVISOR_GET_PALM_INFORMATION_LEN); err = usbd_do_request_flags (udev, NULL, &req, &pconinfo, USB_SHORT_XFER_OK, &actlen, USB_DEFAULT_TIMEOUT); if (err) { goto done; } if (actlen < 12) { DPRINTF("too little data\n"); err = USB_ERR_INVAL; goto done; } if (pconinfo.endpoint_numbers_different) { port = pconinfo.connections[0].end_point_info; config[0].endpoint = (port & 0xF); /* output */ config[1].endpoint = (port >> 4); /* input */ } else { port = pconinfo.connections[0].port; config[0].endpoint = (port & 0xF); /* output */ config[1].endpoint = (port & 0xF); /* input */ } #if 0 req.bmRequestType = UT_READ_VENDOR_ENDPOINT; req.bRequest = UVISOR_GET_PALM_INFORMATION; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, UVISOR_GET_PALM_INFORMATION_LEN); err = usbd_do_request(udev, &req, buffer); if (err) { goto done; } #endif } if (sc->sc_flag & UVISOR_FLAG_PALM35) { /* get the config number */ DPRINTF("getting config info\n"); req.bmRequestType = UT_READ; req.bRequest = UR_GET_CONFIG; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, 1); err = usbd_do_request(udev, NULL, &req, buffer); if (err) { goto done; } /* get the interface number */ DPRINTF("get the interface number\n"); req.bmRequestType = UT_READ_DEVICE; req.bRequest = UR_GET_INTERFACE; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, 1); err = usbd_do_request(udev, NULL, &req, buffer); if (err) { goto done; } } #if 0 uWord wAvail; DPRINTF("getting available bytes\n"); req.bmRequestType = UT_READ_VENDOR_ENDPOINT; req.bRequest = UVISOR_REQUEST_BYTES_AVAILABLE; USETW(req.wValue, 0); USETW(req.wIndex, 5); USETW(req.wLength, sizeof(wAvail)); err = usbd_do_request(udev, NULL, &req, &wAvail); if (err) { goto done; } DPRINTF("avail=%d\n", UGETW(wAvail)); #endif DPRINTF("done\n"); done: return (err); } static void uvisor_cfg_open(struct ucom_softc *ucom) { return; } static void uvisor_cfg_close(struct ucom_softc *ucom) { struct uvisor_softc *sc = ucom->sc_parent; uint8_t buffer[UVISOR_CONNECTION_INFO_SIZE]; struct usb_device_request req; usb_error_t err; req.bmRequestType = UT_READ_VENDOR_ENDPOINT; /* XXX read? */ req.bRequest = UVISOR_CLOSE_NOTIFICATION; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, UVISOR_CONNECTION_INFO_SIZE); err = ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, buffer, 0, 1000); if (err) { DPRINTFN(0, "close notification failed, error=%s\n", usbd_errstr(err)); } } static void uvisor_start_read(struct ucom_softc *ucom) { struct uvisor_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[UVISOR_BULK_DT_RD]); } static void uvisor_stop_read(struct ucom_softc *ucom) { struct uvisor_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[UVISOR_BULK_DT_RD]); } static void uvisor_start_write(struct ucom_softc *ucom) { struct uvisor_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[UVISOR_BULK_DT_WR]); } static void uvisor_stop_write(struct ucom_softc *ucom) { struct uvisor_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[UVISOR_BULK_DT_WR]); } static void uvisor_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct uvisor_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint32_t actlen; uint8_t x; switch (USB_GET_STATE(xfer)) { case USB_ST_SETUP: case USB_ST_TRANSFERRED: tr_setup: for (x = 0; x != UVISOROFRAMES; x++) { usbd_xfer_set_frame_offset(xfer, x * UVISOROBUFSIZE, x); pc = usbd_xfer_get_frame(xfer, x); if (ucom_get_data(&sc->sc_ucom, pc, 0, UVISOROBUFSIZE, &actlen)) { usbd_xfer_set_frame_len(xfer, x, actlen); } else { break; } } /* check for data */ if (x != 0) { usbd_xfer_set_frames(xfer, x); usbd_transfer_submit(xfer); } break; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void uvisor_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct uvisor_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); ucom_put_data(&sc->sc_ucom, pc, 0, actlen); case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } Index: head/sys/dev/usb/serial/uvscom.c =================================================================== --- head/sys/dev/usb/serial/uvscom.c (revision 276700) +++ head/sys/dev/usb/serial/uvscom.c (revision 276701) @@ -1,770 +1,770 @@ /* $NetBSD: usb/uvscom.c,v 1.1 2002/03/19 15:08:42 augustss Exp $ */ #include __FBSDID("$FreeBSD$"); /*- * Copyright (c) 2001-2003, 2005 Shunsuke Akiyama . * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ /* * uvscom: SUNTAC Slipper U VS-10U driver. * Slipper U is a PC Card to USB converter for data communication card * adapter. It supports DDI Pocket's Air H" C@rd, C@rd H" 64, NTT's P-in, * P-in m@ater and various data communication card adapters. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR uvscom_debug #include #include #include #ifdef USB_DEBUG static int uvscom_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, uvscom, CTLFLAG_RW, 0, "USB uvscom"); -SYSCTL_INT(_hw_usb_uvscom, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_uvscom, OID_AUTO, debug, CTLFLAG_RWTUN, &uvscom_debug, 0, "Debug level"); #endif #define UVSCOM_MODVER 1 /* module version */ #define UVSCOM_CONFIG_INDEX 0 #define UVSCOM_IFACE_INDEX 0 /* Request */ #define UVSCOM_SET_SPEED 0x10 #define UVSCOM_LINE_CTL 0x11 #define UVSCOM_SET_PARAM 0x12 #define UVSCOM_READ_STATUS 0xd0 #define UVSCOM_SHUTDOWN 0xe0 /* UVSCOM_SET_SPEED parameters */ #define UVSCOM_SPEED_150BPS 0x00 #define UVSCOM_SPEED_300BPS 0x01 #define UVSCOM_SPEED_600BPS 0x02 #define UVSCOM_SPEED_1200BPS 0x03 #define UVSCOM_SPEED_2400BPS 0x04 #define UVSCOM_SPEED_4800BPS 0x05 #define UVSCOM_SPEED_9600BPS 0x06 #define UVSCOM_SPEED_19200BPS 0x07 #define UVSCOM_SPEED_38400BPS 0x08 #define UVSCOM_SPEED_57600BPS 0x09 #define UVSCOM_SPEED_115200BPS 0x0a /* UVSCOM_LINE_CTL parameters */ #define UVSCOM_BREAK 0x40 #define UVSCOM_RTS 0x02 #define UVSCOM_DTR 0x01 #define UVSCOM_LINE_INIT 0x08 /* UVSCOM_SET_PARAM parameters */ #define UVSCOM_DATA_MASK 0x03 #define UVSCOM_DATA_BIT_8 0x03 #define UVSCOM_DATA_BIT_7 0x02 #define UVSCOM_DATA_BIT_6 0x01 #define UVSCOM_DATA_BIT_5 0x00 #define UVSCOM_STOP_MASK 0x04 #define UVSCOM_STOP_BIT_2 0x04 #define UVSCOM_STOP_BIT_1 0x00 #define UVSCOM_PARITY_MASK 0x18 #define UVSCOM_PARITY_EVEN 0x18 #define UVSCOM_PARITY_ODD 0x08 #define UVSCOM_PARITY_NONE 0x00 /* Status bits */ #define UVSCOM_TXRDY 0x04 #define UVSCOM_RXRDY 0x01 #define UVSCOM_DCD 0x08 #define UVSCOM_NOCARD 0x04 #define UVSCOM_DSR 0x02 #define UVSCOM_CTS 0x01 #define UVSCOM_USTAT_MASK (UVSCOM_NOCARD | UVSCOM_DSR | UVSCOM_CTS) #define UVSCOM_BULK_BUF_SIZE 1024 /* bytes */ enum { UVSCOM_BULK_DT_WR, UVSCOM_BULK_DT_RD, UVSCOM_INTR_DT_RD, UVSCOM_N_TRANSFER, }; struct uvscom_softc { struct ucom_super_softc sc_super_ucom; struct ucom_softc sc_ucom; struct usb_xfer *sc_xfer[UVSCOM_N_TRANSFER]; struct usb_device *sc_udev; struct mtx sc_mtx; uint16_t sc_line; /* line control register */ uint8_t sc_iface_no; /* interface number */ uint8_t sc_iface_index; /* interface index */ uint8_t sc_lsr; /* local status register */ uint8_t sc_msr; /* uvscom status register */ uint8_t sc_unit_status; /* unit status */ }; /* prototypes */ static device_probe_t uvscom_probe; static device_attach_t uvscom_attach; static device_detach_t uvscom_detach; static void uvscom_free_softc(struct uvscom_softc *); static usb_callback_t uvscom_write_callback; static usb_callback_t uvscom_read_callback; static usb_callback_t uvscom_intr_callback; static void uvscom_free(struct ucom_softc *); static void uvscom_cfg_set_dtr(struct ucom_softc *, uint8_t); static void uvscom_cfg_set_rts(struct ucom_softc *, uint8_t); static void uvscom_cfg_set_break(struct ucom_softc *, uint8_t); static int uvscom_pre_param(struct ucom_softc *, struct termios *); static void uvscom_cfg_param(struct ucom_softc *, struct termios *); static int uvscom_pre_open(struct ucom_softc *); static void uvscom_cfg_open(struct ucom_softc *); static void uvscom_cfg_close(struct ucom_softc *); static void uvscom_start_read(struct ucom_softc *); static void uvscom_stop_read(struct ucom_softc *); static void uvscom_start_write(struct ucom_softc *); static void uvscom_stop_write(struct ucom_softc *); static void uvscom_cfg_get_status(struct ucom_softc *, uint8_t *, uint8_t *); static void uvscom_cfg_write(struct uvscom_softc *, uint8_t, uint16_t); static uint16_t uvscom_cfg_read_status(struct uvscom_softc *); static void uvscom_poll(struct ucom_softc *ucom); static const struct usb_config uvscom_config[UVSCOM_N_TRANSFER] = { [UVSCOM_BULK_DT_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = UVSCOM_BULK_BUF_SIZE, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = &uvscom_write_callback, }, [UVSCOM_BULK_DT_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = UVSCOM_BULK_BUF_SIZE, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = &uvscom_read_callback, }, [UVSCOM_INTR_DT_RD] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = &uvscom_intr_callback, }, }; static const struct ucom_callback uvscom_callback = { .ucom_cfg_get_status = &uvscom_cfg_get_status, .ucom_cfg_set_dtr = &uvscom_cfg_set_dtr, .ucom_cfg_set_rts = &uvscom_cfg_set_rts, .ucom_cfg_set_break = &uvscom_cfg_set_break, .ucom_cfg_param = &uvscom_cfg_param, .ucom_cfg_open = &uvscom_cfg_open, .ucom_cfg_close = &uvscom_cfg_close, .ucom_pre_open = &uvscom_pre_open, .ucom_pre_param = &uvscom_pre_param, .ucom_start_read = &uvscom_start_read, .ucom_stop_read = &uvscom_stop_read, .ucom_start_write = &uvscom_start_write, .ucom_stop_write = &uvscom_stop_write, .ucom_poll = &uvscom_poll, .ucom_free = &uvscom_free, }; static const STRUCT_USB_HOST_ID uvscom_devs[] = { /* SUNTAC U-Cable type A4 */ {USB_VPI(USB_VENDOR_SUNTAC, USB_PRODUCT_SUNTAC_AS144L4, 0)}, /* SUNTAC U-Cable type D2 */ {USB_VPI(USB_VENDOR_SUNTAC, USB_PRODUCT_SUNTAC_DS96L, 0)}, /* SUNTAC Ir-Trinity */ {USB_VPI(USB_VENDOR_SUNTAC, USB_PRODUCT_SUNTAC_IS96U, 0)}, /* SUNTAC U-Cable type P1 */ {USB_VPI(USB_VENDOR_SUNTAC, USB_PRODUCT_SUNTAC_PS64P1, 0)}, /* SUNTAC Slipper U */ {USB_VPI(USB_VENDOR_SUNTAC, USB_PRODUCT_SUNTAC_VS10U, 0)}, }; static device_method_t uvscom_methods[] = { DEVMETHOD(device_probe, uvscom_probe), DEVMETHOD(device_attach, uvscom_attach), DEVMETHOD(device_detach, uvscom_detach), DEVMETHOD_END }; static devclass_t uvscom_devclass; static driver_t uvscom_driver = { .name = "uvscom", .methods = uvscom_methods, .size = sizeof(struct uvscom_softc), }; DRIVER_MODULE(uvscom, uhub, uvscom_driver, uvscom_devclass, NULL, 0); MODULE_DEPEND(uvscom, ucom, 1, 1, 1); MODULE_DEPEND(uvscom, usb, 1, 1, 1); MODULE_VERSION(uvscom, UVSCOM_MODVER); static int uvscom_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) { return (ENXIO); } if (uaa->info.bConfigIndex != UVSCOM_CONFIG_INDEX) { return (ENXIO); } if (uaa->info.bIfaceIndex != UVSCOM_IFACE_INDEX) { return (ENXIO); } return (usbd_lookup_id_by_uaa(uvscom_devs, sizeof(uvscom_devs), uaa)); } static int uvscom_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct uvscom_softc *sc = device_get_softc(dev); int error; device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "uvscom", NULL, MTX_DEF); ucom_ref(&sc->sc_super_ucom); sc->sc_udev = uaa->device; DPRINTF("sc=%p\n", sc); sc->sc_iface_no = uaa->info.bIfaceNum; sc->sc_iface_index = UVSCOM_IFACE_INDEX; error = usbd_transfer_setup(uaa->device, &sc->sc_iface_index, sc->sc_xfer, uvscom_config, UVSCOM_N_TRANSFER, sc, &sc->sc_mtx); if (error) { DPRINTF("could not allocate all USB transfers!\n"); goto detach; } sc->sc_line = UVSCOM_LINE_INIT; /* clear stall at first run */ mtx_lock(&sc->sc_mtx); usbd_xfer_set_stall(sc->sc_xfer[UVSCOM_BULK_DT_WR]); usbd_xfer_set_stall(sc->sc_xfer[UVSCOM_BULK_DT_RD]); mtx_unlock(&sc->sc_mtx); error = ucom_attach(&sc->sc_super_ucom, &sc->sc_ucom, 1, sc, &uvscom_callback, &sc->sc_mtx); if (error) { goto detach; } ucom_set_pnpinfo_usb(&sc->sc_super_ucom, dev); /* start interrupt pipe */ mtx_lock(&sc->sc_mtx); usbd_transfer_start(sc->sc_xfer[UVSCOM_INTR_DT_RD]); mtx_unlock(&sc->sc_mtx); return (0); detach: uvscom_detach(dev); return (ENXIO); } static int uvscom_detach(device_t dev) { struct uvscom_softc *sc = device_get_softc(dev); DPRINTF("sc=%p\n", sc); /* stop interrupt pipe */ if (sc->sc_xfer[UVSCOM_INTR_DT_RD]) usbd_transfer_stop(sc->sc_xfer[UVSCOM_INTR_DT_RD]); ucom_detach(&sc->sc_super_ucom, &sc->sc_ucom); usbd_transfer_unsetup(sc->sc_xfer, UVSCOM_N_TRANSFER); device_claim_softc(dev); uvscom_free_softc(sc); return (0); } UCOM_UNLOAD_DRAIN(uvscom); static void uvscom_free_softc(struct uvscom_softc *sc) { if (ucom_unref(&sc->sc_super_ucom)) { mtx_destroy(&sc->sc_mtx); device_free_softc(sc); } } static void uvscom_free(struct ucom_softc *ucom) { uvscom_free_softc(ucom->sc_parent); } static void uvscom_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct uvscom_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint32_t actlen; switch (USB_GET_STATE(xfer)) { case USB_ST_SETUP: case USB_ST_TRANSFERRED: tr_setup: pc = usbd_xfer_get_frame(xfer, 0); if (ucom_get_data(&sc->sc_ucom, pc, 0, UVSCOM_BULK_BUF_SIZE, &actlen)) { usbd_xfer_set_frame_len(xfer, 0, actlen); usbd_transfer_submit(xfer); } return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void uvscom_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct uvscom_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); ucom_put_data(&sc->sc_ucom, pc, 0, actlen); case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void uvscom_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct uvscom_softc *sc = usbd_xfer_softc(xfer); struct usb_page_cache *pc; uint8_t buf[2]; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: if (actlen >= 2) { pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, buf, sizeof(buf)); sc->sc_lsr = 0; sc->sc_msr = 0; sc->sc_unit_status = buf[1]; if (buf[0] & UVSCOM_TXRDY) { sc->sc_lsr |= ULSR_TXRDY; } if (buf[0] & UVSCOM_RXRDY) { sc->sc_lsr |= ULSR_RXRDY; } if (buf[1] & UVSCOM_CTS) { sc->sc_msr |= SER_CTS; } if (buf[1] & UVSCOM_DSR) { sc->sc_msr |= SER_DSR; } if (buf[1] & UVSCOM_DCD) { sc->sc_msr |= SER_DCD; } /* * the UCOM layer will ignore this call if the TTY * device is closed! */ ucom_status_change(&sc->sc_ucom); } case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static void uvscom_cfg_set_dtr(struct ucom_softc *ucom, uint8_t onoff) { struct uvscom_softc *sc = ucom->sc_parent; DPRINTF("onoff = %d\n", onoff); if (onoff) sc->sc_line |= UVSCOM_DTR; else sc->sc_line &= ~UVSCOM_DTR; uvscom_cfg_write(sc, UVSCOM_LINE_CTL, sc->sc_line); } static void uvscom_cfg_set_rts(struct ucom_softc *ucom, uint8_t onoff) { struct uvscom_softc *sc = ucom->sc_parent; DPRINTF("onoff = %d\n", onoff); if (onoff) sc->sc_line |= UVSCOM_RTS; else sc->sc_line &= ~UVSCOM_RTS; uvscom_cfg_write(sc, UVSCOM_LINE_CTL, sc->sc_line); } static void uvscom_cfg_set_break(struct ucom_softc *ucom, uint8_t onoff) { struct uvscom_softc *sc = ucom->sc_parent; DPRINTF("onoff = %d\n", onoff); if (onoff) sc->sc_line |= UVSCOM_BREAK; else sc->sc_line &= ~UVSCOM_BREAK; uvscom_cfg_write(sc, UVSCOM_LINE_CTL, sc->sc_line); } static int uvscom_pre_param(struct ucom_softc *ucom, struct termios *t) { switch (t->c_ospeed) { case B150: case B300: case B600: case B1200: case B2400: case B4800: case B9600: case B19200: case B38400: case B57600: case B115200: default: return (EINVAL); } return (0); } static void uvscom_cfg_param(struct ucom_softc *ucom, struct termios *t) { struct uvscom_softc *sc = ucom->sc_parent; uint16_t value; DPRINTF("\n"); switch (t->c_ospeed) { case B150: value = UVSCOM_SPEED_150BPS; break; case B300: value = UVSCOM_SPEED_300BPS; break; case B600: value = UVSCOM_SPEED_600BPS; break; case B1200: value = UVSCOM_SPEED_1200BPS; break; case B2400: value = UVSCOM_SPEED_2400BPS; break; case B4800: value = UVSCOM_SPEED_4800BPS; break; case B9600: value = UVSCOM_SPEED_9600BPS; break; case B19200: value = UVSCOM_SPEED_19200BPS; break; case B38400: value = UVSCOM_SPEED_38400BPS; break; case B57600: value = UVSCOM_SPEED_57600BPS; break; case B115200: value = UVSCOM_SPEED_115200BPS; break; default: return; } uvscom_cfg_write(sc, UVSCOM_SET_SPEED, value); value = 0; if (t->c_cflag & CSTOPB) { value |= UVSCOM_STOP_BIT_2; } if (t->c_cflag & PARENB) { if (t->c_cflag & PARODD) { value |= UVSCOM_PARITY_ODD; } else { value |= UVSCOM_PARITY_EVEN; } } else { value |= UVSCOM_PARITY_NONE; } switch (t->c_cflag & CSIZE) { case CS5: value |= UVSCOM_DATA_BIT_5; break; case CS6: value |= UVSCOM_DATA_BIT_6; break; case CS7: value |= UVSCOM_DATA_BIT_7; break; default: case CS8: value |= UVSCOM_DATA_BIT_8; break; } uvscom_cfg_write(sc, UVSCOM_SET_PARAM, value); } static int uvscom_pre_open(struct ucom_softc *ucom) { struct uvscom_softc *sc = ucom->sc_parent; DPRINTF("sc = %p\n", sc); /* check if PC card was inserted */ if (sc->sc_unit_status & UVSCOM_NOCARD) { DPRINTF("no PC card!\n"); return (ENXIO); } return (0); } static void uvscom_cfg_open(struct ucom_softc *ucom) { struct uvscom_softc *sc = ucom->sc_parent; DPRINTF("sc = %p\n", sc); uvscom_cfg_read_status(sc); } static void uvscom_cfg_close(struct ucom_softc *ucom) { struct uvscom_softc *sc = ucom->sc_parent; DPRINTF("sc=%p\n", sc); uvscom_cfg_write(sc, UVSCOM_SHUTDOWN, 0); } static void uvscom_start_read(struct ucom_softc *ucom) { struct uvscom_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[UVSCOM_BULK_DT_RD]); } static void uvscom_stop_read(struct ucom_softc *ucom) { struct uvscom_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[UVSCOM_BULK_DT_RD]); } static void uvscom_start_write(struct ucom_softc *ucom) { struct uvscom_softc *sc = ucom->sc_parent; usbd_transfer_start(sc->sc_xfer[UVSCOM_BULK_DT_WR]); } static void uvscom_stop_write(struct ucom_softc *ucom) { struct uvscom_softc *sc = ucom->sc_parent; usbd_transfer_stop(sc->sc_xfer[UVSCOM_BULK_DT_WR]); } static void uvscom_cfg_get_status(struct ucom_softc *ucom, uint8_t *lsr, uint8_t *msr) { struct uvscom_softc *sc = ucom->sc_parent; *lsr = sc->sc_lsr; *msr = sc->sc_msr; } static void uvscom_cfg_write(struct uvscom_softc *sc, uint8_t index, uint16_t value) { struct usb_device_request req; usb_error_t err; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = index; USETW(req.wValue, value); USETW(req.wIndex, 0); USETW(req.wLength, 0); err = ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, NULL, 0, 1000); if (err) { DPRINTFN(0, "device request failed, err=%s " "(ignored)\n", usbd_errstr(err)); } } static uint16_t uvscom_cfg_read_status(struct uvscom_softc *sc) { struct usb_device_request req; usb_error_t err; uint8_t data[2]; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = UVSCOM_READ_STATUS; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, 2); err = ucom_cfg_do_request(sc->sc_udev, &sc->sc_ucom, &req, data, 0, 1000); if (err) { DPRINTFN(0, "device request failed, err=%s " "(ignored)\n", usbd_errstr(err)); } return (data[0] | (data[1] << 8)); } static void uvscom_poll(struct ucom_softc *ucom) { struct uvscom_softc *sc = ucom->sc_parent; usbd_transfer_poll(sc->sc_xfer, UVSCOM_N_TRANSFER); } Index: head/sys/dev/usb/storage/urio.c =================================================================== --- head/sys/dev/usb/storage/urio.c (revision 276700) +++ head/sys/dev/usb/storage/urio.c (revision 276701) @@ -1,496 +1,496 @@ /*- * Copyright (c) 2000 Iwasa Kazmi * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This code is based on ugen.c and ulpt.c developed by Lennart Augustsson. * This code includes software developed by the NetBSD Foundation, Inc. and * its contributors. */ #include __FBSDID("$FreeBSD$"); /* * 2000/3/24 added NetBSD/OpenBSD support (from Alex Nemirovsky) * 2000/3/07 use two bulk-pipe handles for read and write (Dirk) * 2000/3/06 change major number(143), and copyright header * some fix for 4.0 (Dirk) * 2000/3/05 codes for FreeBSD 4.x - CURRENT (Thanks to Dirk-Willem van Gulik) * 2000/3/01 remove retry code from urioioctl() * change method of bulk transfer (no interrupt) * 2000/2/28 small fixes for new rio_usb.h * 2000/2/24 first version. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #include #include #define USB_DEBUG_VAR urio_debug #include #include #ifdef USB_DEBUG static int urio_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, urio, CTLFLAG_RW, 0, "USB urio"); -SYSCTL_INT(_hw_usb_urio, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_urio, OID_AUTO, debug, CTLFLAG_RWTUN, &urio_debug, 0, "urio debug level"); #endif #define URIO_T_WR 0 #define URIO_T_RD 1 #define URIO_T_WR_CS 2 #define URIO_T_RD_CS 3 #define URIO_T_MAX 4 #define URIO_BSIZE (1<<12) /* bytes */ #define URIO_IFQ_MAXLEN 2 /* units */ struct urio_softc { struct usb_fifo_sc sc_fifo; struct mtx sc_mtx; struct usb_device *sc_udev; struct usb_xfer *sc_xfer[URIO_T_MAX]; uint8_t sc_flags; #define URIO_FLAG_READ_STALL 0x01 /* read transfer stalled */ #define URIO_FLAG_WRITE_STALL 0x02 /* write transfer stalled */ uint8_t sc_name[16]; }; /* prototypes */ static device_probe_t urio_probe; static device_attach_t urio_attach; static device_detach_t urio_detach; static usb_callback_t urio_write_callback; static usb_callback_t urio_write_clear_stall_callback; static usb_callback_t urio_read_callback; static usb_callback_t urio_read_clear_stall_callback; static usb_fifo_close_t urio_close; static usb_fifo_cmd_t urio_start_read; static usb_fifo_cmd_t urio_start_write; static usb_fifo_cmd_t urio_stop_read; static usb_fifo_cmd_t urio_stop_write; static usb_fifo_ioctl_t urio_ioctl; static usb_fifo_open_t urio_open; static struct usb_fifo_methods urio_fifo_methods = { .f_close = &urio_close, .f_ioctl = &urio_ioctl, .f_open = &urio_open, .f_start_read = &urio_start_read, .f_start_write = &urio_start_write, .f_stop_read = &urio_stop_read, .f_stop_write = &urio_stop_write, .basename[0] = "urio", }; static const struct usb_config urio_config[URIO_T_MAX] = { [URIO_T_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = URIO_BSIZE, .flags = {.pipe_bof = 1,.force_short_xfer = 1,.proxy_buffer = 1,}, .callback = &urio_write_callback, }, [URIO_T_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = URIO_BSIZE, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,.proxy_buffer = 1,}, .callback = &urio_read_callback, }, [URIO_T_WR_CS] = { .type = UE_CONTROL, .endpoint = 0x00, /* Control pipe */ .direction = UE_DIR_ANY, .bufsize = sizeof(struct usb_device_request), .callback = &urio_write_clear_stall_callback, .timeout = 1000, /* 1 second */ .interval = 50, /* 50ms */ }, [URIO_T_RD_CS] = { .type = UE_CONTROL, .endpoint = 0x00, /* Control pipe */ .direction = UE_DIR_ANY, .bufsize = sizeof(struct usb_device_request), .callback = &urio_read_clear_stall_callback, .timeout = 1000, /* 1 second */ .interval = 50, /* 50ms */ }, }; static devclass_t urio_devclass; static device_method_t urio_methods[] = { /* Device interface */ DEVMETHOD(device_probe, urio_probe), DEVMETHOD(device_attach, urio_attach), DEVMETHOD(device_detach, urio_detach), DEVMETHOD_END }; static driver_t urio_driver = { .name = "urio", .methods = urio_methods, .size = sizeof(struct urio_softc), }; DRIVER_MODULE(urio, uhub, urio_driver, urio_devclass, NULL, 0); MODULE_DEPEND(urio, usb, 1, 1, 1); MODULE_VERSION(urio, 1); static const STRUCT_USB_HOST_ID urio_devs[] = { {USB_VPI(USB_VENDOR_DIAMOND, USB_PRODUCT_DIAMOND_RIO500USB, 0)}, {USB_VPI(USB_VENDOR_DIAMOND2, USB_PRODUCT_DIAMOND2_RIO600USB, 0)}, {USB_VPI(USB_VENDOR_DIAMOND2, USB_PRODUCT_DIAMOND2_RIO800USB, 0)}, }; static int urio_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != 0) return (ENXIO); if (uaa->info.bIfaceIndex != 0) return (ENXIO); return (usbd_lookup_id_by_uaa(urio_devs, sizeof(urio_devs), uaa)); } static int urio_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct urio_softc *sc = device_get_softc(dev); int error; device_set_usb_desc(dev); sc->sc_udev = uaa->device; mtx_init(&sc->sc_mtx, "urio lock", NULL, MTX_DEF | MTX_RECURSE); snprintf(sc->sc_name, sizeof(sc->sc_name), "%s", device_get_nameunit(dev)); error = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex, sc->sc_xfer, urio_config, URIO_T_MAX, sc, &sc->sc_mtx); if (error) { DPRINTF("error=%s\n", usbd_errstr(error)); goto detach; } error = usb_fifo_attach(uaa->device, sc, &sc->sc_mtx, &urio_fifo_methods, &sc->sc_fifo, device_get_unit(dev), -1, uaa->info.bIfaceIndex, UID_ROOT, GID_OPERATOR, 0644); if (error) { goto detach; } return (0); /* success */ detach: urio_detach(dev); return (ENOMEM); /* failure */ } static void urio_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct urio_softc *sc = usbd_xfer_softc(xfer); struct usb_fifo *f = sc->sc_fifo.fp[USB_FIFO_TX]; struct usb_page_cache *pc; uint32_t actlen; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: case USB_ST_SETUP: if (sc->sc_flags & URIO_FLAG_WRITE_STALL) { usbd_transfer_start(sc->sc_xfer[URIO_T_WR_CS]); return; } pc = usbd_xfer_get_frame(xfer, 0); if (usb_fifo_get_data(f, pc, 0, usbd_xfer_max_len(xfer), &actlen, 0)) { usbd_xfer_set_frame_len(xfer, 0, actlen); usbd_transfer_submit(xfer); } return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ sc->sc_flags |= URIO_FLAG_WRITE_STALL; usbd_transfer_start(sc->sc_xfer[URIO_T_WR_CS]); } return; } } static void urio_write_clear_stall_callback(struct usb_xfer *xfer, usb_error_t error) { struct urio_softc *sc = usbd_xfer_softc(xfer); struct usb_xfer *xfer_other = sc->sc_xfer[URIO_T_WR]; if (usbd_clear_stall_callback(xfer, xfer_other)) { DPRINTF("stall cleared\n"); sc->sc_flags &= ~URIO_FLAG_WRITE_STALL; usbd_transfer_start(xfer_other); } } static void urio_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct urio_softc *sc = usbd_xfer_softc(xfer); struct usb_fifo *f = sc->sc_fifo.fp[USB_FIFO_RX]; struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); usb_fifo_put_data(f, pc, 0, actlen, 1); case USB_ST_SETUP: if (sc->sc_flags & URIO_FLAG_READ_STALL) { usbd_transfer_start(sc->sc_xfer[URIO_T_RD_CS]); return; } if (usb_fifo_put_bytes_max(f) != 0) { usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); } return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ sc->sc_flags |= URIO_FLAG_READ_STALL; usbd_transfer_start(sc->sc_xfer[URIO_T_RD_CS]); } return; } } static void urio_read_clear_stall_callback(struct usb_xfer *xfer, usb_error_t error) { struct urio_softc *sc = usbd_xfer_softc(xfer); struct usb_xfer *xfer_other = sc->sc_xfer[URIO_T_RD]; if (usbd_clear_stall_callback(xfer, xfer_other)) { DPRINTF("stall cleared\n"); sc->sc_flags &= ~URIO_FLAG_READ_STALL; usbd_transfer_start(xfer_other); } } static void urio_start_read(struct usb_fifo *fifo) { struct urio_softc *sc = usb_fifo_softc(fifo); usbd_transfer_start(sc->sc_xfer[URIO_T_RD]); } static void urio_stop_read(struct usb_fifo *fifo) { struct urio_softc *sc = usb_fifo_softc(fifo); usbd_transfer_stop(sc->sc_xfer[URIO_T_RD_CS]); usbd_transfer_stop(sc->sc_xfer[URIO_T_RD]); } static void urio_start_write(struct usb_fifo *fifo) { struct urio_softc *sc = usb_fifo_softc(fifo); usbd_transfer_start(sc->sc_xfer[URIO_T_WR]); } static void urio_stop_write(struct usb_fifo *fifo) { struct urio_softc *sc = usb_fifo_softc(fifo); usbd_transfer_stop(sc->sc_xfer[URIO_T_WR_CS]); usbd_transfer_stop(sc->sc_xfer[URIO_T_WR]); } static int urio_open(struct usb_fifo *fifo, int fflags) { struct urio_softc *sc = usb_fifo_softc(fifo); if (fflags & FREAD) { /* clear stall first */ mtx_lock(&sc->sc_mtx); sc->sc_flags |= URIO_FLAG_READ_STALL; mtx_unlock(&sc->sc_mtx); if (usb_fifo_alloc_buffer(fifo, usbd_xfer_max_len(sc->sc_xfer[URIO_T_RD]), URIO_IFQ_MAXLEN)) { return (ENOMEM); } } if (fflags & FWRITE) { /* clear stall first */ sc->sc_flags |= URIO_FLAG_WRITE_STALL; if (usb_fifo_alloc_buffer(fifo, usbd_xfer_max_len(sc->sc_xfer[URIO_T_WR]), URIO_IFQ_MAXLEN)) { return (ENOMEM); } } return (0); /* success */ } static void urio_close(struct usb_fifo *fifo, int fflags) { if (fflags & (FREAD | FWRITE)) { usb_fifo_free_buffer(fifo); } } static int urio_ioctl(struct usb_fifo *fifo, u_long cmd, void *addr, int fflags) { struct usb_ctl_request ur; struct RioCommand *rio_cmd; int error; switch (cmd) { case RIO_RECV_COMMAND: if (!(fflags & FWRITE)) { error = EPERM; goto done; } memset(&ur, 0, sizeof(ur)); rio_cmd = addr; ur.ucr_request.bmRequestType = rio_cmd->requesttype | UT_READ_VENDOR_DEVICE; break; case RIO_SEND_COMMAND: if (!(fflags & FWRITE)) { error = EPERM; goto done; } memset(&ur, 0, sizeof(ur)); rio_cmd = addr; ur.ucr_request.bmRequestType = rio_cmd->requesttype | UT_WRITE_VENDOR_DEVICE; break; default: error = EINVAL; goto done; } DPRINTFN(2, "Sending command\n"); /* Send rio control message */ ur.ucr_request.bRequest = rio_cmd->request; USETW(ur.ucr_request.wValue, rio_cmd->value); USETW(ur.ucr_request.wIndex, rio_cmd->index); USETW(ur.ucr_request.wLength, rio_cmd->length); ur.ucr_data = rio_cmd->buffer; /* reuse generic USB code */ error = ugen_do_request(fifo, &ur); done: return (error); } static int urio_detach(device_t dev) { struct urio_softc *sc = device_get_softc(dev); DPRINTF("\n"); usb_fifo_detach(&sc->sc_fifo); usbd_transfer_unsetup(sc->sc_xfer, URIO_T_MAX); mtx_destroy(&sc->sc_mtx); return (0); } Index: head/sys/dev/usb/storage/ustorage_fs.c =================================================================== --- head/sys/dev/usb/storage/ustorage_fs.c (revision 276700) +++ head/sys/dev/usb/storage/ustorage_fs.c (revision 276701) @@ -1,1959 +1,1959 @@ /* $FreeBSD$ */ /*- * Copyright (C) 2003-2005 Alan Stern * Copyright (C) 2008 Hans Petter Selasky * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The names of the above-listed copyright holders may not be used * to endorse or promote products derived from this software without * specific prior written permission. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * NOTE: Much of the SCSI statemachine handling code derives from the * Linux USB gadget stack. */ #ifdef USB_GLOBAL_INCLUDE_FILE #include USB_GLOBAL_INCLUDE_FILE #else #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "usbdevs.h" #include "usb_if.h" #define USB_DEBUG_VAR ustorage_fs_debug #include #endif /* USB_GLOBAL_INCLUDE_FILE */ #ifdef USB_DEBUG static int ustorage_fs_debug = 0; SYSCTL_NODE(_hw_usb, OID_AUTO, ustorage_fs, CTLFLAG_RW, 0, "USB ustorage_fs"); -SYSCTL_INT(_hw_usb_ustorage_fs, OID_AUTO, debug, CTLFLAG_RW, +SYSCTL_INT(_hw_usb_ustorage_fs, OID_AUTO, debug, CTLFLAG_RWTUN, &ustorage_fs_debug, 0, "ustorage_fs debug level"); #endif /* Define some limits */ #ifndef USTORAGE_FS_BULK_SIZE #define USTORAGE_FS_BULK_SIZE (1U << 17) /* bytes */ #endif #ifndef USTORAGE_FS_MAX_LUN #define USTORAGE_FS_MAX_LUN 8 /* units */ #endif #ifndef USTORAGE_QDATA_MAX #define USTORAGE_QDATA_MAX 40 /* bytes */ #endif /* * The SCSI ID string must be exactly 28 characters long * exluding the terminating zero. */ #ifndef USTORAGE_FS_ID_STRING #define USTORAGE_FS_ID_STRING \ "FreeBSD " /* 8 */ \ "File-Stor Gadget" /* 16 */ \ "0101" /* 4 */ #endif /* * The following macro defines the number of * sectors to be allocated for the RAM disk: */ #ifndef USTORAGE_FS_RAM_SECT #define USTORAGE_FS_RAM_SECT (1UL << 13) #endif static uint8_t *ustorage_fs_ramdisk; /* USB transfer definitions */ #define USTORAGE_FS_T_BBB_COMMAND 0 #define USTORAGE_FS_T_BBB_DATA_DUMP 1 #define USTORAGE_FS_T_BBB_DATA_READ 2 #define USTORAGE_FS_T_BBB_DATA_WRITE 3 #define USTORAGE_FS_T_BBB_STATUS 4 #define USTORAGE_FS_T_BBB_MAX 5 /* USB data stage direction */ #define DIR_NONE 0 #define DIR_READ 1 #define DIR_WRITE 2 /* USB interface specific control request */ #define UR_BBB_RESET 0xff /* Bulk-Only reset */ #define UR_BBB_GET_MAX_LUN 0xfe /* Get maximum lun */ /* Command Block Wrapper */ typedef struct { uDWord dCBWSignature; #define CBWSIGNATURE 0x43425355 uDWord dCBWTag; uDWord dCBWDataTransferLength; uByte bCBWFlags; #define CBWFLAGS_OUT 0x00 #define CBWFLAGS_IN 0x80 uByte bCBWLUN; uByte bCDBLength; #define CBWCDBLENGTH 16 uByte CBWCDB[CBWCDBLENGTH]; } __packed ustorage_fs_bbb_cbw_t; #define USTORAGE_FS_BBB_CBW_SIZE 31 /* Command Status Wrapper */ typedef struct { uDWord dCSWSignature; #define CSWSIGNATURE 0x53425355 uDWord dCSWTag; uDWord dCSWDataResidue; uByte bCSWStatus; #define CSWSTATUS_GOOD 0x0 #define CSWSTATUS_FAILED 0x1 #define CSWSTATUS_PHASE 0x2 } __packed ustorage_fs_bbb_csw_t; #define USTORAGE_FS_BBB_CSW_SIZE 13 struct ustorage_fs_lun { uint8_t *memory_image; uint32_t num_sectors; uint32_t sense_data; uint32_t sense_data_info; uint32_t unit_attention_data; uint8_t read_only:1; uint8_t prevent_medium_removal:1; uint8_t info_valid:1; uint8_t removable:1; }; struct ustorage_fs_softc { ustorage_fs_bbb_cbw_t *sc_cbw; /* Command Wrapper Block */ ustorage_fs_bbb_csw_t *sc_csw; /* Command Status Block */ void *sc_dma_ptr; /* Main data buffer */ struct mtx sc_mtx; struct ustorage_fs_lun sc_lun[USTORAGE_FS_MAX_LUN]; struct { uint8_t *data_ptr; struct ustorage_fs_lun *currlun; uint32_t data_rem; /* bytes, as reported by the command * block wrapper */ uint32_t offset; /* bytes */ uint8_t cbw_dir; uint8_t cmd_dir; uint8_t lun; uint8_t cmd_len; uint8_t data_short:1; uint8_t data_error:1; } sc_transfer; device_t sc_dev; struct usb_device *sc_udev; struct usb_xfer *sc_xfer[USTORAGE_FS_T_BBB_MAX]; uint8_t sc_iface_no; /* interface number */ uint8_t sc_last_lun; uint8_t sc_last_xfer_index; uint8_t sc_qdata[USTORAGE_QDATA_MAX]; }; /* prototypes */ static device_probe_t ustorage_fs_probe; static device_attach_t ustorage_fs_attach; static device_detach_t ustorage_fs_detach; static device_suspend_t ustorage_fs_suspend; static device_resume_t ustorage_fs_resume; static usb_handle_request_t ustorage_fs_handle_request; static usb_callback_t ustorage_fs_t_bbb_command_callback; static usb_callback_t ustorage_fs_t_bbb_data_dump_callback; static usb_callback_t ustorage_fs_t_bbb_data_read_callback; static usb_callback_t ustorage_fs_t_bbb_data_write_callback; static usb_callback_t ustorage_fs_t_bbb_status_callback; static void ustorage_fs_transfer_start(struct ustorage_fs_softc *sc, uint8_t xfer_index); static void ustorage_fs_transfer_stop(struct ustorage_fs_softc *sc); static uint8_t ustorage_fs_verify(struct ustorage_fs_softc *sc); static uint8_t ustorage_fs_inquiry(struct ustorage_fs_softc *sc); static uint8_t ustorage_fs_request_sense(struct ustorage_fs_softc *sc); static uint8_t ustorage_fs_read_capacity(struct ustorage_fs_softc *sc); static uint8_t ustorage_fs_mode_sense(struct ustorage_fs_softc *sc); static uint8_t ustorage_fs_start_stop(struct ustorage_fs_softc *sc); static uint8_t ustorage_fs_prevent_allow(struct ustorage_fs_softc *sc); static uint8_t ustorage_fs_read_format_capacities(struct ustorage_fs_softc *sc); static uint8_t ustorage_fs_mode_select(struct ustorage_fs_softc *sc); static uint8_t ustorage_fs_min_len(struct ustorage_fs_softc *sc, uint32_t len, uint32_t mask); static uint8_t ustorage_fs_read(struct ustorage_fs_softc *sc); static uint8_t ustorage_fs_write(struct ustorage_fs_softc *sc); static uint8_t ustorage_fs_check_cmd(struct ustorage_fs_softc *sc, uint8_t cmd_size, uint16_t mask, uint8_t needs_medium); static uint8_t ustorage_fs_do_cmd(struct ustorage_fs_softc *sc); static device_method_t ustorage_fs_methods[] = { /* USB interface */ DEVMETHOD(usb_handle_request, ustorage_fs_handle_request), /* Device interface */ DEVMETHOD(device_probe, ustorage_fs_probe), DEVMETHOD(device_attach, ustorage_fs_attach), DEVMETHOD(device_detach, ustorage_fs_detach), DEVMETHOD(device_suspend, ustorage_fs_suspend), DEVMETHOD(device_resume, ustorage_fs_resume), DEVMETHOD_END }; static driver_t ustorage_fs_driver = { .name = "ustorage_fs", .methods = ustorage_fs_methods, .size = sizeof(struct ustorage_fs_softc), }; static devclass_t ustorage_fs_devclass; DRIVER_MODULE(ustorage_fs, uhub, ustorage_fs_driver, ustorage_fs_devclass, NULL, 0); MODULE_VERSION(ustorage_fs, 0); MODULE_DEPEND(ustorage_fs, usb, 1, 1, 1); static struct usb_config ustorage_fs_bbb_config[USTORAGE_FS_T_BBB_MAX] = { [USTORAGE_FS_T_BBB_COMMAND] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = sizeof(ustorage_fs_bbb_cbw_t), .callback = &ustorage_fs_t_bbb_command_callback, .usb_mode = USB_MODE_DEVICE, }, [USTORAGE_FS_T_BBB_DATA_DUMP] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = 0, /* use wMaxPacketSize */ .flags = {.proxy_buffer = 1,.short_xfer_ok = 1,}, .callback = &ustorage_fs_t_bbb_data_dump_callback, .usb_mode = USB_MODE_DEVICE, }, [USTORAGE_FS_T_BBB_DATA_READ] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = USTORAGE_FS_BULK_SIZE, .flags = {.proxy_buffer = 1,.short_xfer_ok = 1}, .callback = &ustorage_fs_t_bbb_data_read_callback, .usb_mode = USB_MODE_DEVICE, }, [USTORAGE_FS_T_BBB_DATA_WRITE] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = USTORAGE_FS_BULK_SIZE, .flags = {.proxy_buffer = 1,.short_xfer_ok = 1,.ext_buffer = 1}, .callback = &ustorage_fs_t_bbb_data_write_callback, .usb_mode = USB_MODE_DEVICE, }, [USTORAGE_FS_T_BBB_STATUS] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = sizeof(ustorage_fs_bbb_csw_t), .flags = {.short_xfer_ok = 1}, .callback = &ustorage_fs_t_bbb_status_callback, .usb_mode = USB_MODE_DEVICE, }, }; /* * USB device probe/attach/detach */ static int ustorage_fs_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct usb_interface_descriptor *id; if (uaa->usb_mode != USB_MODE_DEVICE) { return (ENXIO); } /* Check for a standards compliant device */ id = usbd_get_interface_descriptor(uaa->iface); if ((id == NULL) || (id->bInterfaceClass != UICLASS_MASS) || (id->bInterfaceSubClass != UISUBCLASS_SCSI) || (id->bInterfaceProtocol != UIPROTO_MASS_BBB)) { return (ENXIO); } return (BUS_PROBE_GENERIC); } static int ustorage_fs_attach(device_t dev) { struct ustorage_fs_softc *sc = device_get_softc(dev); struct usb_attach_arg *uaa = device_get_ivars(dev); struct usb_interface_descriptor *id; int err; int unit; /* * NOTE: the softc struct is cleared in device_set_driver. * We can safely call ustorage_fs_detach without specifically * initializing the struct. */ sc->sc_dev = dev; sc->sc_udev = uaa->device; unit = device_get_unit(dev); /* enable power saving mode */ usbd_set_power_mode(uaa->device, USB_POWER_MODE_SAVE); if (unit == 0) { if (ustorage_fs_ramdisk == NULL) { /* * allocate a memory image for our ramdisk until * further */ ustorage_fs_ramdisk = malloc(USTORAGE_FS_RAM_SECT << 9, M_USB, M_ZERO | M_WAITOK); if (ustorage_fs_ramdisk == NULL) { return (ENOMEM); } } sc->sc_lun[0].memory_image = ustorage_fs_ramdisk; sc->sc_lun[0].num_sectors = USTORAGE_FS_RAM_SECT; sc->sc_lun[0].removable = 1; } device_set_usb_desc(dev); mtx_init(&sc->sc_mtx, "USTORAGE_FS lock", NULL, (MTX_DEF | MTX_RECURSE)); /* get interface index */ id = usbd_get_interface_descriptor(uaa->iface); if (id == NULL) { device_printf(dev, "failed to get " "interface number\n"); goto detach; } sc->sc_iface_no = id->bInterfaceNumber; err = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex, sc->sc_xfer, ustorage_fs_bbb_config, USTORAGE_FS_T_BBB_MAX, sc, &sc->sc_mtx); if (err) { device_printf(dev, "could not setup required " "transfers, %s\n", usbd_errstr(err)); goto detach; } sc->sc_cbw = usbd_xfer_get_frame_buffer(sc->sc_xfer[ USTORAGE_FS_T_BBB_COMMAND], 0); sc->sc_csw = usbd_xfer_get_frame_buffer(sc->sc_xfer[ USTORAGE_FS_T_BBB_STATUS], 0); sc->sc_dma_ptr = usbd_xfer_get_frame_buffer(sc->sc_xfer[ USTORAGE_FS_T_BBB_DATA_READ], 0); /* start Mass Storage State Machine */ mtx_lock(&sc->sc_mtx); ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_COMMAND); mtx_unlock(&sc->sc_mtx); return (0); /* success */ detach: ustorage_fs_detach(dev); return (ENXIO); /* failure */ } static int ustorage_fs_detach(device_t dev) { struct ustorage_fs_softc *sc = device_get_softc(dev); /* teardown our statemachine */ usbd_transfer_unsetup(sc->sc_xfer, USTORAGE_FS_T_BBB_MAX); mtx_destroy(&sc->sc_mtx); return (0); /* success */ } static int ustorage_fs_suspend(device_t dev) { device_printf(dev, "suspending\n"); return (0); /* success */ } static int ustorage_fs_resume(device_t dev) { device_printf(dev, "resuming\n"); return (0); /* success */ } /* * Generic functions to handle transfers */ static void ustorage_fs_transfer_start(struct ustorage_fs_softc *sc, uint8_t xfer_index) { if (sc->sc_xfer[xfer_index]) { sc->sc_last_xfer_index = xfer_index; usbd_transfer_start(sc->sc_xfer[xfer_index]); } } static void ustorage_fs_transfer_stop(struct ustorage_fs_softc *sc) { usbd_transfer_stop(sc->sc_xfer[sc->sc_last_xfer_index]); mtx_unlock(&sc->sc_mtx); usbd_transfer_drain(sc->sc_xfer[sc->sc_last_xfer_index]); mtx_lock(&sc->sc_mtx); } static int ustorage_fs_handle_request(device_t dev, const void *preq, void **pptr, uint16_t *plen, uint16_t offset, uint8_t *pstate) { struct ustorage_fs_softc *sc = device_get_softc(dev); const struct usb_device_request *req = preq; uint8_t is_complete = *pstate; if (!is_complete) { if ((req->bmRequestType == UT_WRITE_CLASS_INTERFACE) && (req->bRequest == UR_BBB_RESET)) { *plen = 0; mtx_lock(&sc->sc_mtx); ustorage_fs_transfer_stop(sc); sc->sc_transfer.data_error = 1; ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_COMMAND); mtx_unlock(&sc->sc_mtx); return (0); } else if ((req->bmRequestType == UT_READ_CLASS_INTERFACE) && (req->bRequest == UR_BBB_GET_MAX_LUN)) { if (offset == 0) { *plen = 1; *pptr = &sc->sc_last_lun; } else { *plen = 0; } return (0); } } return (ENXIO); /* use builtin handler */ } static void ustorage_fs_t_bbb_command_callback(struct usb_xfer *xfer, usb_error_t error) { struct ustorage_fs_softc *sc = usbd_xfer_softc(xfer); uint32_t tag; uint8_t err = 0; DPRINTF("\n"); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: tag = UGETDW(sc->sc_cbw->dCBWSignature); if (tag != CBWSIGNATURE) { /* do nothing */ DPRINTF("invalid signature 0x%08x\n", tag); break; } tag = UGETDW(sc->sc_cbw->dCBWTag); /* echo back tag */ USETDW(sc->sc_csw->dCSWTag, tag); /* reset status */ sc->sc_csw->bCSWStatus = 0; /* reset data offset, data length and data remainder */ sc->sc_transfer.offset = 0; sc->sc_transfer.data_rem = UGETDW(sc->sc_cbw->dCBWDataTransferLength); /* reset data flags */ sc->sc_transfer.data_short = 0; /* extract LUN */ sc->sc_transfer.lun = sc->sc_cbw->bCBWLUN; if (sc->sc_transfer.data_rem == 0) { sc->sc_transfer.cbw_dir = DIR_NONE; } else { if (sc->sc_cbw->bCBWFlags & CBWFLAGS_IN) { sc->sc_transfer.cbw_dir = DIR_WRITE; } else { sc->sc_transfer.cbw_dir = DIR_READ; } } sc->sc_transfer.cmd_len = sc->sc_cbw->bCDBLength; if ((sc->sc_transfer.cmd_len > sizeof(sc->sc_cbw->CBWCDB)) || (sc->sc_transfer.cmd_len == 0)) { /* just halt - this is invalid */ DPRINTF("invalid command length %d bytes\n", sc->sc_transfer.cmd_len); break; } err = ustorage_fs_do_cmd(sc); if (err) { /* got an error */ DPRINTF("command failed\n"); break; } if ((sc->sc_transfer.data_rem > 0) && (sc->sc_transfer.cbw_dir != sc->sc_transfer.cmd_dir)) { /* contradicting data transfer direction */ err = 1; DPRINTF("data direction mismatch\n"); break; } switch (sc->sc_transfer.cbw_dir) { case DIR_READ: ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_DATA_READ); break; case DIR_WRITE: ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_DATA_WRITE); break; default: ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_STATUS); break; } break; case USB_ST_SETUP: tr_setup: if (sc->sc_transfer.data_error) { sc->sc_transfer.data_error = 0; usbd_xfer_set_stall(xfer); DPRINTF("stall pipe\n"); } usbd_xfer_set_frame_len(xfer, 0, sizeof(ustorage_fs_bbb_cbw_t)); usbd_transfer_submit(xfer); break; default: /* Error */ DPRINTF("error\n"); if (error == USB_ERR_CANCELLED) { break; } /* If the pipe is already stalled, don't do another stall */ if (!usbd_xfer_is_stalled(xfer)) sc->sc_transfer.data_error = 1; /* try again */ goto tr_setup; } if (err) { if (sc->sc_csw->bCSWStatus == 0) { /* set some default error code */ sc->sc_csw->bCSWStatus = CSWSTATUS_FAILED; } if (sc->sc_transfer.cbw_dir == DIR_READ) { /* dump all data */ ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_DATA_DUMP); return; } if (sc->sc_transfer.cbw_dir == DIR_WRITE) { /* need to stall before status */ sc->sc_transfer.data_error = 1; } ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_STATUS); } } static void ustorage_fs_t_bbb_data_dump_callback(struct usb_xfer *xfer, usb_error_t error) { struct ustorage_fs_softc *sc = usbd_xfer_softc(xfer); uint32_t max_bulk = usbd_xfer_max_len(xfer); int actlen, sumlen; usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL); DPRINTF("\n"); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: sc->sc_transfer.data_rem -= actlen; sc->sc_transfer.offset += actlen; if (actlen != sumlen || sc->sc_transfer.data_rem == 0) { /* short transfer or end of data */ ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_STATUS); break; } /* Fallthrough */ case USB_ST_SETUP: tr_setup: if (max_bulk > sc->sc_transfer.data_rem) { max_bulk = sc->sc_transfer.data_rem; } if (sc->sc_transfer.data_error) { sc->sc_transfer.data_error = 0; usbd_xfer_set_stall(xfer); } usbd_xfer_set_frame_len(xfer, 0, max_bulk); usbd_transfer_submit(xfer); break; default: /* Error */ if (error == USB_ERR_CANCELLED) { break; } /* * If the pipe is already stalled, don't do another stall: */ if (!usbd_xfer_is_stalled(xfer)) sc->sc_transfer.data_error = 1; /* try again */ goto tr_setup; } } static void ustorage_fs_t_bbb_data_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct ustorage_fs_softc *sc = usbd_xfer_softc(xfer); uint32_t max_bulk = usbd_xfer_max_len(xfer); int actlen, sumlen; usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL); DPRINTF("\n"); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: /* XXX copy data from DMA buffer */ memcpy(sc->sc_transfer.data_ptr, sc->sc_dma_ptr, actlen); sc->sc_transfer.data_rem -= actlen; sc->sc_transfer.data_ptr += actlen; sc->sc_transfer.offset += actlen; if (actlen != sumlen || sc->sc_transfer.data_rem == 0) { /* short transfer or end of data */ ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_STATUS); break; } /* Fallthrough */ case USB_ST_SETUP: tr_setup: if (max_bulk > sc->sc_transfer.data_rem) { max_bulk = sc->sc_transfer.data_rem; } if (sc->sc_transfer.data_error) { sc->sc_transfer.data_error = 0; usbd_xfer_set_stall(xfer); } usbd_xfer_set_frame_data(xfer, 0, sc->sc_dma_ptr, max_bulk); usbd_transfer_submit(xfer); break; default: /* Error */ if (error == USB_ERR_CANCELLED) { break; } /* If the pipe is already stalled, don't do another stall */ if (!usbd_xfer_is_stalled(xfer)) sc->sc_transfer.data_error = 1; /* try again */ goto tr_setup; } } static void ustorage_fs_t_bbb_data_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct ustorage_fs_softc *sc = usbd_xfer_softc(xfer); uint32_t max_bulk = usbd_xfer_max_len(xfer); int actlen, sumlen; usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL); DPRINTF("\n"); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: sc->sc_transfer.data_rem -= actlen; sc->sc_transfer.data_ptr += actlen; sc->sc_transfer.offset += actlen; if (actlen != sumlen || sc->sc_transfer.data_rem == 0) { /* short transfer or end of data */ ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_STATUS); break; } case USB_ST_SETUP: tr_setup: if (max_bulk >= sc->sc_transfer.data_rem) { max_bulk = sc->sc_transfer.data_rem; if (sc->sc_transfer.data_short) usbd_xfer_set_flag(xfer, USB_FORCE_SHORT_XFER); else usbd_xfer_clr_flag(xfer, USB_FORCE_SHORT_XFER); } else usbd_xfer_clr_flag(xfer, USB_FORCE_SHORT_XFER); if (sc->sc_transfer.data_error) { sc->sc_transfer.data_error = 0; usbd_xfer_set_stall(xfer); } /* XXX copy data to DMA buffer */ memcpy(sc->sc_dma_ptr, sc->sc_transfer.data_ptr, max_bulk); usbd_xfer_set_frame_data(xfer, 0, sc->sc_dma_ptr, max_bulk); usbd_transfer_submit(xfer); break; default: /* Error */ if (error == USB_ERR_CANCELLED) { break; } /* * If the pipe is already stalled, don't do another * stall */ if (!usbd_xfer_is_stalled(xfer)) sc->sc_transfer.data_error = 1; /* try again */ goto tr_setup; } } static void ustorage_fs_t_bbb_status_callback(struct usb_xfer *xfer, usb_error_t error) { struct ustorage_fs_softc *sc = usbd_xfer_softc(xfer); DPRINTF("\n"); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: ustorage_fs_transfer_start(sc, USTORAGE_FS_T_BBB_COMMAND); break; case USB_ST_SETUP: tr_setup: USETDW(sc->sc_csw->dCSWSignature, CSWSIGNATURE); USETDW(sc->sc_csw->dCSWDataResidue, sc->sc_transfer.data_rem); if (sc->sc_transfer.data_error) { sc->sc_transfer.data_error = 0; usbd_xfer_set_stall(xfer); } usbd_xfer_set_frame_len(xfer, 0, sizeof(ustorage_fs_bbb_csw_t)); usbd_transfer_submit(xfer); break; default: if (error == USB_ERR_CANCELLED) { break; } /* If the pipe is already stalled, don't do another stall */ if (!usbd_xfer_is_stalled(xfer)) sc->sc_transfer.data_error = 1; /* try again */ goto tr_setup; } } /* SCSI commands that we recognize */ #define SC_FORMAT_UNIT 0x04 #define SC_INQUIRY 0x12 #define SC_MODE_SELECT_6 0x15 #define SC_MODE_SELECT_10 0x55 #define SC_MODE_SENSE_6 0x1a #define SC_MODE_SENSE_10 0x5a #define SC_PREVENT_ALLOW_MEDIUM_REMOVAL 0x1e #define SC_READ_6 0x08 #define SC_READ_10 0x28 #define SC_READ_12 0xa8 #define SC_READ_CAPACITY 0x25 #define SC_READ_FORMAT_CAPACITIES 0x23 #define SC_RELEASE 0x17 #define SC_REQUEST_SENSE 0x03 #define SC_RESERVE 0x16 #define SC_SEND_DIAGNOSTIC 0x1d #define SC_START_STOP_UNIT 0x1b #define SC_SYNCHRONIZE_CACHE 0x35 #define SC_TEST_UNIT_READY 0x00 #define SC_VERIFY 0x2f #define SC_WRITE_6 0x0a #define SC_WRITE_10 0x2a #define SC_WRITE_12 0xaa /* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */ #define SS_NO_SENSE 0 #define SS_COMMUNICATION_FAILURE 0x040800 #define SS_INVALID_COMMAND 0x052000 #define SS_INVALID_FIELD_IN_CDB 0x052400 #define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100 #define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500 #define SS_MEDIUM_NOT_PRESENT 0x023a00 #define SS_MEDIUM_REMOVAL_PREVENTED 0x055302 #define SS_NOT_READY_TO_READY_TRANSITION 0x062800 #define SS_RESET_OCCURRED 0x062900 #define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900 #define SS_UNRECOVERED_READ_ERROR 0x031100 #define SS_WRITE_ERROR 0x030c02 #define SS_WRITE_PROTECTED 0x072700 #define SK(x) ((uint8_t) ((x) >> 16)) /* Sense Key byte, etc. */ #define ASC(x) ((uint8_t) ((x) >> 8)) #define ASCQ(x) ((uint8_t) (x)) /* Routines for unaligned data access */ static uint16_t get_be16(uint8_t *buf) { return ((uint16_t)buf[0] << 8) | ((uint16_t)buf[1]); } static uint32_t get_be32(uint8_t *buf) { return ((uint32_t)buf[0] << 24) | ((uint32_t)buf[1] << 16) | ((uint32_t)buf[2] << 8) | ((uint32_t)buf[3]); } static void put_be16(uint8_t *buf, uint16_t val) { buf[0] = val >> 8; buf[1] = val; } static void put_be32(uint8_t *buf, uint32_t val) { buf[0] = val >> 24; buf[1] = val >> 16; buf[2] = val >> 8; buf[3] = val & 0xff; } /*------------------------------------------------------------------------* * ustorage_fs_verify * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_verify(struct ustorage_fs_softc *sc) { struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun; uint32_t lba; uint32_t vlen; uint64_t file_offset; uint64_t amount_left; /* * Get the starting Logical Block Address */ lba = get_be32(&sc->sc_cbw->CBWCDB[2]); /* * We allow DPO (Disable Page Out = don't save data in the cache) * but we don't implement it. */ if ((sc->sc_cbw->CBWCDB[1] & ~0x10) != 0) { currlun->sense_data = SS_INVALID_FIELD_IN_CDB; return (1); } vlen = get_be16(&sc->sc_cbw->CBWCDB[7]); if (vlen == 0) { goto done; } /* No default reply */ /* Prepare to carry out the file verify */ amount_left = vlen; amount_left <<= 9; file_offset = lba; file_offset <<= 9; /* Range check */ vlen += lba; if ((vlen < lba) || (vlen > currlun->num_sectors) || (lba >= currlun->num_sectors)) { currlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; return (1); } /* XXX TODO: verify that data is readable */ done: return (ustorage_fs_min_len(sc, 0, -1U)); } /*------------------------------------------------------------------------* * ustorage_fs_inquiry * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_inquiry(struct ustorage_fs_softc *sc) { uint8_t *buf = sc->sc_transfer.data_ptr; struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun; if (!sc->sc_transfer.currlun) { /* Unsupported LUNs are okay */ memset(buf, 0, 36); buf[0] = 0x7f; /* Unsupported, no device - type */ return (ustorage_fs_min_len(sc, 36, -1U)); } memset(buf, 0, 8); /* Non - removable, direct - access device */ if (currlun->removable) buf[1] = 0x80; buf[2] = 2; /* ANSI SCSI level 2 */ buf[3] = 2; /* SCSI - 2 INQUIRY data format */ buf[4] = 31; /* Additional length */ /* No special options */ /* Copy in ID string */ memcpy(buf + 8, USTORAGE_FS_ID_STRING, 28); #if (USTORAGE_QDATA_MAX < 36) #error "(USTORAGE_QDATA_MAX < 36)" #endif return (ustorage_fs_min_len(sc, 36, -1U)); } /*------------------------------------------------------------------------* * ustorage_fs_request_sense * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_request_sense(struct ustorage_fs_softc *sc) { uint8_t *buf = sc->sc_transfer.data_ptr; struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun; uint32_t sd; uint32_t sdinfo; uint8_t valid; /* * From the SCSI-2 spec., section 7.9 (Unit attention condition): * * If a REQUEST SENSE command is received from an initiator * with a pending unit attention condition (before the target * generates the contingent allegiance condition), then the * target shall either: * a) report any pending sense data and preserve the unit * attention condition on the logical unit, or, * b) report the unit attention condition, may discard any * pending sense data, and clear the unit attention * condition on the logical unit for that initiator. * * FSG normally uses option a); enable this code to use option b). */ #if 0 if (currlun && currlun->unit_attention_data != SS_NO_SENSE) { currlun->sense_data = currlun->unit_attention_data; currlun->unit_attention_data = SS_NO_SENSE; } #endif if (!currlun) { /* Unsupported LUNs are okay */ sd = SS_LOGICAL_UNIT_NOT_SUPPORTED; sdinfo = 0; valid = 0; } else { sd = currlun->sense_data; sdinfo = currlun->sense_data_info; valid = currlun->info_valid << 7; currlun->sense_data = SS_NO_SENSE; currlun->sense_data_info = 0; currlun->info_valid = 0; } memset(buf, 0, 18); buf[0] = valid | 0x70; /* Valid, current error */ buf[2] = SK(sd); put_be32(&buf[3], sdinfo); /* Sense information */ buf[7] = 18 - 8; /* Additional sense length */ buf[12] = ASC(sd); buf[13] = ASCQ(sd); #if (USTORAGE_QDATA_MAX < 18) #error "(USTORAGE_QDATA_MAX < 18)" #endif return (ustorage_fs_min_len(sc, 18, -1U)); } /*------------------------------------------------------------------------* * ustorage_fs_read_capacity * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_read_capacity(struct ustorage_fs_softc *sc) { uint8_t *buf = sc->sc_transfer.data_ptr; struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun; uint32_t lba = get_be32(&sc->sc_cbw->CBWCDB[2]); uint8_t pmi = sc->sc_cbw->CBWCDB[8]; /* Check the PMI and LBA fields */ if ((pmi > 1) || ((pmi == 0) && (lba != 0))) { currlun->sense_data = SS_INVALID_FIELD_IN_CDB; return (1); } /* Max logical block */ put_be32(&buf[0], currlun->num_sectors - 1); /* Block length */ put_be32(&buf[4], 512); #if (USTORAGE_QDATA_MAX < 8) #error "(USTORAGE_QDATA_MAX < 8)" #endif return (ustorage_fs_min_len(sc, 8, -1U)); } /*------------------------------------------------------------------------* * ustorage_fs_mode_sense * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_mode_sense(struct ustorage_fs_softc *sc) { uint8_t *buf = sc->sc_transfer.data_ptr; struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun; uint8_t *buf0; uint16_t len; uint16_t limit; uint8_t mscmnd = sc->sc_cbw->CBWCDB[0]; uint8_t pc; uint8_t page_code; uint8_t changeable_values; uint8_t all_pages; buf0 = buf; if ((sc->sc_cbw->CBWCDB[1] & ~0x08) != 0) { /* Mask away DBD */ currlun->sense_data = SS_INVALID_FIELD_IN_CDB; return (1); } pc = sc->sc_cbw->CBWCDB[2] >> 6; page_code = sc->sc_cbw->CBWCDB[2] & 0x3f; if (pc == 3) { currlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED; return (1); } changeable_values = (pc == 1); all_pages = (page_code == 0x3f); /* * Write the mode parameter header. Fixed values are: default * medium type, no cache control (DPOFUA), and no block descriptors. * The only variable value is the WriteProtect bit. We will fill in * the mode data length later. */ memset(buf, 0, 8); if (mscmnd == SC_MODE_SENSE_6) { buf[2] = (currlun->read_only ? 0x80 : 0x00); /* WP, DPOFUA */ buf += 4; limit = 255; } else { /* SC_MODE_SENSE_10 */ buf[3] = (currlun->read_only ? 0x80 : 0x00); /* WP, DPOFUA */ buf += 8; limit = 65535; /* Should really be mod_data.buflen */ } /* No block descriptors */ /* * The mode pages, in numerical order. */ if ((page_code == 0x08) || all_pages) { buf[0] = 0x08; /* Page code */ buf[1] = 10; /* Page length */ memset(buf + 2, 0, 10); /* None of the fields are changeable */ if (!changeable_values) { buf[2] = 0x04; /* Write cache enable, */ /* Read cache not disabled */ /* No cache retention priorities */ put_be16(&buf[4], 0xffff); /* Don 't disable prefetch */ /* Minimum prefetch = 0 */ put_be16(&buf[8], 0xffff); /* Maximum prefetch */ put_be16(&buf[10], 0xffff); /* Maximum prefetch ceiling */ } buf += 12; } /* * Check that a valid page was requested and the mode data length * isn't too long. */ len = buf - buf0; if (len > limit) { currlun->sense_data = SS_INVALID_FIELD_IN_CDB; return (1); } /* Store the mode data length */ if (mscmnd == SC_MODE_SENSE_6) buf0[0] = len - 1; else put_be16(buf0, len - 2); #if (USTORAGE_QDATA_MAX < 24) #error "(USTORAGE_QDATA_MAX < 24)" #endif return (ustorage_fs_min_len(sc, len, -1U)); } /*------------------------------------------------------------------------* * ustorage_fs_start_stop * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_start_stop(struct ustorage_fs_softc *sc) { struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun; uint8_t loej; uint8_t start; uint8_t immed; if (!currlun->removable) { currlun->sense_data = SS_INVALID_COMMAND; return (1); } immed = sc->sc_cbw->CBWCDB[1] & 0x01; loej = sc->sc_cbw->CBWCDB[4] & 0x02; start = sc->sc_cbw->CBWCDB[4] & 0x01; if (immed || loej || start) { /* compile fix */ } return (0); } /*------------------------------------------------------------------------* * ustorage_fs_prevent_allow * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_prevent_allow(struct ustorage_fs_softc *sc) { struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun; uint8_t prevent; if (!currlun->removable) { currlun->sense_data = SS_INVALID_COMMAND; return (1); } prevent = sc->sc_cbw->CBWCDB[4] & 0x01; if ((sc->sc_cbw->CBWCDB[4] & ~0x01) != 0) { /* Mask away Prevent */ currlun->sense_data = SS_INVALID_FIELD_IN_CDB; return (1); } if (currlun->prevent_medium_removal && !prevent) { //fsync_sub(currlun); } currlun->prevent_medium_removal = prevent; return (0); } /*------------------------------------------------------------------------* * ustorage_fs_read_format_capacities * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_read_format_capacities(struct ustorage_fs_softc *sc) { uint8_t *buf = sc->sc_transfer.data_ptr; struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun; buf[0] = buf[1] = buf[2] = 0; buf[3] = 8; /* Only the Current / Maximum Capacity Descriptor */ buf += 4; /* Number of blocks */ put_be32(&buf[0], currlun->num_sectors); /* Block length */ put_be32(&buf[4], 512); /* Current capacity */ buf[4] = 0x02; #if (USTORAGE_QDATA_MAX < 12) #error "(USTORAGE_QDATA_MAX < 12)" #endif return (ustorage_fs_min_len(sc, 12, -1U)); } /*------------------------------------------------------------------------* * ustorage_fs_mode_select * * Return values: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_mode_select(struct ustorage_fs_softc *sc) { struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun; /* We don't support MODE SELECT */ currlun->sense_data = SS_INVALID_COMMAND; return (1); } /*------------------------------------------------------------------------* * ustorage_fs_synchronize_cache * * Return values: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_synchronize_cache(struct ustorage_fs_softc *sc) { #if 0 struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun; uint8_t rc; /* * We ignore the requested LBA and write out all dirty data buffers. */ rc = 0; if (rc) { currlun->sense_data = SS_WRITE_ERROR; } #endif return (0); } /*------------------------------------------------------------------------* * ustorage_fs_read - read data from disk * * Return values: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_read(struct ustorage_fs_softc *sc) { struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun; uint64_t file_offset; uint32_t lba; uint32_t len; /* * Get the starting Logical Block Address and check that it's not * too big */ if (sc->sc_cbw->CBWCDB[0] == SC_READ_6) { lba = (((uint32_t)sc->sc_cbw->CBWCDB[1]) << 16) | get_be16(&sc->sc_cbw->CBWCDB[2]); } else { lba = get_be32(&sc->sc_cbw->CBWCDB[2]); /* * We allow DPO (Disable Page Out = don't save data in the * cache) and FUA (Force Unit Access = don't read from the * cache), but we don't implement them. */ if ((sc->sc_cbw->CBWCDB[1] & ~0x18) != 0) { currlun->sense_data = SS_INVALID_FIELD_IN_CDB; return (1); } } len = sc->sc_transfer.data_rem >> 9; len += lba; if ((len < lba) || (len > currlun->num_sectors) || (lba >= currlun->num_sectors)) { currlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; return (1); } file_offset = lba; file_offset <<= 9; sc->sc_transfer.data_ptr = currlun->memory_image + file_offset; return (0); } /*------------------------------------------------------------------------* * ustorage_fs_write - write data to disk * * Return values: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_write(struct ustorage_fs_softc *sc) { struct ustorage_fs_lun *currlun = sc->sc_transfer.currlun; uint64_t file_offset; uint32_t lba; uint32_t len; if (currlun->read_only) { currlun->sense_data = SS_WRITE_PROTECTED; return (1); } /* XXX clear SYNC */ /* * Get the starting Logical Block Address and check that it's not * too big. */ if (sc->sc_cbw->CBWCDB[0] == SC_WRITE_6) lba = (((uint32_t)sc->sc_cbw->CBWCDB[1]) << 16) | get_be16(&sc->sc_cbw->CBWCDB[2]); else { lba = get_be32(&sc->sc_cbw->CBWCDB[2]); /* * We allow DPO (Disable Page Out = don't save data in the * cache) and FUA (Force Unit Access = write directly to the * medium). We don't implement DPO; we implement FUA by * performing synchronous output. */ if ((sc->sc_cbw->CBWCDB[1] & ~0x18) != 0) { currlun->sense_data = SS_INVALID_FIELD_IN_CDB; return (1); } if (sc->sc_cbw->CBWCDB[1] & 0x08) { /* FUA */ /* XXX set SYNC flag here */ } } len = sc->sc_transfer.data_rem >> 9; len += lba; if ((len < lba) || (len > currlun->num_sectors) || (lba >= currlun->num_sectors)) { currlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE; return (1); } file_offset = lba; file_offset <<= 9; sc->sc_transfer.data_ptr = currlun->memory_image + file_offset; return (0); } /*------------------------------------------------------------------------* * ustorage_fs_min_len * * Return values: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_min_len(struct ustorage_fs_softc *sc, uint32_t len, uint32_t mask) { if (len != sc->sc_transfer.data_rem) { if (sc->sc_transfer.cbw_dir == DIR_READ) { /* * there must be something wrong about this SCSI * command */ sc->sc_csw->bCSWStatus = CSWSTATUS_PHASE; return (1); } /* compute the minimum length */ if (sc->sc_transfer.data_rem > len) { /* data ends prematurely */ sc->sc_transfer.data_rem = len; sc->sc_transfer.data_short = 1; } /* check length alignment */ if (sc->sc_transfer.data_rem & ~mask) { /* data ends prematurely */ sc->sc_transfer.data_rem &= mask; sc->sc_transfer.data_short = 1; } } return (0); } /*------------------------------------------------------------------------* * ustorage_fs_check_cmd - check command routine * * Check whether the command is properly formed and whether its data * size and direction agree with the values we already have. * * Return values: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_check_cmd(struct ustorage_fs_softc *sc, uint8_t min_cmd_size, uint16_t mask, uint8_t needs_medium) { struct ustorage_fs_lun *currlun; uint8_t lun = (sc->sc_cbw->CBWCDB[1] >> 5); uint8_t i; /* Verify the length of the command itself */ if (min_cmd_size > sc->sc_transfer.cmd_len) { DPRINTF("%u > %u\n", min_cmd_size, sc->sc_transfer.cmd_len); sc->sc_csw->bCSWStatus = CSWSTATUS_PHASE; return (1); } /* Mask away the LUN */ sc->sc_cbw->CBWCDB[1] &= 0x1f; /* Check if LUN is correct */ if (lun != sc->sc_transfer.lun) { } /* Check the LUN */ if (sc->sc_transfer.lun <= sc->sc_last_lun) { sc->sc_transfer.currlun = currlun = sc->sc_lun + sc->sc_transfer.lun; if (sc->sc_cbw->CBWCDB[0] != SC_REQUEST_SENSE) { currlun->sense_data = SS_NO_SENSE; currlun->sense_data_info = 0; currlun->info_valid = 0; } /* * If a unit attention condition exists, only INQUIRY * and REQUEST SENSE commands are allowed. Anything * else must fail! */ if ((currlun->unit_attention_data != SS_NO_SENSE) && (sc->sc_cbw->CBWCDB[0] != SC_INQUIRY) && (sc->sc_cbw->CBWCDB[0] != SC_REQUEST_SENSE)) { currlun->sense_data = currlun->unit_attention_data; currlun->unit_attention_data = SS_NO_SENSE; return (1); } } else { sc->sc_transfer.currlun = currlun = NULL; /* * INQUIRY and REQUEST SENSE commands are explicitly allowed * to use unsupported LUNs; all others may not. */ if ((sc->sc_cbw->CBWCDB[0] != SC_INQUIRY) && (sc->sc_cbw->CBWCDB[0] != SC_REQUEST_SENSE)) { return (1); } } /* * Check that only command bytes listed in the mask are * non-zero. */ for (i = 0; i != min_cmd_size; i++) { if (sc->sc_cbw->CBWCDB[i] && !(mask & (1UL << i))) { if (currlun) { currlun->sense_data = SS_INVALID_FIELD_IN_CDB; } return (1); } } /* * If the medium isn't mounted and the command needs to access * it, return an error. */ if (currlun && (!currlun->memory_image) && needs_medium) { currlun->sense_data = SS_MEDIUM_NOT_PRESENT; return (1); } return (0); } /*------------------------------------------------------------------------* * ustorage_fs_do_cmd - do command * * Return values: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static uint8_t ustorage_fs_do_cmd(struct ustorage_fs_softc *sc) { uint8_t error = 1; uint8_t i; uint32_t temp; const uint32_t mask9 = (0xFFFFFFFFUL >> 9) << 9; /* set default data transfer pointer */ sc->sc_transfer.data_ptr = sc->sc_qdata; DPRINTF("cmd_data[0]=0x%02x, data_rem=0x%08x\n", sc->sc_cbw->CBWCDB[0], sc->sc_transfer.data_rem); switch (sc->sc_cbw->CBWCDB[0]) { case SC_INQUIRY: sc->sc_transfer.cmd_dir = DIR_WRITE; error = ustorage_fs_min_len(sc, sc->sc_cbw->CBWCDB[4], -1U); if (error) { break; } error = ustorage_fs_check_cmd(sc, 6, (1UL << 4) | 1, 0); if (error) { break; } error = ustorage_fs_inquiry(sc); break; case SC_MODE_SELECT_6: sc->sc_transfer.cmd_dir = DIR_READ; error = ustorage_fs_min_len(sc, sc->sc_cbw->CBWCDB[4], -1U); if (error) { break; } error = ustorage_fs_check_cmd(sc, 6, (1UL << 1) | (1UL << 4) | 1, 0); if (error) { break; } error = ustorage_fs_mode_select(sc); break; case SC_MODE_SELECT_10: sc->sc_transfer.cmd_dir = DIR_READ; error = ustorage_fs_min_len(sc, get_be16(&sc->sc_cbw->CBWCDB[7]), -1U); if (error) { break; } error = ustorage_fs_check_cmd(sc, 10, (1UL << 1) | (3UL << 7) | 1, 0); if (error) { break; } error = ustorage_fs_mode_select(sc); break; case SC_MODE_SENSE_6: sc->sc_transfer.cmd_dir = DIR_WRITE; error = ustorage_fs_min_len(sc, sc->sc_cbw->CBWCDB[4], -1U); if (error) { break; } error = ustorage_fs_check_cmd(sc, 6, (1UL << 1) | (1UL << 2) | (1UL << 4) | 1, 0); if (error) { break; } error = ustorage_fs_mode_sense(sc); break; case SC_MODE_SENSE_10: sc->sc_transfer.cmd_dir = DIR_WRITE; error = ustorage_fs_min_len(sc, get_be16(&sc->sc_cbw->CBWCDB[7]), -1U); if (error) { break; } error = ustorage_fs_check_cmd(sc, 10, (1UL << 1) | (1UL << 2) | (3UL << 7) | 1, 0); if (error) { break; } error = ustorage_fs_mode_sense(sc); break; case SC_PREVENT_ALLOW_MEDIUM_REMOVAL: error = ustorage_fs_min_len(sc, 0, -1U); if (error) { break; } error = ustorage_fs_check_cmd(sc, 6, (1UL << 4) | 1, 0); if (error) { break; } error = ustorage_fs_prevent_allow(sc); break; case SC_READ_6: i = sc->sc_cbw->CBWCDB[4]; sc->sc_transfer.cmd_dir = DIR_WRITE; temp = ((i == 0) ? 256UL : i); error = ustorage_fs_min_len(sc, temp << 9, mask9); if (error) { break; } error = ustorage_fs_check_cmd(sc, 6, (7UL << 1) | (1UL << 4) | 1, 1); if (error) { break; } error = ustorage_fs_read(sc); break; case SC_READ_10: sc->sc_transfer.cmd_dir = DIR_WRITE; temp = get_be16(&sc->sc_cbw->CBWCDB[7]); error = ustorage_fs_min_len(sc, temp << 9, mask9); if (error) { break; } error = ustorage_fs_check_cmd(sc, 10, (1UL << 1) | (0xfUL << 2) | (3UL << 7) | 1, 1); if (error) { break; } error = ustorage_fs_read(sc); break; case SC_READ_12: sc->sc_transfer.cmd_dir = DIR_WRITE; temp = get_be32(&sc->sc_cbw->CBWCDB[6]); if (temp >= (1UL << (32 - 9))) { /* numerical overflow */ sc->sc_csw->bCSWStatus = CSWSTATUS_FAILED; error = 1; break; } error = ustorage_fs_min_len(sc, temp << 9, mask9); if (error) { break; } error = ustorage_fs_check_cmd(sc, 12, (1UL << 1) | (0xfUL << 2) | (0xfUL << 6) | 1, 1); if (error) { break; } error = ustorage_fs_read(sc); break; case SC_READ_CAPACITY: sc->sc_transfer.cmd_dir = DIR_WRITE; error = ustorage_fs_check_cmd(sc, 10, (0xfUL << 2) | (1UL << 8) | 1, 1); if (error) { break; } error = ustorage_fs_read_capacity(sc); break; case SC_READ_FORMAT_CAPACITIES: sc->sc_transfer.cmd_dir = DIR_WRITE; error = ustorage_fs_min_len(sc, get_be16(&sc->sc_cbw->CBWCDB[7]), -1U); if (error) { break; } error = ustorage_fs_check_cmd(sc, 10, (3UL << 7) | 1, 1); if (error) { break; } error = ustorage_fs_read_format_capacities(sc); break; case SC_REQUEST_SENSE: sc->sc_transfer.cmd_dir = DIR_WRITE; error = ustorage_fs_min_len(sc, sc->sc_cbw->CBWCDB[4], -1U); if (error) { break; } error = ustorage_fs_check_cmd(sc, 6, (1UL << 4) | 1, 0); if (error) { break; } error = ustorage_fs_request_sense(sc); break; case SC_START_STOP_UNIT: error = ustorage_fs_min_len(sc, 0, -1U); if (error) { break; } error = ustorage_fs_check_cmd(sc, 6, (1UL << 1) | (1UL << 4) | 1, 0); if (error) { break; } error = ustorage_fs_start_stop(sc); break; case SC_SYNCHRONIZE_CACHE: error = ustorage_fs_min_len(sc, 0, -1U); if (error) { break; } error = ustorage_fs_check_cmd(sc, 10, (0xfUL << 2) | (3UL << 7) | 1, 1); if (error) { break; } error = ustorage_fs_synchronize_cache(sc); break; case SC_TEST_UNIT_READY: error = ustorage_fs_min_len(sc, 0, -1U); if (error) { break; } error = ustorage_fs_check_cmd(sc, 6, 0 | 1, 1); break; /* * Although optional, this command is used by MS-Windows. * We support a minimal version: BytChk must be 0. */ case SC_VERIFY: error = ustorage_fs_min_len(sc, 0, -1U); if (error) { break; } error = ustorage_fs_check_cmd(sc, 10, (1UL << 1) | (0xfUL << 2) | (3UL << 7) | 1, 1); if (error) { break; } error = ustorage_fs_verify(sc); break; case SC_WRITE_6: i = sc->sc_cbw->CBWCDB[4]; sc->sc_transfer.cmd_dir = DIR_READ; temp = ((i == 0) ? 256UL : i); error = ustorage_fs_min_len(sc, temp << 9, mask9); if (error) { break; } error = ustorage_fs_check_cmd(sc, 6, (7UL << 1) | (1UL << 4) | 1, 1); if (error) { break; } error = ustorage_fs_write(sc); break; case SC_WRITE_10: sc->sc_transfer.cmd_dir = DIR_READ; temp = get_be16(&sc->sc_cbw->CBWCDB[7]); error = ustorage_fs_min_len(sc, temp << 9, mask9); if (error) { break; } error = ustorage_fs_check_cmd(sc, 10, (1UL << 1) | (0xfUL << 2) | (3UL << 7) | 1, 1); if (error) { break; } error = ustorage_fs_write(sc); break; case SC_WRITE_12: sc->sc_transfer.cmd_dir = DIR_READ; temp = get_be32(&sc->sc_cbw->CBWCDB[6]); if (temp > (mask9 >> 9)) { /* numerical overflow */ sc->sc_csw->bCSWStatus = CSWSTATUS_FAILED; error = 1; break; } error = ustorage_fs_min_len(sc, temp << 9, mask9); if (error) { break; } error = ustorage_fs_check_cmd(sc, 12, (1UL << 1) | (0xfUL << 2) | (0xfUL << 6) | 1, 1); if (error) { break; } error = ustorage_fs_write(sc); break; /* * Some mandatory commands that we recognize but don't * implement. They don't mean much in this setting. * It's left as an exercise for anyone interested to * implement RESERVE and RELEASE in terms of Posix * locks. */ case SC_FORMAT_UNIT: case SC_RELEASE: case SC_RESERVE: case SC_SEND_DIAGNOSTIC: /* Fallthrough */ default: error = ustorage_fs_min_len(sc, 0, -1U); if (error) { break; } error = ustorage_fs_check_cmd(sc, sc->sc_transfer.cmd_len, 0xff, 0); if (error) { break; } sc->sc_transfer.currlun->sense_data = SS_INVALID_COMMAND; error = 1; break; } return (error); } Index: head/sys/dev/usb/usb_hub.c =================================================================== --- head/sys/dev/usb/usb_hub.c (revision 276700) +++ head/sys/dev/usb/usb_hub.c (revision 276701) @@ -1,2914 +1,2914 @@ /* $FreeBSD$ */ /*- * Copyright (c) 1998 The NetBSD Foundation, Inc. All rights reserved. * Copyright (c) 1998 Lennart Augustsson. All rights reserved. * Copyright (c) 2008-2010 Hans Petter Selasky. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * USB spec: http://www.usb.org/developers/docs/usbspec.zip */ #ifdef USB_GLOBAL_INCLUDE_FILE #include USB_GLOBAL_INCLUDE_FILE #else #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define USB_DEBUG_VAR uhub_debug #include #include #include #include #include #include #include #include #include #include #include #include #endif /* USB_GLOBAL_INCLUDE_FILE */ #define UHUB_INTR_INTERVAL 250 /* ms */ enum { UHUB_INTR_TRANSFER, #if USB_HAVE_TT_SUPPORT UHUB_RESET_TT_TRANSFER, #endif UHUB_N_TRANSFER, }; #ifdef USB_DEBUG static int uhub_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, uhub, CTLFLAG_RW, 0, "USB HUB"); SYSCTL_INT(_hw_usb_uhub, OID_AUTO, debug, CTLFLAG_RWTUN, &uhub_debug, 0, "Debug level"); #endif #if USB_HAVE_POWERD static int usb_power_timeout = 30; /* seconds */ -SYSCTL_INT(_hw_usb, OID_AUTO, power_timeout, CTLFLAG_RW, +SYSCTL_INT(_hw_usb, OID_AUTO, power_timeout, CTLFLAG_RWTUN, &usb_power_timeout, 0, "USB power timeout"); #endif #if USB_HAVE_DISABLE_ENUM static int usb_disable_enumeration = 0; SYSCTL_INT(_hw_usb, OID_AUTO, disable_enumeration, CTLFLAG_RWTUN, &usb_disable_enumeration, 0, "Set to disable all USB device enumeration."); static int usb_disable_port_power = 0; SYSCTL_INT(_hw_usb, OID_AUTO, disable_port_power, CTLFLAG_RWTUN, &usb_disable_port_power, 0, "Set to disable all USB port power."); #endif struct uhub_current_state { uint16_t port_change; uint16_t port_status; }; struct uhub_softc { struct uhub_current_state sc_st;/* current state */ #if (USB_HAVE_FIXED_PORT != 0) struct usb_hub sc_hub; #endif device_t sc_dev; /* base device */ struct mtx sc_mtx; /* our mutex */ struct usb_device *sc_udev; /* USB device */ struct usb_xfer *sc_xfer[UHUB_N_TRANSFER]; /* interrupt xfer */ #if USB_HAVE_DISABLE_ENUM int sc_disable_enumeration; int sc_disable_port_power; #endif uint8_t sc_flags; #define UHUB_FLAG_DID_EXPLORE 0x01 }; #define UHUB_PROTO(sc) ((sc)->sc_udev->ddesc.bDeviceProtocol) #define UHUB_IS_HIGH_SPEED(sc) (UHUB_PROTO(sc) != UDPROTO_FSHUB) #define UHUB_IS_SINGLE_TT(sc) (UHUB_PROTO(sc) == UDPROTO_HSHUBSTT) #define UHUB_IS_MULTI_TT(sc) (UHUB_PROTO(sc) == UDPROTO_HSHUBMTT) #define UHUB_IS_SUPER_SPEED(sc) (UHUB_PROTO(sc) == UDPROTO_SSHUB) /* prototypes for type checking: */ static device_probe_t uhub_probe; static device_attach_t uhub_attach; static device_detach_t uhub_detach; static device_suspend_t uhub_suspend; static device_resume_t uhub_resume; static bus_driver_added_t uhub_driver_added; static bus_child_location_str_t uhub_child_location_string; static bus_child_pnpinfo_str_t uhub_child_pnpinfo_string; static usb_callback_t uhub_intr_callback; #if USB_HAVE_TT_SUPPORT static usb_callback_t uhub_reset_tt_callback; #endif static void usb_dev_resume_peer(struct usb_device *udev); static void usb_dev_suspend_peer(struct usb_device *udev); static uint8_t usb_peer_should_wakeup(struct usb_device *udev); static const struct usb_config uhub_config[UHUB_N_TRANSFER] = { [UHUB_INTR_TRANSFER] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_ANY, .timeout = 0, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .bufsize = 0, /* use wMaxPacketSize */ .callback = &uhub_intr_callback, .interval = UHUB_INTR_INTERVAL, }, #if USB_HAVE_TT_SUPPORT [UHUB_RESET_TT_TRANSFER] = { .type = UE_CONTROL, .endpoint = 0x00, /* Control pipe */ .direction = UE_DIR_ANY, .bufsize = sizeof(struct usb_device_request), .callback = &uhub_reset_tt_callback, .timeout = 1000, /* 1 second */ .usb_mode = USB_MODE_HOST, }, #endif }; /* * driver instance for "hub" connected to "usb" * and "hub" connected to "hub" */ static devclass_t uhub_devclass; static device_method_t uhub_methods[] = { DEVMETHOD(device_probe, uhub_probe), DEVMETHOD(device_attach, uhub_attach), DEVMETHOD(device_detach, uhub_detach), DEVMETHOD(device_suspend, uhub_suspend), DEVMETHOD(device_resume, uhub_resume), DEVMETHOD(bus_child_location_str, uhub_child_location_string), DEVMETHOD(bus_child_pnpinfo_str, uhub_child_pnpinfo_string), DEVMETHOD(bus_driver_added, uhub_driver_added), DEVMETHOD_END }; static driver_t uhub_driver = { .name = "uhub", .methods = uhub_methods, .size = sizeof(struct uhub_softc) }; DRIVER_MODULE(uhub, usbus, uhub_driver, uhub_devclass, 0, 0); DRIVER_MODULE(uhub, uhub, uhub_driver, uhub_devclass, NULL, 0); MODULE_VERSION(uhub, 1); static void uhub_intr_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhub_softc *sc = usbd_xfer_softc(xfer); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(2, "\n"); /* * This is an indication that some port * has changed status. Notify the bus * event handler thread that we need * to be explored again: */ usb_needs_explore(sc->sc_udev->bus, 0); case USB_ST_SETUP: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: /* Error */ if (xfer->error != USB_ERR_CANCELLED) { /* * Do a clear-stall. The "stall_pipe" flag * will get cleared before next callback by * the USB stack. */ usbd_xfer_set_stall(xfer); usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); } break; } } /*------------------------------------------------------------------------* * uhub_reset_tt_proc * * This function starts the TT reset USB request *------------------------------------------------------------------------*/ #if USB_HAVE_TT_SUPPORT static void uhub_reset_tt_proc(struct usb_proc_msg *_pm) { struct usb_udev_msg *pm = (void *)_pm; struct usb_device *udev = pm->udev; struct usb_hub *hub; struct uhub_softc *sc; hub = udev->hub; if (hub == NULL) return; sc = hub->hubsoftc; if (sc == NULL) return; /* Change lock */ USB_BUS_UNLOCK(udev->bus); mtx_lock(&sc->sc_mtx); /* Start transfer */ usbd_transfer_start(sc->sc_xfer[UHUB_RESET_TT_TRANSFER]); /* Change lock */ mtx_unlock(&sc->sc_mtx); USB_BUS_LOCK(udev->bus); } #endif /*------------------------------------------------------------------------* * uhub_tt_buffer_reset_async_locked * * This function queues a TT reset for the given USB device and endpoint. *------------------------------------------------------------------------*/ #if USB_HAVE_TT_SUPPORT void uhub_tt_buffer_reset_async_locked(struct usb_device *child, struct usb_endpoint *ep) { struct usb_device_request req; struct usb_device *udev; struct usb_hub *hub; struct usb_port *up; uint16_t wValue; uint8_t port; if (child == NULL || ep == NULL) return; udev = child->parent_hs_hub; port = child->hs_port_no; if (udev == NULL) return; hub = udev->hub; if ((hub == NULL) || (udev->speed != USB_SPEED_HIGH) || (child->speed != USB_SPEED_LOW && child->speed != USB_SPEED_FULL) || (child->flags.usb_mode != USB_MODE_HOST) || (port == 0) || (ep->edesc == NULL)) { /* not applicable */ return; } USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED); up = hub->ports + port - 1; if (udev->ddesc.bDeviceClass == UDCLASS_HUB && udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBSTT) port = 1; /* if we already received a clear buffer request, reset the whole TT */ if (up->req_reset_tt.bRequest != 0) { req.bmRequestType = UT_WRITE_CLASS_OTHER; req.bRequest = UR_RESET_TT; USETW(req.wValue, 0); req.wIndex[0] = port; req.wIndex[1] = 0; USETW(req.wLength, 0); } else { wValue = (ep->edesc->bEndpointAddress & 0xF) | ((child->address & 0x7F) << 4) | ((ep->edesc->bEndpointAddress & 0x80) << 8) | ((ep->edesc->bmAttributes & 3) << 12); req.bmRequestType = UT_WRITE_CLASS_OTHER; req.bRequest = UR_CLEAR_TT_BUFFER; USETW(req.wValue, wValue); req.wIndex[0] = port; req.wIndex[1] = 0; USETW(req.wLength, 0); } up->req_reset_tt = req; /* get reset transfer started */ usb_proc_msignal(USB_BUS_NON_GIANT_PROC(udev->bus), &hub->tt_msg[0], &hub->tt_msg[1]); } #endif #if USB_HAVE_TT_SUPPORT static void uhub_reset_tt_callback(struct usb_xfer *xfer, usb_error_t error) { struct uhub_softc *sc; struct usb_device *udev; struct usb_port *up; uint8_t x; DPRINTF("TT buffer reset\n"); sc = usbd_xfer_softc(xfer); udev = sc->sc_udev; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: case USB_ST_SETUP: tr_setup: USB_BUS_LOCK(udev->bus); /* find first port which needs a TT reset */ for (x = 0; x != udev->hub->nports; x++) { up = udev->hub->ports + x; if (up->req_reset_tt.bRequest == 0) continue; /* copy in the transfer */ usbd_copy_in(xfer->frbuffers, 0, &up->req_reset_tt, sizeof(up->req_reset_tt)); /* reset buffer */ memset(&up->req_reset_tt, 0, sizeof(up->req_reset_tt)); /* set length */ usbd_xfer_set_frame_len(xfer, 0, sizeof(up->req_reset_tt)); xfer->nframes = 1; USB_BUS_UNLOCK(udev->bus); usbd_transfer_submit(xfer); return; } USB_BUS_UNLOCK(udev->bus); break; default: if (error == USB_ERR_CANCELLED) break; DPRINTF("TT buffer reset failed (%s)\n", usbd_errstr(error)); goto tr_setup; } } #endif /*------------------------------------------------------------------------* * uhub_count_active_host_ports * * This function counts the number of active ports at the given speed. *------------------------------------------------------------------------*/ uint8_t uhub_count_active_host_ports(struct usb_device *udev, enum usb_dev_speed speed) { struct uhub_softc *sc; struct usb_device *child; struct usb_hub *hub; struct usb_port *up; uint8_t retval = 0; uint8_t x; if (udev == NULL) goto done; hub = udev->hub; if (hub == NULL) goto done; sc = hub->hubsoftc; if (sc == NULL) goto done; for (x = 0; x != hub->nports; x++) { up = hub->ports + x; child = usb_bus_port_get_device(udev->bus, up); if (child != NULL && child->flags.usb_mode == USB_MODE_HOST && child->speed == speed) retval++; } done: return (retval); } void uhub_explore_handle_re_enumerate(struct usb_device *child) { uint8_t do_unlock; usb_error_t err; /* check if device should be re-enumerated */ if (child->flags.usb_mode != USB_MODE_HOST) return; do_unlock = usbd_enum_lock(child); switch (child->re_enumerate_wait) { case USB_RE_ENUM_START: err = usbd_set_config_index(child, USB_UNCONFIG_INDEX); if (err != 0) { DPRINTF("Unconfigure failed: %s: Ignored.\n", usbd_errstr(err)); } if (child->parent_hub == NULL) { /* the root HUB cannot be re-enumerated */ DPRINTFN(6, "cannot reset root HUB\n"); err = 0; } else { err = usbd_req_re_enumerate(child, NULL); } if (err == 0) err = usbd_set_config_index(child, 0); if (err == 0) { err = usb_probe_and_attach(child, USB_IFACE_INDEX_ANY); } child->re_enumerate_wait = USB_RE_ENUM_DONE; break; case USB_RE_ENUM_PWR_OFF: /* get the device unconfigured */ err = usbd_set_config_index(child, USB_UNCONFIG_INDEX); if (err) { DPRINTFN(0, "Could not unconfigure " "device (ignored)\n"); } if (child->parent_hub == NULL) { /* the root HUB cannot be re-enumerated */ DPRINTFN(6, "cannot set port feature\n"); err = 0; } else { /* clear port enable */ err = usbd_req_clear_port_feature(child->parent_hub, NULL, child->port_no, UHF_PORT_ENABLE); if (err) { DPRINTFN(0, "Could not disable port " "(ignored)\n"); } } child->re_enumerate_wait = USB_RE_ENUM_DONE; break; case USB_RE_ENUM_SET_CONFIG: err = usbd_set_config_index(child, child->next_config_index); if (err != 0) { DPRINTF("Configure failed: %s: Ignored.\n", usbd_errstr(err)); } else { err = usb_probe_and_attach(child, USB_IFACE_INDEX_ANY); } child->re_enumerate_wait = USB_RE_ENUM_DONE; break; default: child->re_enumerate_wait = USB_RE_ENUM_DONE; break; } if (do_unlock) usbd_enum_unlock(child); } /*------------------------------------------------------------------------* * uhub_explore_sub - subroutine * * Return values: * 0: Success * Else: A control transaction failed *------------------------------------------------------------------------*/ static usb_error_t uhub_explore_sub(struct uhub_softc *sc, struct usb_port *up) { struct usb_bus *bus; struct usb_device *child; uint8_t refcount; usb_error_t err; bus = sc->sc_udev->bus; err = 0; /* get driver added refcount from USB bus */ refcount = bus->driver_added_refcount; /* get device assosiated with the given port */ child = usb_bus_port_get_device(bus, up); if (child == NULL) { /* nothing to do */ goto done; } uhub_explore_handle_re_enumerate(child); /* check if probe and attach should be done */ if (child->driver_added_refcount != refcount) { child->driver_added_refcount = refcount; err = usb_probe_and_attach(child, USB_IFACE_INDEX_ANY); if (err) { goto done; } } /* start control transfer, if device mode */ if (child->flags.usb_mode == USB_MODE_DEVICE) usbd_ctrl_transfer_setup(child); /* if a HUB becomes present, do a recursive HUB explore */ if (child->hub) err = (child->hub->explore) (child); done: return (err); } /*------------------------------------------------------------------------* * uhub_read_port_status - factored out code *------------------------------------------------------------------------*/ static usb_error_t uhub_read_port_status(struct uhub_softc *sc, uint8_t portno) { struct usb_port_status ps; usb_error_t err; err = usbd_req_get_port_status( sc->sc_udev, NULL, &ps, portno); /* update status regardless of error */ sc->sc_st.port_status = UGETW(ps.wPortStatus); sc->sc_st.port_change = UGETW(ps.wPortChange); /* debugging print */ DPRINTFN(4, "port %d, wPortStatus=0x%04x, " "wPortChange=0x%04x, err=%s\n", portno, sc->sc_st.port_status, sc->sc_st.port_change, usbd_errstr(err)); return (err); } /*------------------------------------------------------------------------* * uhub_reattach_port * * Returns: * 0: Success * Else: A control transaction failed *------------------------------------------------------------------------*/ static usb_error_t uhub_reattach_port(struct uhub_softc *sc, uint8_t portno) { struct usb_device *child; struct usb_device *udev; enum usb_dev_speed speed; enum usb_hc_mode mode; usb_error_t err; uint16_t power_mask; uint8_t timeout; DPRINTF("reattaching port %d\n", portno); timeout = 0; udev = sc->sc_udev; child = usb_bus_port_get_device(udev->bus, udev->hub->ports + portno - 1); repeat: /* first clear the port connection change bit */ err = usbd_req_clear_port_feature(udev, NULL, portno, UHF_C_PORT_CONNECTION); if (err) goto error; /* check if there is a child */ if (child != NULL) { /* * Free USB device and all subdevices, if any. */ usb_free_device(child, 0); child = NULL; } /* get fresh status */ err = uhub_read_port_status(sc, portno); if (err) goto error; #if USB_HAVE_DISABLE_ENUM /* check if we should skip enumeration from this USB HUB */ if (usb_disable_enumeration != 0 || sc->sc_disable_enumeration != 0) { DPRINTF("Enumeration is disabled!\n"); goto error; } #endif /* check if nothing is connected to the port */ if (!(sc->sc_st.port_status & UPS_CURRENT_CONNECT_STATUS)) goto error; /* check if there is no power on the port and print a warning */ switch (udev->speed) { case USB_SPEED_HIGH: case USB_SPEED_FULL: case USB_SPEED_LOW: power_mask = UPS_PORT_POWER; break; case USB_SPEED_SUPER: if (udev->parent_hub == NULL) power_mask = UPS_PORT_POWER; else power_mask = UPS_PORT_POWER_SS; break; default: power_mask = 0; break; } if (!(sc->sc_st.port_status & power_mask)) { DPRINTF("WARNING: strange, connected port %d " "has no power\n", portno); } /* check if the device is in Host Mode */ if (!(sc->sc_st.port_status & UPS_PORT_MODE_DEVICE)) { DPRINTF("Port %d is in Host Mode\n", portno); if (sc->sc_st.port_status & UPS_SUSPEND) { /* * NOTE: Should not get here in SuperSpeed * mode, because the HUB should report this * bit as zero. */ DPRINTF("Port %d was still " "suspended, clearing.\n", portno); err = usbd_req_clear_port_feature(udev, NULL, portno, UHF_PORT_SUSPEND); } /* USB Host Mode */ /* wait for maximum device power up time */ usb_pause_mtx(NULL, USB_MS_TO_TICKS(usb_port_powerup_delay)); /* reset port, which implies enabling it */ err = usbd_req_reset_port(udev, NULL, portno); if (err) { DPRINTFN(0, "port %d reset " "failed, error=%s\n", portno, usbd_errstr(err)); goto error; } /* get port status again, it might have changed during reset */ err = uhub_read_port_status(sc, portno); if (err) { goto error; } /* check if something changed during port reset */ if ((sc->sc_st.port_change & UPS_C_CONNECT_STATUS) || (!(sc->sc_st.port_status & UPS_CURRENT_CONNECT_STATUS))) { if (timeout) { DPRINTFN(0, "giving up port reset " "- device vanished\n"); goto error; } timeout = 1; goto repeat; } } else { DPRINTF("Port %d is in Device Mode\n", portno); } /* * Figure out the device speed */ switch (udev->speed) { case USB_SPEED_HIGH: if (sc->sc_st.port_status & UPS_HIGH_SPEED) speed = USB_SPEED_HIGH; else if (sc->sc_st.port_status & UPS_LOW_SPEED) speed = USB_SPEED_LOW; else speed = USB_SPEED_FULL; break; case USB_SPEED_FULL: if (sc->sc_st.port_status & UPS_LOW_SPEED) speed = USB_SPEED_LOW; else speed = USB_SPEED_FULL; break; case USB_SPEED_LOW: speed = USB_SPEED_LOW; break; case USB_SPEED_SUPER: if (udev->parent_hub == NULL) { /* Root HUB - special case */ switch (sc->sc_st.port_status & UPS_OTHER_SPEED) { case 0: speed = USB_SPEED_FULL; break; case UPS_LOW_SPEED: speed = USB_SPEED_LOW; break; case UPS_HIGH_SPEED: speed = USB_SPEED_HIGH; break; default: speed = USB_SPEED_SUPER; break; } } else { speed = USB_SPEED_SUPER; } break; default: /* same speed like parent */ speed = udev->speed; break; } if (speed == USB_SPEED_SUPER) { err = usbd_req_set_hub_u1_timeout(udev, NULL, portno, 128 - (2 * udev->depth)); if (err) { DPRINTFN(0, "port %d U1 timeout " "failed, error=%s\n", portno, usbd_errstr(err)); } err = usbd_req_set_hub_u2_timeout(udev, NULL, portno, 128 - (2 * udev->depth)); if (err) { DPRINTFN(0, "port %d U2 timeout " "failed, error=%s\n", portno, usbd_errstr(err)); } } /* * Figure out the device mode * * NOTE: This part is currently FreeBSD specific. */ if (udev->parent_hub != NULL) { /* inherit mode from the parent HUB */ mode = udev->parent_hub->flags.usb_mode; } else if (sc->sc_st.port_status & UPS_PORT_MODE_DEVICE) mode = USB_MODE_DEVICE; else mode = USB_MODE_HOST; /* need to create a new child */ child = usb_alloc_device(sc->sc_dev, udev->bus, udev, udev->depth + 1, portno - 1, portno, speed, mode); if (child == NULL) { DPRINTFN(0, "could not allocate new device\n"); goto error; } return (0); /* success */ error: if (child != NULL) { /* * Free USB device and all subdevices, if any. */ usb_free_device(child, 0); child = NULL; } if (err == 0) { if (sc->sc_st.port_status & UPS_PORT_ENABLED) { err = usbd_req_clear_port_feature( sc->sc_udev, NULL, portno, UHF_PORT_ENABLE); } } if (err) { DPRINTFN(0, "device problem (%s), " "disabling port %d\n", usbd_errstr(err), portno); } return (err); } /*------------------------------------------------------------------------* * usb_device_20_compatible * * Returns: * 0: HUB does not support suspend and resume * Else: HUB supports suspend and resume *------------------------------------------------------------------------*/ static uint8_t usb_device_20_compatible(struct usb_device *udev) { if (udev == NULL) return (0); switch (udev->speed) { case USB_SPEED_LOW: case USB_SPEED_FULL: case USB_SPEED_HIGH: return (1); default: return (0); } } /*------------------------------------------------------------------------* * uhub_suspend_resume_port * * Returns: * 0: Success * Else: A control transaction failed *------------------------------------------------------------------------*/ static usb_error_t uhub_suspend_resume_port(struct uhub_softc *sc, uint8_t portno) { struct usb_device *child; struct usb_device *udev; uint8_t is_suspend; usb_error_t err; DPRINTF("port %d\n", portno); udev = sc->sc_udev; child = usb_bus_port_get_device(udev->bus, udev->hub->ports + portno - 1); /* first clear the port suspend change bit */ if (usb_device_20_compatible(udev)) { err = usbd_req_clear_port_feature(udev, NULL, portno, UHF_C_PORT_SUSPEND); } else { err = usbd_req_clear_port_feature(udev, NULL, portno, UHF_C_PORT_LINK_STATE); } if (err) { DPRINTF("clearing suspend failed.\n"); goto done; } /* get fresh status */ err = uhub_read_port_status(sc, portno); if (err) { DPRINTF("reading port status failed.\n"); goto done; } /* convert current state */ if (usb_device_20_compatible(udev)) { if (sc->sc_st.port_status & UPS_SUSPEND) { is_suspend = 1; } else { is_suspend = 0; } } else { switch (UPS_PORT_LINK_STATE_GET(sc->sc_st.port_status)) { case UPS_PORT_LS_U3: is_suspend = 1; break; case UPS_PORT_LS_SS_INA: usbd_req_warm_reset_port(udev, NULL, portno); is_suspend = 0; break; default: is_suspend = 0; break; } } DPRINTF("suspended=%u\n", is_suspend); /* do the suspend or resume */ if (child) { /* * This code handle two cases: 1) Host Mode - we can only * receive resume here 2) Device Mode - we can receive * suspend and resume here */ if (is_suspend == 0) usb_dev_resume_peer(child); else if (child->flags.usb_mode == USB_MODE_DEVICE) usb_dev_suspend_peer(child); } done: return (err); } /*------------------------------------------------------------------------* * uhub_root_interrupt * * This function is called when a Root HUB interrupt has * happened. "ptr" and "len" makes up the Root HUB interrupt * packet. This function is called having the "bus_mtx" locked. *------------------------------------------------------------------------*/ void uhub_root_intr(struct usb_bus *bus, const uint8_t *ptr, uint8_t len) { USB_BUS_LOCK_ASSERT(bus, MA_OWNED); usb_needs_explore(bus, 0); } static uint8_t uhub_is_too_deep(struct usb_device *udev) { switch (udev->speed) { case USB_SPEED_FULL: case USB_SPEED_LOW: case USB_SPEED_HIGH: if (udev->depth > USB_HUB_MAX_DEPTH) return (1); break; case USB_SPEED_SUPER: if (udev->depth > USB_SS_HUB_DEPTH_MAX) return (1); break; default: break; } return (0); } /*------------------------------------------------------------------------* * uhub_explore * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ static usb_error_t uhub_explore(struct usb_device *udev) { struct usb_hub *hub; struct uhub_softc *sc; struct usb_port *up; usb_error_t err; uint8_t portno; uint8_t x; uint8_t do_unlock; hub = udev->hub; sc = hub->hubsoftc; DPRINTFN(11, "udev=%p addr=%d\n", udev, udev->address); /* ignore devices that are too deep */ if (uhub_is_too_deep(udev)) return (USB_ERR_TOO_DEEP); /* check if device is suspended */ if (udev->flags.self_suspended) { /* need to wait until the child signals resume */ DPRINTF("Device is suspended!\n"); return (0); } /* * Make sure we don't race against user-space applications * like LibUSB: */ do_unlock = usbd_enum_lock(udev); for (x = 0; x != hub->nports; x++) { up = hub->ports + x; portno = x + 1; err = uhub_read_port_status(sc, portno); if (err) { /* most likely the HUB is gone */ break; } if (sc->sc_st.port_change & UPS_C_OVERCURRENT_INDICATOR) { DPRINTF("Overcurrent on port %u.\n", portno); err = usbd_req_clear_port_feature( udev, NULL, portno, UHF_C_PORT_OVER_CURRENT); if (err) { /* most likely the HUB is gone */ break; } } if (!(sc->sc_flags & UHUB_FLAG_DID_EXPLORE)) { /* * Fake a connect status change so that the * status gets checked initially! */ sc->sc_st.port_change |= UPS_C_CONNECT_STATUS; } if (sc->sc_st.port_change & UPS_C_PORT_ENABLED) { err = usbd_req_clear_port_feature( udev, NULL, portno, UHF_C_PORT_ENABLE); if (err) { /* most likely the HUB is gone */ break; } if (sc->sc_st.port_change & UPS_C_CONNECT_STATUS) { /* * Ignore the port error if the device * has vanished ! */ } else if (sc->sc_st.port_status & UPS_PORT_ENABLED) { DPRINTFN(0, "illegal enable change, " "port %d\n", portno); } else { if (up->restartcnt == USB_RESTART_MAX) { /* XXX could try another speed ? */ DPRINTFN(0, "port error, giving up " "port %d\n", portno); } else { sc->sc_st.port_change |= UPS_C_CONNECT_STATUS; up->restartcnt++; } } } if (sc->sc_st.port_change & UPS_C_CONNECT_STATUS) { err = uhub_reattach_port(sc, portno); if (err) { /* most likely the HUB is gone */ break; } } if (sc->sc_st.port_change & (UPS_C_SUSPEND | UPS_C_PORT_LINK_STATE)) { err = uhub_suspend_resume_port(sc, portno); if (err) { /* most likely the HUB is gone */ break; } } err = uhub_explore_sub(sc, up); if (err) { /* no device(s) present */ continue; } /* explore succeeded - reset restart counter */ up->restartcnt = 0; } if (do_unlock) usbd_enum_unlock(udev); /* initial status checked */ sc->sc_flags |= UHUB_FLAG_DID_EXPLORE; /* return success */ return (USB_ERR_NORMAL_COMPLETION); } static int uhub_probe(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); /* * The subclass for USB HUBs is currently ignored because it * is 0 for some and 1 for others. */ if (uaa->info.bConfigIndex == 0 && uaa->info.bDeviceClass == UDCLASS_HUB) return (0); return (ENXIO); } /* NOTE: The information returned by this function can be wrong. */ usb_error_t uhub_query_info(struct usb_device *udev, uint8_t *pnports, uint8_t *ptt) { struct usb_hub_descriptor hubdesc20; struct usb_hub_ss_descriptor hubdesc30; usb_error_t err; uint8_t nports; uint8_t tt; if (udev->ddesc.bDeviceClass != UDCLASS_HUB) return (USB_ERR_INVAL); nports = 0; tt = 0; switch (udev->speed) { case USB_SPEED_LOW: case USB_SPEED_FULL: case USB_SPEED_HIGH: /* assuming that there is one port */ err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, 1); if (err) { DPRINTFN(0, "getting USB 2.0 HUB descriptor failed," "error=%s\n", usbd_errstr(err)); break; } nports = hubdesc20.bNbrPorts; if (nports > 127) nports = 127; if (udev->speed == USB_SPEED_HIGH) tt = (UGETW(hubdesc20.wHubCharacteristics) >> 5) & 3; break; case USB_SPEED_SUPER: err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, 1); if (err) { DPRINTFN(0, "Getting USB 3.0 HUB descriptor failed," "error=%s\n", usbd_errstr(err)); break; } nports = hubdesc30.bNbrPorts; if (nports > 16) nports = 16; break; default: err = USB_ERR_INVAL; break; } if (pnports != NULL) *pnports = nports; if (ptt != NULL) *ptt = tt; return (err); } static int uhub_attach(device_t dev) { struct uhub_softc *sc = device_get_softc(dev); struct usb_attach_arg *uaa = device_get_ivars(dev); struct usb_device *udev = uaa->device; struct usb_device *parent_hub = udev->parent_hub; struct usb_hub *hub; struct usb_hub_descriptor hubdesc20; struct usb_hub_ss_descriptor hubdesc30; #if USB_HAVE_DISABLE_ENUM struct sysctl_ctx_list *sysctl_ctx; struct sysctl_oid *sysctl_tree; #endif uint16_t pwrdly; uint16_t nports; uint8_t x; uint8_t portno; uint8_t removable; uint8_t iface_index; usb_error_t err; sc->sc_udev = udev; sc->sc_dev = dev; mtx_init(&sc->sc_mtx, "USB HUB mutex", NULL, MTX_DEF); device_set_usb_desc(dev); DPRINTFN(2, "depth=%d selfpowered=%d, parent=%p, " "parent->selfpowered=%d\n", udev->depth, udev->flags.self_powered, parent_hub, parent_hub ? parent_hub->flags.self_powered : 0); if (uhub_is_too_deep(udev)) { DPRINTFN(0, "HUB at depth %d, " "exceeds maximum. HUB ignored\n", (int)udev->depth); goto error; } if (!udev->flags.self_powered && parent_hub && !parent_hub->flags.self_powered) { DPRINTFN(0, "Bus powered HUB connected to " "bus powered HUB. HUB ignored\n"); goto error; } if (UHUB_IS_MULTI_TT(sc)) { err = usbd_set_alt_interface_index(udev, 0, 1); if (err) { device_printf(dev, "MTT could not be enabled\n"); goto error; } device_printf(dev, "MTT enabled\n"); } /* get HUB descriptor */ DPRINTFN(2, "Getting HUB descriptor\n"); switch (udev->speed) { case USB_SPEED_LOW: case USB_SPEED_FULL: case USB_SPEED_HIGH: /* assuming that there is one port */ err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, 1); if (err) { DPRINTFN(0, "getting USB 2.0 HUB descriptor failed," "error=%s\n", usbd_errstr(err)); goto error; } /* get number of ports */ nports = hubdesc20.bNbrPorts; /* get power delay */ pwrdly = ((hubdesc20.bPwrOn2PwrGood * UHD_PWRON_FACTOR) + usb_extra_power_up_time); /* get complete HUB descriptor */ if (nports >= 8) { /* check number of ports */ if (nports > 127) { DPRINTFN(0, "Invalid number of USB 2.0 ports," "error=%s\n", usbd_errstr(err)); goto error; } /* get complete HUB descriptor */ err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, nports); if (err) { DPRINTFN(0, "Getting USB 2.0 HUB descriptor failed," "error=%s\n", usbd_errstr(err)); goto error; } if (hubdesc20.bNbrPorts != nports) { DPRINTFN(0, "Number of ports changed\n"); goto error; } } break; case USB_SPEED_SUPER: if (udev->parent_hub != NULL) { err = usbd_req_set_hub_depth(udev, NULL, udev->depth - 1); if (err) { DPRINTFN(0, "Setting USB 3.0 HUB depth failed," "error=%s\n", usbd_errstr(err)); goto error; } } err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, 1); if (err) { DPRINTFN(0, "Getting USB 3.0 HUB descriptor failed," "error=%s\n", usbd_errstr(err)); goto error; } /* get number of ports */ nports = hubdesc30.bNbrPorts; /* get power delay */ pwrdly = ((hubdesc30.bPwrOn2PwrGood * UHD_PWRON_FACTOR) + usb_extra_power_up_time); /* get complete HUB descriptor */ if (nports >= 8) { /* check number of ports */ if (nports > ((udev->parent_hub != NULL) ? 15 : 127)) { DPRINTFN(0, "Invalid number of USB 3.0 ports," "error=%s\n", usbd_errstr(err)); goto error; } /* get complete HUB descriptor */ err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, nports); if (err) { DPRINTFN(0, "Getting USB 2.0 HUB descriptor failed," "error=%s\n", usbd_errstr(err)); goto error; } if (hubdesc30.bNbrPorts != nports) { DPRINTFN(0, "Number of ports changed\n"); goto error; } } break; default: DPRINTF("Assuming HUB has only one port\n"); /* default number of ports */ nports = 1; /* default power delay */ pwrdly = ((10 * UHD_PWRON_FACTOR) + usb_extra_power_up_time); break; } if (nports == 0) { DPRINTFN(0, "portless HUB\n"); goto error; } if (nports > USB_MAX_PORTS) { DPRINTF("Port limit exceeded\n"); goto error; } #if (USB_HAVE_FIXED_PORT == 0) hub = malloc(sizeof(hub[0]) + (sizeof(hub->ports[0]) * nports), M_USBDEV, M_WAITOK | M_ZERO); if (hub == NULL) goto error; #else hub = &sc->sc_hub; #endif udev->hub = hub; /* initialize HUB structure */ hub->hubsoftc = sc; hub->explore = &uhub_explore; hub->nports = nports; hub->hubudev = udev; #if USB_HAVE_TT_SUPPORT hub->tt_msg[0].hdr.pm_callback = &uhub_reset_tt_proc; hub->tt_msg[0].udev = udev; hub->tt_msg[1].hdr.pm_callback = &uhub_reset_tt_proc; hub->tt_msg[1].udev = udev; #endif /* if self powered hub, give ports maximum current */ if (udev->flags.self_powered) { hub->portpower = USB_MAX_POWER; } else { hub->portpower = USB_MIN_POWER; } /* set up interrupt pipe */ iface_index = 0; if (udev->parent_hub == NULL) { /* root HUB is special */ err = 0; } else { /* normal HUB */ err = usbd_transfer_setup(udev, &iface_index, sc->sc_xfer, uhub_config, UHUB_N_TRANSFER, sc, &sc->sc_mtx); } if (err) { DPRINTFN(0, "cannot setup interrupt transfer, " "errstr=%s\n", usbd_errstr(err)); goto error; } /* wait with power off for a while */ usb_pause_mtx(NULL, USB_MS_TO_TICKS(USB_POWER_DOWN_TIME)); #if USB_HAVE_DISABLE_ENUM /* Add device sysctls */ sysctl_ctx = device_get_sysctl_ctx(dev); sysctl_tree = device_get_sysctl_tree(dev); if (sysctl_ctx != NULL && sysctl_tree != NULL) { (void) SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO, "disable_enumeration", CTLFLAG_RWTUN, &sc->sc_disable_enumeration, 0, "Set to disable enumeration on this USB HUB."); (void) SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree), OID_AUTO, "disable_port_power", CTLFLAG_RWTUN, &sc->sc_disable_port_power, 0, "Set to disable USB port power on this USB HUB."); } #endif /* * To have the best chance of success we do things in the exact same * order as Windoze98. This should not be necessary, but some * devices do not follow the USB specs to the letter. * * These are the events on the bus when a hub is attached: * Get device and config descriptors (see attach code) * Get hub descriptor (see above) * For all ports * turn on power * wait for power to become stable * (all below happens in explore code) * For all ports * clear C_PORT_CONNECTION * For all ports * get port status * if device connected * wait 100 ms * turn on reset * wait * clear C_PORT_RESET * get port status * proceed with device attachment */ /* XXX should check for none, individual, or ganged power? */ removable = 0; for (x = 0; x != nports; x++) { /* set up data structures */ struct usb_port *up = hub->ports + x; up->device_index = 0; up->restartcnt = 0; portno = x + 1; /* check if port is removable */ switch (udev->speed) { case USB_SPEED_LOW: case USB_SPEED_FULL: case USB_SPEED_HIGH: if (!UHD_NOT_REMOV(&hubdesc20, portno)) removable++; break; case USB_SPEED_SUPER: if (!UHD_NOT_REMOV(&hubdesc30, portno)) removable++; break; default: DPRINTF("Assuming removable port\n"); removable++; break; } if (err == 0) { #if USB_HAVE_DISABLE_ENUM /* check if we should disable USB port power or not */ if (usb_disable_port_power != 0 || sc->sc_disable_port_power != 0) { /* turn the power off */ DPRINTFN(2, "Turning port %d power off\n", portno); err = usbd_req_clear_port_feature(udev, NULL, portno, UHF_PORT_POWER); } else { #endif /* turn the power on */ DPRINTFN(2, "Turning port %d power on\n", portno); err = usbd_req_set_port_feature(udev, NULL, portno, UHF_PORT_POWER); #if USB_HAVE_DISABLE_ENUM } #endif } if (err != 0) { DPRINTFN(0, "port %d power on or off failed, %s\n", portno, usbd_errstr(err)); } DPRINTF("turn on port %d power\n", portno); /* wait for stable power */ usb_pause_mtx(NULL, USB_MS_TO_TICKS(pwrdly)); } device_printf(dev, "%d port%s with %d " "removable, %s powered\n", nports, (nports != 1) ? "s" : "", removable, udev->flags.self_powered ? "self" : "bus"); /* Start the interrupt endpoint, if any */ mtx_lock(&sc->sc_mtx); usbd_transfer_start(sc->sc_xfer[UHUB_INTR_TRANSFER]); mtx_unlock(&sc->sc_mtx); /* Enable automatic power save on all USB HUBs */ usbd_set_power_mode(udev, USB_POWER_MODE_SAVE); return (0); error: usbd_transfer_unsetup(sc->sc_xfer, UHUB_N_TRANSFER); #if (USB_HAVE_FIXED_PORT == 0) free(udev->hub, M_USBDEV); #endif udev->hub = NULL; mtx_destroy(&sc->sc_mtx); return (ENXIO); } /* * Called from process context when the hub is gone. * Detach all devices on active ports. */ static int uhub_detach(device_t dev) { struct uhub_softc *sc = device_get_softc(dev); struct usb_hub *hub = sc->sc_udev->hub; struct usb_bus *bus = sc->sc_udev->bus; struct usb_device *child; uint8_t x; if (hub == NULL) /* must be partially working */ return (0); /* Make sure interrupt transfer is gone. */ usbd_transfer_unsetup(sc->sc_xfer, UHUB_N_TRANSFER); /* Detach all ports */ for (x = 0; x != hub->nports; x++) { child = usb_bus_port_get_device(bus, hub->ports + x); if (child == NULL) { continue; } /* * Free USB device and all subdevices, if any. */ usb_free_device(child, 0); } #if USB_HAVE_TT_SUPPORT /* Make sure our TT messages are not queued anywhere */ USB_BUS_LOCK(bus); usb_proc_mwait(USB_BUS_NON_GIANT_PROC(bus), &hub->tt_msg[0], &hub->tt_msg[1]); USB_BUS_UNLOCK(bus); #endif #if (USB_HAVE_FIXED_PORT == 0) free(hub, M_USBDEV); #endif sc->sc_udev->hub = NULL; mtx_destroy(&sc->sc_mtx); return (0); } static int uhub_suspend(device_t dev) { DPRINTF("\n"); /* Sub-devices are not suspended here! */ return (0); } static int uhub_resume(device_t dev) { DPRINTF("\n"); /* Sub-devices are not resumed here! */ return (0); } static void uhub_driver_added(device_t dev, driver_t *driver) { usb_needs_explore_all(); } struct hub_result { struct usb_device *udev; uint8_t portno; uint8_t iface_index; }; static void uhub_find_iface_index(struct usb_hub *hub, device_t child, struct hub_result *res) { struct usb_interface *iface; struct usb_device *udev; uint8_t nports; uint8_t x; uint8_t i; nports = hub->nports; for (x = 0; x != nports; x++) { udev = usb_bus_port_get_device(hub->hubudev->bus, hub->ports + x); if (!udev) { continue; } for (i = 0; i != USB_IFACE_MAX; i++) { iface = usbd_get_iface(udev, i); if (iface && (iface->subdev == child)) { res->iface_index = i; res->udev = udev; res->portno = x + 1; return; } } } res->iface_index = 0; res->udev = NULL; res->portno = 0; } static int uhub_child_location_string(device_t parent, device_t child, char *buf, size_t buflen) { struct uhub_softc *sc; struct usb_hub *hub; struct hub_result res; if (!device_is_attached(parent)) { if (buflen) buf[0] = 0; return (0); } sc = device_get_softc(parent); hub = sc->sc_udev->hub; mtx_lock(&Giant); uhub_find_iface_index(hub, child, &res); if (!res.udev) { DPRINTF("device not on hub\n"); if (buflen) { buf[0] = '\0'; } goto done; } snprintf(buf, buflen, "bus=%u hubaddr=%u port=%u devaddr=%u interface=%u", device_get_unit(res.udev->bus->bdev), (res.udev->parent_hub != NULL) ? res.udev->parent_hub->device_index : 0, res.portno, res.udev->device_index, res.iface_index); done: mtx_unlock(&Giant); return (0); } static int uhub_child_pnpinfo_string(device_t parent, device_t child, char *buf, size_t buflen) { struct uhub_softc *sc; struct usb_hub *hub; struct usb_interface *iface; struct hub_result res; if (!device_is_attached(parent)) { if (buflen) buf[0] = 0; return (0); } sc = device_get_softc(parent); hub = sc->sc_udev->hub; mtx_lock(&Giant); uhub_find_iface_index(hub, child, &res); if (!res.udev) { DPRINTF("device not on hub\n"); if (buflen) { buf[0] = '\0'; } goto done; } iface = usbd_get_iface(res.udev, res.iface_index); if (iface && iface->idesc) { snprintf(buf, buflen, "vendor=0x%04x product=0x%04x " "devclass=0x%02x devsubclass=0x%02x " "sernum=\"%s\" " "release=0x%04x " "mode=%s " "intclass=0x%02x intsubclass=0x%02x " "intprotocol=0x%02x " "%s%s", UGETW(res.udev->ddesc.idVendor), UGETW(res.udev->ddesc.idProduct), res.udev->ddesc.bDeviceClass, res.udev->ddesc.bDeviceSubClass, usb_get_serial(res.udev), UGETW(res.udev->ddesc.bcdDevice), (res.udev->flags.usb_mode == USB_MODE_HOST) ? "host" : "device", iface->idesc->bInterfaceClass, iface->idesc->bInterfaceSubClass, iface->idesc->bInterfaceProtocol, iface->pnpinfo ? " " : "", iface->pnpinfo ? iface->pnpinfo : ""); } else { if (buflen) { buf[0] = '\0'; } goto done; } done: mtx_unlock(&Giant); return (0); } /* * The USB Transaction Translator: * =============================== * * When doing LOW- and FULL-speed USB transfers accross a HIGH-speed * USB HUB, bandwidth must be allocated for ISOCHRONOUS and INTERRUPT * USB transfers. To utilize bandwidth dynamically the "scatter and * gather" principle must be applied. This means that bandwidth must * be divided into equal parts of bandwidth. With regard to USB all * data is transferred in smaller packets with length * "wMaxPacketSize". The problem however is that "wMaxPacketSize" is * not a constant! * * The bandwidth scheduler which I have implemented will simply pack * the USB transfers back to back until there is no more space in the * schedule. Out of the 8 microframes which the USB 2.0 standard * provides, only 6 are available for non-HIGH-speed devices. I have * reserved the first 4 microframes for ISOCHRONOUS transfers. The * last 2 microframes I have reserved for INTERRUPT transfers. Without * this division, it is very difficult to allocate and free bandwidth * dynamically. * * NOTE about the Transaction Translator in USB HUBs: * * USB HUBs have a very simple Transaction Translator, that will * simply pipeline all the SPLIT transactions. That means that the * transactions will be executed in the order they are queued! * */ /*------------------------------------------------------------------------* * usb_intr_find_best_slot * * Return value: * The best Transaction Translation slot for an interrupt endpoint. *------------------------------------------------------------------------*/ static uint8_t usb_intr_find_best_slot(usb_size_t *ptr, uint8_t start, uint8_t end, uint8_t mask) { usb_size_t min = (usb_size_t)-1; usb_size_t sum; uint8_t x; uint8_t y; uint8_t z; y = 0; /* find the last slot with lesser used bandwidth */ for (x = start; x < end; x++) { sum = 0; /* compute sum of bandwidth */ for (z = x; z < end; z++) { if (mask & (1U << (z - x))) sum += ptr[z]; } /* check if the current multi-slot is more optimal */ if (min >= sum) { min = sum; y = x; } /* check if the mask is about to be shifted out */ if (mask & (1U << (end - 1 - x))) break; } return (y); } /*------------------------------------------------------------------------* * usb_hs_bandwidth_adjust * * This function will update the bandwith usage for the microframe * having index "slot" by "len" bytes. "len" can be negative. If the * "slot" argument is greater or equal to "USB_HS_MICRO_FRAMES_MAX" * the "slot" argument will be replaced by the slot having least used * bandwidth. The "mask" argument is used for multi-slot allocations. * * Returns: * The slot in which the bandwidth update was done: 0..7 *------------------------------------------------------------------------*/ static uint8_t usb_hs_bandwidth_adjust(struct usb_device *udev, int16_t len, uint8_t slot, uint8_t mask) { struct usb_bus *bus = udev->bus; struct usb_hub *hub; enum usb_dev_speed speed; uint8_t x; USB_BUS_LOCK_ASSERT(bus, MA_OWNED); speed = usbd_get_speed(udev); switch (speed) { case USB_SPEED_LOW: case USB_SPEED_FULL: if (speed == USB_SPEED_LOW) { len *= 8; } /* * The Host Controller Driver should have * performed checks so that the lookup * below does not result in a NULL pointer * access. */ hub = udev->parent_hs_hub->hub; if (slot >= USB_HS_MICRO_FRAMES_MAX) { slot = usb_intr_find_best_slot(hub->uframe_usage, USB_FS_ISOC_UFRAME_MAX, 6, mask); } for (x = slot; x < 8; x++) { if (mask & (1U << (x - slot))) { hub->uframe_usage[x] += len; bus->uframe_usage[x] += len; } } break; default: if (slot >= USB_HS_MICRO_FRAMES_MAX) { slot = usb_intr_find_best_slot(bus->uframe_usage, 0, USB_HS_MICRO_FRAMES_MAX, mask); } for (x = slot; x < 8; x++) { if (mask & (1U << (x - slot))) { bus->uframe_usage[x] += len; } } break; } return (slot); } /*------------------------------------------------------------------------* * usb_hs_bandwidth_alloc * * This function is a wrapper function for "usb_hs_bandwidth_adjust()". *------------------------------------------------------------------------*/ void usb_hs_bandwidth_alloc(struct usb_xfer *xfer) { struct usb_device *udev; uint8_t slot; uint8_t mask; uint8_t speed; udev = xfer->xroot->udev; if (udev->flags.usb_mode != USB_MODE_HOST) return; /* not supported */ xfer->endpoint->refcount_bw++; if (xfer->endpoint->refcount_bw != 1) return; /* already allocated */ speed = usbd_get_speed(udev); switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) { case UE_INTERRUPT: /* allocate a microframe slot */ mask = 0x01; slot = usb_hs_bandwidth_adjust(udev, xfer->max_frame_size, USB_HS_MICRO_FRAMES_MAX, mask); xfer->endpoint->usb_uframe = slot; xfer->endpoint->usb_smask = mask << slot; if ((speed != USB_SPEED_FULL) && (speed != USB_SPEED_LOW)) { xfer->endpoint->usb_cmask = 0x00 ; } else { xfer->endpoint->usb_cmask = (-(0x04 << slot)) & 0xFE; } break; case UE_ISOCHRONOUS: switch (usbd_xfer_get_fps_shift(xfer)) { case 0: mask = 0xFF; break; case 1: mask = 0x55; break; case 2: mask = 0x11; break; default: mask = 0x01; break; } /* allocate a microframe multi-slot */ slot = usb_hs_bandwidth_adjust(udev, xfer->max_frame_size, USB_HS_MICRO_FRAMES_MAX, mask); xfer->endpoint->usb_uframe = slot; xfer->endpoint->usb_cmask = 0; xfer->endpoint->usb_smask = mask << slot; break; default: xfer->endpoint->usb_uframe = 0; xfer->endpoint->usb_cmask = 0; xfer->endpoint->usb_smask = 0; break; } DPRINTFN(11, "slot=%d, mask=0x%02x\n", xfer->endpoint->usb_uframe, xfer->endpoint->usb_smask >> xfer->endpoint->usb_uframe); } /*------------------------------------------------------------------------* * usb_hs_bandwidth_free * * This function is a wrapper function for "usb_hs_bandwidth_adjust()". *------------------------------------------------------------------------*/ void usb_hs_bandwidth_free(struct usb_xfer *xfer) { struct usb_device *udev; uint8_t slot; uint8_t mask; udev = xfer->xroot->udev; if (udev->flags.usb_mode != USB_MODE_HOST) return; /* not supported */ xfer->endpoint->refcount_bw--; if (xfer->endpoint->refcount_bw != 0) return; /* still allocated */ switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) { case UE_INTERRUPT: case UE_ISOCHRONOUS: slot = xfer->endpoint->usb_uframe; mask = xfer->endpoint->usb_smask; /* free microframe slot(s): */ usb_hs_bandwidth_adjust(udev, -xfer->max_frame_size, slot, mask >> slot); DPRINTFN(11, "slot=%d, mask=0x%02x\n", slot, mask >> slot); xfer->endpoint->usb_uframe = 0; xfer->endpoint->usb_cmask = 0; xfer->endpoint->usb_smask = 0; break; default: break; } } /*------------------------------------------------------------------------* * usb_isoc_time_expand * * This function will expand the time counter from 7-bit to 16-bit. * * Returns: * 16-bit isochronous time counter. *------------------------------------------------------------------------*/ uint16_t usb_isoc_time_expand(struct usb_bus *bus, uint16_t isoc_time_curr) { uint16_t rem; USB_BUS_LOCK_ASSERT(bus, MA_OWNED); rem = bus->isoc_time_last & (USB_ISOC_TIME_MAX - 1); isoc_time_curr &= (USB_ISOC_TIME_MAX - 1); if (isoc_time_curr < rem) { /* the time counter wrapped around */ bus->isoc_time_last += USB_ISOC_TIME_MAX; } /* update the remainder */ bus->isoc_time_last &= ~(USB_ISOC_TIME_MAX - 1); bus->isoc_time_last |= isoc_time_curr; return (bus->isoc_time_last); } /*------------------------------------------------------------------------* * usbd_fs_isoc_schedule_alloc_slot * * This function will allocate bandwidth for an isochronous FULL speed * transaction in the FULL speed schedule. * * Returns: * <8: Success * Else: Error *------------------------------------------------------------------------*/ #if USB_HAVE_TT_SUPPORT uint8_t usbd_fs_isoc_schedule_alloc_slot(struct usb_xfer *isoc_xfer, uint16_t isoc_time) { struct usb_xfer *xfer; struct usb_xfer *pipe_xfer; struct usb_bus *bus; usb_frlength_t len; usb_frlength_t data_len; uint16_t delta; uint16_t slot; uint8_t retval; data_len = 0; slot = 0; bus = isoc_xfer->xroot->bus; TAILQ_FOREACH(xfer, &bus->intr_q.head, wait_entry) { /* skip self, if any */ if (xfer == isoc_xfer) continue; /* check if this USB transfer is going through the same TT */ if (xfer->xroot->udev->parent_hs_hub != isoc_xfer->xroot->udev->parent_hs_hub) { continue; } if ((isoc_xfer->xroot->udev->parent_hs_hub-> ddesc.bDeviceProtocol == UDPROTO_HSHUBMTT) && (xfer->xroot->udev->hs_port_no != isoc_xfer->xroot->udev->hs_port_no)) { continue; } if (xfer->endpoint->methods != isoc_xfer->endpoint->methods) continue; /* check if isoc_time is part of this transfer */ delta = xfer->isoc_time_complete - isoc_time; if (delta > 0 && delta <= xfer->nframes) { delta = xfer->nframes - delta; len = xfer->frlengths[delta]; len += 8; len *= 7; len /= 6; data_len += len; } /* * Check double buffered transfers. Only stream ID * equal to zero is valid here! */ TAILQ_FOREACH(pipe_xfer, &xfer->endpoint->endpoint_q[0].head, wait_entry) { /* skip self, if any */ if (pipe_xfer == isoc_xfer) continue; /* check if isoc_time is part of this transfer */ delta = pipe_xfer->isoc_time_complete - isoc_time; if (delta > 0 && delta <= pipe_xfer->nframes) { delta = pipe_xfer->nframes - delta; len = pipe_xfer->frlengths[delta]; len += 8; len *= 7; len /= 6; data_len += len; } } } while (data_len >= USB_FS_BYTES_PER_HS_UFRAME) { data_len -= USB_FS_BYTES_PER_HS_UFRAME; slot++; } /* check for overflow */ if (slot >= USB_FS_ISOC_UFRAME_MAX) return (255); retval = slot; delta = isoc_xfer->isoc_time_complete - isoc_time; if (delta > 0 && delta <= isoc_xfer->nframes) { delta = isoc_xfer->nframes - delta; len = isoc_xfer->frlengths[delta]; len += 8; len *= 7; len /= 6; data_len += len; } while (data_len >= USB_FS_BYTES_PER_HS_UFRAME) { data_len -= USB_FS_BYTES_PER_HS_UFRAME; slot++; } /* check for overflow */ if (slot >= USB_FS_ISOC_UFRAME_MAX) return (255); return (retval); } #endif /*------------------------------------------------------------------------* * usb_bus_port_get_device * * This function is NULL safe. *------------------------------------------------------------------------*/ struct usb_device * usb_bus_port_get_device(struct usb_bus *bus, struct usb_port *up) { if ((bus == NULL) || (up == NULL)) { /* be NULL safe */ return (NULL); } if (up->device_index == 0) { /* nothing to do */ return (NULL); } return (bus->devices[up->device_index]); } /*------------------------------------------------------------------------* * usb_bus_port_set_device * * This function is NULL safe. *------------------------------------------------------------------------*/ void usb_bus_port_set_device(struct usb_bus *bus, struct usb_port *up, struct usb_device *udev, uint8_t device_index) { if (bus == NULL) { /* be NULL safe */ return; } /* * There is only one case where we don't * have an USB port, and that is the Root Hub! */ if (up) { if (udev) { up->device_index = device_index; } else { device_index = up->device_index; up->device_index = 0; } } /* * Make relationships to our new device */ if (device_index != 0) { #if USB_HAVE_UGEN mtx_lock(&usb_ref_lock); #endif bus->devices[device_index] = udev; #if USB_HAVE_UGEN mtx_unlock(&usb_ref_lock); #endif } /* * Debug print */ DPRINTFN(2, "bus %p devices[%u] = %p\n", bus, device_index, udev); } /*------------------------------------------------------------------------* * usb_needs_explore * * This functions is called when the USB event thread needs to run. *------------------------------------------------------------------------*/ void usb_needs_explore(struct usb_bus *bus, uint8_t do_probe) { uint8_t do_unlock; DPRINTF("\n"); if (bus == NULL) { DPRINTF("No bus pointer!\n"); return; } if ((bus->devices == NULL) || (bus->devices[USB_ROOT_HUB_ADDR] == NULL)) { DPRINTF("No root HUB\n"); return; } if (mtx_owned(&bus->bus_mtx)) { do_unlock = 0; } else { USB_BUS_LOCK(bus); do_unlock = 1; } if (do_probe) { bus->do_probe = 1; } if (usb_proc_msignal(USB_BUS_EXPLORE_PROC(bus), &bus->explore_msg[0], &bus->explore_msg[1])) { /* ignore */ } if (do_unlock) { USB_BUS_UNLOCK(bus); } } /*------------------------------------------------------------------------* * usb_needs_explore_all * * This function is called whenever a new driver is loaded and will * cause that all USB busses are re-explored. *------------------------------------------------------------------------*/ void usb_needs_explore_all(void) { struct usb_bus *bus; devclass_t dc; device_t dev; int max; DPRINTFN(3, "\n"); dc = usb_devclass_ptr; if (dc == NULL) { DPRINTFN(0, "no devclass\n"); return; } /* * Explore all USB busses in parallell. */ max = devclass_get_maxunit(dc); while (max >= 0) { dev = devclass_get_device(dc, max); if (dev) { bus = device_get_softc(dev); if (bus) { usb_needs_explore(bus, 1); } } max--; } } /*------------------------------------------------------------------------* * usb_bus_power_update * * This function will ensure that all USB devices on the given bus are * properly suspended or resumed according to the device transfer * state. *------------------------------------------------------------------------*/ #if USB_HAVE_POWERD void usb_bus_power_update(struct usb_bus *bus) { usb_needs_explore(bus, 0 /* no probe */ ); } #endif /*------------------------------------------------------------------------* * usbd_transfer_power_ref * * This function will modify the power save reference counts and * wakeup the USB device associated with the given USB transfer, if * needed. *------------------------------------------------------------------------*/ #if USB_HAVE_POWERD void usbd_transfer_power_ref(struct usb_xfer *xfer, int val) { static const usb_power_mask_t power_mask[4] = { [UE_CONTROL] = USB_HW_POWER_CONTROL, [UE_BULK] = USB_HW_POWER_BULK, [UE_INTERRUPT] = USB_HW_POWER_INTERRUPT, [UE_ISOCHRONOUS] = USB_HW_POWER_ISOC, }; struct usb_device *udev; uint8_t needs_explore; uint8_t needs_hw_power; uint8_t xfer_type; udev = xfer->xroot->udev; if (udev->device_index == USB_ROOT_HUB_ADDR) { /* no power save for root HUB */ return; } USB_BUS_LOCK(udev->bus); xfer_type = xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE; udev->pwr_save.last_xfer_time = ticks; udev->pwr_save.type_refs[xfer_type] += val; if (xfer->flags_int.control_xfr) { udev->pwr_save.read_refs += val; if (xfer->flags_int.usb_mode == USB_MODE_HOST) { /* * It is not allowed to suspend during a * control transfer: */ udev->pwr_save.write_refs += val; } } else if (USB_GET_DATA_ISREAD(xfer)) { udev->pwr_save.read_refs += val; } else { udev->pwr_save.write_refs += val; } if (val > 0) { if (udev->flags.self_suspended) needs_explore = usb_peer_should_wakeup(udev); else needs_explore = 0; if (!(udev->bus->hw_power_state & power_mask[xfer_type])) { DPRINTF("Adding type %u to power state\n", xfer_type); udev->bus->hw_power_state |= power_mask[xfer_type]; needs_hw_power = 1; } else { needs_hw_power = 0; } } else { needs_explore = 0; needs_hw_power = 0; } USB_BUS_UNLOCK(udev->bus); if (needs_explore) { DPRINTF("update\n"); usb_bus_power_update(udev->bus); } else if (needs_hw_power) { DPRINTF("needs power\n"); if (udev->bus->methods->set_hw_power != NULL) { (udev->bus->methods->set_hw_power) (udev->bus); } } } #endif /*------------------------------------------------------------------------* * usb_peer_should_wakeup * * This function returns non-zero if the current device should wake up. *------------------------------------------------------------------------*/ static uint8_t usb_peer_should_wakeup(struct usb_device *udev) { return (((udev->power_mode == USB_POWER_MODE_ON) && (udev->flags.usb_mode == USB_MODE_HOST)) || (udev->driver_added_refcount != udev->bus->driver_added_refcount) || (udev->re_enumerate_wait != USB_RE_ENUM_DONE) || (udev->pwr_save.type_refs[UE_ISOCHRONOUS] != 0) || (udev->pwr_save.write_refs != 0) || ((udev->pwr_save.read_refs != 0) && (udev->flags.usb_mode == USB_MODE_HOST) && (usb_peer_can_wakeup(udev) == 0))); } /*------------------------------------------------------------------------* * usb_bus_powerd * * This function implements the USB power daemon and is called * regularly from the USB explore thread. *------------------------------------------------------------------------*/ #if USB_HAVE_POWERD void usb_bus_powerd(struct usb_bus *bus) { struct usb_device *udev; usb_ticks_t temp; usb_ticks_t limit; usb_ticks_t mintime; usb_size_t type_refs[5]; uint8_t x; limit = usb_power_timeout; if (limit == 0) limit = hz; else if (limit > 255) limit = 255 * hz; else limit = limit * hz; DPRINTF("bus=%p\n", bus); USB_BUS_LOCK(bus); /* * The root HUB device is never suspended * and we simply skip it. */ for (x = USB_ROOT_HUB_ADDR + 1; x != bus->devices_max; x++) { udev = bus->devices[x]; if (udev == NULL) continue; temp = ticks - udev->pwr_save.last_xfer_time; if (usb_peer_should_wakeup(udev)) { /* check if we are suspended */ if (udev->flags.self_suspended != 0) { USB_BUS_UNLOCK(bus); usb_dev_resume_peer(udev); USB_BUS_LOCK(bus); } } else if ((temp >= limit) && (udev->flags.usb_mode == USB_MODE_HOST) && (udev->flags.self_suspended == 0)) { /* try to do suspend */ USB_BUS_UNLOCK(bus); usb_dev_suspend_peer(udev); USB_BUS_LOCK(bus); } } /* reset counters */ mintime = (usb_ticks_t)-1; type_refs[0] = 0; type_refs[1] = 0; type_refs[2] = 0; type_refs[3] = 0; type_refs[4] = 0; /* Re-loop all the devices to get the actual state */ for (x = USB_ROOT_HUB_ADDR + 1; x != bus->devices_max; x++) { udev = bus->devices[x]; if (udev == NULL) continue; /* we found a non-Root-Hub USB device */ type_refs[4] += 1; /* "last_xfer_time" can be updated by a resume */ temp = ticks - udev->pwr_save.last_xfer_time; /* * Compute minimum time since last transfer for the complete * bus: */ if (temp < mintime) mintime = temp; if (udev->flags.self_suspended == 0) { type_refs[0] += udev->pwr_save.type_refs[0]; type_refs[1] += udev->pwr_save.type_refs[1]; type_refs[2] += udev->pwr_save.type_refs[2]; type_refs[3] += udev->pwr_save.type_refs[3]; } } if (mintime >= (usb_ticks_t)(1 * hz)) { /* recompute power masks */ DPRINTF("Recomputing power masks\n"); bus->hw_power_state = 0; if (type_refs[UE_CONTROL] != 0) bus->hw_power_state |= USB_HW_POWER_CONTROL; if (type_refs[UE_BULK] != 0) bus->hw_power_state |= USB_HW_POWER_BULK; if (type_refs[UE_INTERRUPT] != 0) bus->hw_power_state |= USB_HW_POWER_INTERRUPT; if (type_refs[UE_ISOCHRONOUS] != 0) bus->hw_power_state |= USB_HW_POWER_ISOC; if (type_refs[4] != 0) bus->hw_power_state |= USB_HW_POWER_NON_ROOT_HUB; } USB_BUS_UNLOCK(bus); if (bus->methods->set_hw_power != NULL) { /* always update hardware power! */ (bus->methods->set_hw_power) (bus); } return; } #endif /*------------------------------------------------------------------------* * usb_dev_resume_peer * * This function will resume an USB peer and do the required USB * signalling to get an USB device out of the suspended state. *------------------------------------------------------------------------*/ static void usb_dev_resume_peer(struct usb_device *udev) { struct usb_bus *bus; int err; /* be NULL safe */ if (udev == NULL) return; /* check if already resumed */ if (udev->flags.self_suspended == 0) return; /* we need a parent HUB to do resume */ if (udev->parent_hub == NULL) return; DPRINTF("udev=%p\n", udev); if ((udev->flags.usb_mode == USB_MODE_DEVICE) && (udev->flags.remote_wakeup == 0)) { /* * If the host did not set the remote wakeup feature, we can * not wake it up either! */ DPRINTF("remote wakeup is not set!\n"); return; } /* get bus pointer */ bus = udev->bus; /* resume parent hub first */ usb_dev_resume_peer(udev->parent_hub); /* reduce chance of instant resume failure by waiting a little bit */ usb_pause_mtx(NULL, USB_MS_TO_TICKS(20)); if (usb_device_20_compatible(udev)) { /* resume current port (Valid in Host and Device Mode) */ err = usbd_req_clear_port_feature(udev->parent_hub, NULL, udev->port_no, UHF_PORT_SUSPEND); if (err) { DPRINTFN(0, "Resuming port failed\n"); return; } } else { /* resume current port (Valid in Host and Device Mode) */ err = usbd_req_set_port_link_state(udev->parent_hub, NULL, udev->port_no, UPS_PORT_LS_U0); if (err) { DPRINTFN(0, "Resuming port failed\n"); return; } } /* resume settle time */ usb_pause_mtx(NULL, USB_MS_TO_TICKS(usb_port_resume_delay)); if (bus->methods->device_resume != NULL) { /* resume USB device on the USB controller */ (bus->methods->device_resume) (udev); } USB_BUS_LOCK(bus); /* set that this device is now resumed */ udev->flags.self_suspended = 0; #if USB_HAVE_POWERD /* make sure that we don't go into suspend right away */ udev->pwr_save.last_xfer_time = ticks; /* make sure the needed power masks are on */ if (udev->pwr_save.type_refs[UE_CONTROL] != 0) bus->hw_power_state |= USB_HW_POWER_CONTROL; if (udev->pwr_save.type_refs[UE_BULK] != 0) bus->hw_power_state |= USB_HW_POWER_BULK; if (udev->pwr_save.type_refs[UE_INTERRUPT] != 0) bus->hw_power_state |= USB_HW_POWER_INTERRUPT; if (udev->pwr_save.type_refs[UE_ISOCHRONOUS] != 0) bus->hw_power_state |= USB_HW_POWER_ISOC; #endif USB_BUS_UNLOCK(bus); if (bus->methods->set_hw_power != NULL) { /* always update hardware power! */ (bus->methods->set_hw_power) (bus); } usbd_sr_lock(udev); /* notify all sub-devices about resume */ err = usb_suspend_resume(udev, 0); usbd_sr_unlock(udev); /* check if peer has wakeup capability */ if (usb_peer_can_wakeup(udev)) { /* clear remote wakeup */ err = usbd_req_clear_device_feature(udev, NULL, UF_DEVICE_REMOTE_WAKEUP); if (err) { DPRINTFN(0, "Clearing device " "remote wakeup failed: %s\n", usbd_errstr(err)); } } } /*------------------------------------------------------------------------* * usb_dev_suspend_peer * * This function will suspend an USB peer and do the required USB * signalling to get an USB device into the suspended state. *------------------------------------------------------------------------*/ static void usb_dev_suspend_peer(struct usb_device *udev) { struct usb_device *child; int err; uint8_t x; uint8_t nports; repeat: /* be NULL safe */ if (udev == NULL) return; /* check if already suspended */ if (udev->flags.self_suspended) return; /* we need a parent HUB to do suspend */ if (udev->parent_hub == NULL) return; DPRINTF("udev=%p\n", udev); /* check if the current device is a HUB */ if (udev->hub != NULL) { nports = udev->hub->nports; /* check if all devices on the HUB are suspended */ for (x = 0; x != nports; x++) { child = usb_bus_port_get_device(udev->bus, udev->hub->ports + x); if (child == NULL) continue; if (child->flags.self_suspended) continue; DPRINTFN(1, "Port %u is busy on the HUB!\n", x + 1); return; } } if (usb_peer_can_wakeup(udev)) { /* * This request needs to be done before we set * "udev->flags.self_suspended": */ /* allow device to do remote wakeup */ err = usbd_req_set_device_feature(udev, NULL, UF_DEVICE_REMOTE_WAKEUP); if (err) { DPRINTFN(0, "Setting device " "remote wakeup failed\n"); } } USB_BUS_LOCK(udev->bus); /* * Checking for suspend condition and setting suspended bit * must be atomic! */ err = usb_peer_should_wakeup(udev); if (err == 0) { /* * Set that this device is suspended. This variable * must be set before calling USB controller suspend * callbacks. */ udev->flags.self_suspended = 1; } USB_BUS_UNLOCK(udev->bus); if (err != 0) { if (usb_peer_can_wakeup(udev)) { /* allow device to do remote wakeup */ err = usbd_req_clear_device_feature(udev, NULL, UF_DEVICE_REMOTE_WAKEUP); if (err) { DPRINTFN(0, "Setting device " "remote wakeup failed\n"); } } if (udev->flags.usb_mode == USB_MODE_DEVICE) { /* resume parent HUB first */ usb_dev_resume_peer(udev->parent_hub); /* reduce chance of instant resume failure by waiting a little bit */ usb_pause_mtx(NULL, USB_MS_TO_TICKS(20)); /* resume current port (Valid in Host and Device Mode) */ err = usbd_req_clear_port_feature(udev->parent_hub, NULL, udev->port_no, UHF_PORT_SUSPEND); /* resume settle time */ usb_pause_mtx(NULL, USB_MS_TO_TICKS(usb_port_resume_delay)); } DPRINTF("Suspend was cancelled!\n"); return; } usbd_sr_lock(udev); /* notify all sub-devices about suspend */ err = usb_suspend_resume(udev, 1); usbd_sr_unlock(udev); if (udev->bus->methods->device_suspend != NULL) { usb_timeout_t temp; /* suspend device on the USB controller */ (udev->bus->methods->device_suspend) (udev); /* do DMA delay */ temp = usbd_get_dma_delay(udev); if (temp != 0) usb_pause_mtx(NULL, USB_MS_TO_TICKS(temp)); } if (usb_device_20_compatible(udev)) { /* suspend current port */ err = usbd_req_set_port_feature(udev->parent_hub, NULL, udev->port_no, UHF_PORT_SUSPEND); if (err) { DPRINTFN(0, "Suspending port failed\n"); return; } } else { /* suspend current port */ err = usbd_req_set_port_link_state(udev->parent_hub, NULL, udev->port_no, UPS_PORT_LS_U3); if (err) { DPRINTFN(0, "Suspending port failed\n"); return; } } udev = udev->parent_hub; goto repeat; } /*------------------------------------------------------------------------* * usbd_set_power_mode * * This function will set the power mode, see USB_POWER_MODE_XXX for a * USB device. *------------------------------------------------------------------------*/ void usbd_set_power_mode(struct usb_device *udev, uint8_t power_mode) { /* filter input argument */ if ((power_mode != USB_POWER_MODE_ON) && (power_mode != USB_POWER_MODE_OFF)) power_mode = USB_POWER_MODE_SAVE; power_mode = usbd_filter_power_mode(udev, power_mode); udev->power_mode = power_mode; /* update copy of power mode */ #if USB_HAVE_POWERD usb_bus_power_update(udev->bus); #else usb_needs_explore(udev->bus, 0 /* no probe */ ); #endif } /*------------------------------------------------------------------------* * usbd_filter_power_mode * * This function filters the power mode based on hardware requirements. *------------------------------------------------------------------------*/ uint8_t usbd_filter_power_mode(struct usb_device *udev, uint8_t power_mode) { const struct usb_bus_methods *mtod; int8_t temp; mtod = udev->bus->methods; temp = -1; if (mtod->get_power_mode != NULL) (mtod->get_power_mode) (udev, &temp); /* check if we should not filter */ if (temp < 0) return (power_mode); /* use fixed power mode given by hardware driver */ return (temp); } /*------------------------------------------------------------------------* * usbd_start_re_enumerate * * This function starts re-enumeration of the given USB device. This * function does not need to be called BUS-locked. This function does * not wait until the re-enumeration is completed. *------------------------------------------------------------------------*/ void usbd_start_re_enumerate(struct usb_device *udev) { if (udev->re_enumerate_wait == USB_RE_ENUM_DONE) { udev->re_enumerate_wait = USB_RE_ENUM_START; usb_needs_explore(udev->bus, 0); } } /*-----------------------------------------------------------------------* * usbd_start_set_config * * This function starts setting a USB configuration. This function * does not need to be called BUS-locked. This function does not wait * until the set USB configuratino is completed. *------------------------------------------------------------------------*/ usb_error_t usbd_start_set_config(struct usb_device *udev, uint8_t index) { if (udev->re_enumerate_wait == USB_RE_ENUM_DONE) { if (udev->curr_config_index == index) { /* no change needed */ return (0); } udev->next_config_index = index; udev->re_enumerate_wait = USB_RE_ENUM_SET_CONFIG; usb_needs_explore(udev->bus, 0); return (0); } else if (udev->re_enumerate_wait == USB_RE_ENUM_SET_CONFIG) { if (udev->next_config_index == index) { /* no change needed */ return (0); } } return (USB_ERR_PENDING_REQUESTS); } Index: head/sys/dev/usb/usb_request.c =================================================================== --- head/sys/dev/usb/usb_request.c (revision 276700) +++ head/sys/dev/usb/usb_request.c (revision 276701) @@ -1,2291 +1,2291 @@ /* $FreeBSD$ */ /*- * Copyright (c) 1998 The NetBSD Foundation, Inc. All rights reserved. * Copyright (c) 1998 Lennart Augustsson. All rights reserved. * Copyright (c) 2008 Hans Petter Selasky. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifdef USB_GLOBAL_INCLUDE_FILE #include USB_GLOBAL_INCLUDE_FILE #else #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define USB_DEBUG_VAR usb_debug #include #include #include #include #include #include #include #include #include #include #include #include #endif /* USB_GLOBAL_INCLUDE_FILE */ static int usb_no_cs_fail; -SYSCTL_INT(_hw_usb, OID_AUTO, no_cs_fail, CTLFLAG_RW, +SYSCTL_INT(_hw_usb, OID_AUTO, no_cs_fail, CTLFLAG_RWTUN, &usb_no_cs_fail, 0, "USB clear stall failures are ignored, if set"); static int usb_full_ddesc; -SYSCTL_INT(_hw_usb, OID_AUTO, full_ddesc, CTLFLAG_RW, +SYSCTL_INT(_hw_usb, OID_AUTO, full_ddesc, CTLFLAG_RWTUN, &usb_full_ddesc, 0, "USB always read complete device descriptor, if set"); #ifdef USB_DEBUG #ifdef USB_REQ_DEBUG /* The following structures are used in connection to fault injection. */ struct usb_ctrl_debug { int bus_index; /* target bus */ int dev_index; /* target address */ int ds_fail; /* fail data stage */ int ss_fail; /* fail status stage */ int ds_delay; /* data stage delay in ms */ int ss_delay; /* status stage delay in ms */ int bmRequestType_value; int bRequest_value; }; struct usb_ctrl_debug_bits { uint16_t ds_delay; uint16_t ss_delay; uint8_t ds_fail:1; uint8_t ss_fail:1; uint8_t enabled:1; }; /* The default is to disable fault injection. */ static struct usb_ctrl_debug usb_ctrl_debug = { .bus_index = -1, .dev_index = -1, .bmRequestType_value = -1, .bRequest_value = -1, }; -SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_bus_fail, CTLFLAG_RW, +SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_bus_fail, CTLFLAG_RWTUN, &usb_ctrl_debug.bus_index, 0, "USB controller index to fail"); -SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_dev_fail, CTLFLAG_RW, +SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_dev_fail, CTLFLAG_RWTUN, &usb_ctrl_debug.dev_index, 0, "USB device address to fail"); -SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ds_fail, CTLFLAG_RW, +SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ds_fail, CTLFLAG_RWTUN, &usb_ctrl_debug.ds_fail, 0, "USB fail data stage"); -SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ss_fail, CTLFLAG_RW, +SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ss_fail, CTLFLAG_RWTUN, &usb_ctrl_debug.ss_fail, 0, "USB fail status stage"); -SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ds_delay, CTLFLAG_RW, +SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ds_delay, CTLFLAG_RWTUN, &usb_ctrl_debug.ds_delay, 0, "USB data stage delay in ms"); -SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ss_delay, CTLFLAG_RW, +SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ss_delay, CTLFLAG_RWTUN, &usb_ctrl_debug.ss_delay, 0, "USB status stage delay in ms"); -SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_rt_fail, CTLFLAG_RW, +SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_rt_fail, CTLFLAG_RWTUN, &usb_ctrl_debug.bmRequestType_value, 0, "USB bmRequestType to fail"); -SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_rv_fail, CTLFLAG_RW, +SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_rv_fail, CTLFLAG_RWTUN, &usb_ctrl_debug.bRequest_value, 0, "USB bRequest to fail"); /*------------------------------------------------------------------------* * usbd_get_debug_bits * * This function is only useful in USB host mode. *------------------------------------------------------------------------*/ static void usbd_get_debug_bits(struct usb_device *udev, struct usb_device_request *req, struct usb_ctrl_debug_bits *dbg) { int temp; memset(dbg, 0, sizeof(*dbg)); /* Compute data stage delay */ temp = usb_ctrl_debug.ds_delay; if (temp < 0) temp = 0; else if (temp > (16*1024)) temp = (16*1024); dbg->ds_delay = temp; /* Compute status stage delay */ temp = usb_ctrl_debug.ss_delay; if (temp < 0) temp = 0; else if (temp > (16*1024)) temp = (16*1024); dbg->ss_delay = temp; /* Check if this control request should be failed */ if (usbd_get_bus_index(udev) != usb_ctrl_debug.bus_index) return; if (usbd_get_device_index(udev) != usb_ctrl_debug.dev_index) return; temp = usb_ctrl_debug.bmRequestType_value; if ((temp != req->bmRequestType) && (temp >= 0) && (temp <= 255)) return; temp = usb_ctrl_debug.bRequest_value; if ((temp != req->bRequest) && (temp >= 0) && (temp <= 255)) return; temp = usb_ctrl_debug.ds_fail; if (temp) dbg->ds_fail = 1; temp = usb_ctrl_debug.ss_fail; if (temp) dbg->ss_fail = 1; dbg->enabled = 1; } #endif /* USB_REQ_DEBUG */ #endif /* USB_DEBUG */ /*------------------------------------------------------------------------* * usbd_do_request_callback * * This function is the USB callback for generic USB Host control * transfers. *------------------------------------------------------------------------*/ void usbd_do_request_callback(struct usb_xfer *xfer, usb_error_t error) { ; /* workaround for a bug in "indent" */ DPRINTF("st=%u\n", USB_GET_STATE(xfer)); switch (USB_GET_STATE(xfer)) { case USB_ST_SETUP: usbd_transfer_submit(xfer); break; default: cv_signal(&xfer->xroot->udev->ctrlreq_cv); break; } } /*------------------------------------------------------------------------* * usb_do_clear_stall_callback * * This function is the USB callback for generic clear stall requests. *------------------------------------------------------------------------*/ void usb_do_clear_stall_callback(struct usb_xfer *xfer, usb_error_t error) { struct usb_device_request req; struct usb_device *udev; struct usb_endpoint *ep; struct usb_endpoint *ep_end; struct usb_endpoint *ep_first; usb_stream_t x; uint8_t to; udev = xfer->xroot->udev; USB_BUS_LOCK(udev->bus); /* round robin endpoint clear stall */ ep = udev->ep_curr; ep_end = udev->endpoints + udev->endpoints_max; ep_first = udev->endpoints; to = udev->endpoints_max; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: tr_transferred: /* reset error counter */ udev->clear_stall_errors = 0; if (ep == NULL) goto tr_setup; /* device was unconfigured */ if (ep->edesc && ep->is_stalled) { ep->toggle_next = 0; ep->is_stalled = 0; /* some hardware needs a callback to clear the data toggle */ usbd_clear_stall_locked(udev, ep); for (x = 0; x != USB_MAX_EP_STREAMS; x++) { /* start the current or next transfer, if any */ usb_command_wrapper(&ep->endpoint_q[x], ep->endpoint_q[x].curr); } } ep++; case USB_ST_SETUP: tr_setup: if (to == 0) break; /* no endpoints - nothing to do */ if ((ep < ep_first) || (ep >= ep_end)) ep = ep_first; /* endpoint wrapped around */ if (ep->edesc && ep->is_stalled) { /* setup a clear-stall packet */ req.bmRequestType = UT_WRITE_ENDPOINT; req.bRequest = UR_CLEAR_FEATURE; USETW(req.wValue, UF_ENDPOINT_HALT); req.wIndex[0] = ep->edesc->bEndpointAddress; req.wIndex[1] = 0; USETW(req.wLength, 0); /* copy in the transfer */ usbd_copy_in(xfer->frbuffers, 0, &req, sizeof(req)); /* set length */ usbd_xfer_set_frame_len(xfer, 0, sizeof(req)); xfer->nframes = 1; USB_BUS_UNLOCK(udev->bus); usbd_transfer_submit(xfer); USB_BUS_LOCK(udev->bus); break; } ep++; to--; goto tr_setup; default: if (error == USB_ERR_CANCELLED) break; DPRINTF("Clear stall failed.\n"); /* * Some VMs like VirtualBox always return failure on * clear-stall which we sometimes should just ignore. */ if (usb_no_cs_fail) goto tr_transferred; if (udev->clear_stall_errors == USB_CS_RESET_LIMIT) goto tr_setup; if (error == USB_ERR_TIMEOUT) { udev->clear_stall_errors = USB_CS_RESET_LIMIT; DPRINTF("Trying to re-enumerate.\n"); usbd_start_re_enumerate(udev); } else { udev->clear_stall_errors++; if (udev->clear_stall_errors == USB_CS_RESET_LIMIT) { DPRINTF("Trying to re-enumerate.\n"); usbd_start_re_enumerate(udev); } } goto tr_setup; } /* store current endpoint */ udev->ep_curr = ep; USB_BUS_UNLOCK(udev->bus); } static usb_handle_req_t * usbd_get_hr_func(struct usb_device *udev) { /* figure out if there is a Handle Request function */ if (udev->flags.usb_mode == USB_MODE_DEVICE) return (usb_temp_get_desc_p); else if (udev->parent_hub == NULL) return (udev->bus->methods->roothub_exec); else return (NULL); } /*------------------------------------------------------------------------* * usbd_do_request_flags and usbd_do_request * * Description of arguments passed to these functions: * * "udev" - this is the "usb_device" structure pointer on which the * request should be performed. It is possible to call this function * in both Host Side mode and Device Side mode. * * "mtx" - if this argument is non-NULL the mutex pointed to by it * will get dropped and picked up during the execution of this * function, hence this function sometimes needs to sleep. If this * argument is NULL it has no effect. * * "req" - this argument must always be non-NULL and points to an * 8-byte structure holding the USB request to be done. The USB * request structure has a bit telling the direction of the USB * request, if it is a read or a write. * * "data" - if the "wLength" part of the structure pointed to by "req" * is non-zero this argument must point to a valid kernel buffer which * can hold at least "wLength" bytes. If "wLength" is zero "data" can * be NULL. * * "flags" - here is a list of valid flags: * * o USB_SHORT_XFER_OK: allows the data transfer to be shorter than * specified * * o USB_DELAY_STATUS_STAGE: allows the status stage to be performed * at a later point in time. This is tunable by the "hw.usb.ss_delay" * sysctl. This flag is mostly useful for debugging. * * o USB_USER_DATA_PTR: treat the "data" pointer like a userland * pointer. * * "actlen" - if non-NULL the actual transfer length will be stored in * the 16-bit unsigned integer pointed to by "actlen". This * information is mostly useful when the "USB_SHORT_XFER_OK" flag is * used. * * "timeout" - gives the timeout for the control transfer in * milliseconds. A "timeout" value less than 50 milliseconds is * treated like a 50 millisecond timeout. A "timeout" value greater * than 30 seconds is treated like a 30 second timeout. This USB stack * does not allow control requests without a timeout. * * NOTE: This function is thread safe. All calls to "usbd_do_request_flags" * will be serialized by the use of the USB device enumeration lock. * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_do_request_flags(struct usb_device *udev, struct mtx *mtx, struct usb_device_request *req, void *data, uint16_t flags, uint16_t *actlen, usb_timeout_t timeout) { #ifdef USB_REQ_DEBUG struct usb_ctrl_debug_bits dbg; #endif usb_handle_req_t *hr_func; struct usb_xfer *xfer; const void *desc; int err = 0; usb_ticks_t start_ticks; usb_ticks_t delta_ticks; usb_ticks_t max_ticks; uint16_t length; uint16_t temp; uint16_t acttemp; uint8_t do_unlock; if (timeout < 50) { /* timeout is too small */ timeout = 50; } if (timeout > 30000) { /* timeout is too big */ timeout = 30000; } length = UGETW(req->wLength); DPRINTFN(5, "udev=%p bmRequestType=0x%02x bRequest=0x%02x " "wValue=0x%02x%02x wIndex=0x%02x%02x wLength=0x%02x%02x\n", udev, req->bmRequestType, req->bRequest, req->wValue[1], req->wValue[0], req->wIndex[1], req->wIndex[0], req->wLength[1], req->wLength[0]); /* Check if the device is still alive */ if (udev->state < USB_STATE_POWERED) { DPRINTF("usb device has gone\n"); return (USB_ERR_NOT_CONFIGURED); } /* * Set "actlen" to a known value in case the caller does not * check the return value: */ if (actlen) *actlen = 0; #if (USB_HAVE_USER_IO == 0) if (flags & USB_USER_DATA_PTR) return (USB_ERR_INVAL); #endif if ((mtx != NULL) && (mtx != &Giant)) { mtx_unlock(mtx); mtx_assert(mtx, MA_NOTOWNED); } /* * Grab the USB device enumeration SX-lock serialization is * achieved when multiple threads are involved: */ do_unlock = usbd_enum_lock(udev); /* * We need to allow suspend and resume at this point, else the * control transfer will timeout if the device is suspended! */ usbd_sr_unlock(udev); hr_func = usbd_get_hr_func(udev); if (hr_func != NULL) { DPRINTF("Handle Request function is set\n"); desc = NULL; temp = 0; if (!(req->bmRequestType & UT_READ)) { if (length != 0) { DPRINTFN(1, "The handle request function " "does not support writing data!\n"); err = USB_ERR_INVAL; goto done; } } /* The root HUB code needs the BUS lock locked */ USB_BUS_LOCK(udev->bus); err = (hr_func) (udev, req, &desc, &temp); USB_BUS_UNLOCK(udev->bus); if (err) goto done; if (length > temp) { if (!(flags & USB_SHORT_XFER_OK)) { err = USB_ERR_SHORT_XFER; goto done; } length = temp; } if (actlen) *actlen = length; if (length > 0) { #if USB_HAVE_USER_IO if (flags & USB_USER_DATA_PTR) { if (copyout(desc, data, length)) { err = USB_ERR_INVAL; goto done; } } else #endif memcpy(data, desc, length); } goto done; /* success */ } /* * Setup a new USB transfer or use the existing one, if any: */ usbd_ctrl_transfer_setup(udev); xfer = udev->ctrl_xfer[0]; if (xfer == NULL) { /* most likely out of memory */ err = USB_ERR_NOMEM; goto done; } #ifdef USB_REQ_DEBUG /* Get debug bits */ usbd_get_debug_bits(udev, req, &dbg); /* Check for fault injection */ if (dbg.enabled) flags |= USB_DELAY_STATUS_STAGE; #endif USB_XFER_LOCK(xfer); if (flags & USB_DELAY_STATUS_STAGE) xfer->flags.manual_status = 1; else xfer->flags.manual_status = 0; if (flags & USB_SHORT_XFER_OK) xfer->flags.short_xfer_ok = 1; else xfer->flags.short_xfer_ok = 0; xfer->timeout = timeout; start_ticks = ticks; max_ticks = USB_MS_TO_TICKS(timeout); usbd_copy_in(xfer->frbuffers, 0, req, sizeof(*req)); usbd_xfer_set_frame_len(xfer, 0, sizeof(*req)); while (1) { temp = length; if (temp > usbd_xfer_max_len(xfer)) { temp = usbd_xfer_max_len(xfer); } #ifdef USB_REQ_DEBUG if (xfer->flags.manual_status) { if (usbd_xfer_frame_len(xfer, 0) != 0) { /* Execute data stage separately */ temp = 0; } else if (temp > 0) { if (dbg.ds_fail) { err = USB_ERR_INVAL; break; } if (dbg.ds_delay > 0) { usb_pause_mtx( xfer->xroot->xfer_mtx, USB_MS_TO_TICKS(dbg.ds_delay)); /* make sure we don't time out */ start_ticks = ticks; } } } #endif usbd_xfer_set_frame_len(xfer, 1, temp); if (temp > 0) { if (!(req->bmRequestType & UT_READ)) { #if USB_HAVE_USER_IO if (flags & USB_USER_DATA_PTR) { USB_XFER_UNLOCK(xfer); err = usbd_copy_in_user(xfer->frbuffers + 1, 0, data, temp); USB_XFER_LOCK(xfer); if (err) { err = USB_ERR_INVAL; break; } } else #endif usbd_copy_in(xfer->frbuffers + 1, 0, data, temp); } usbd_xfer_set_frames(xfer, 2); } else { if (usbd_xfer_frame_len(xfer, 0) == 0) { if (xfer->flags.manual_status) { #ifdef USB_REQ_DEBUG if (dbg.ss_fail) { err = USB_ERR_INVAL; break; } if (dbg.ss_delay > 0) { usb_pause_mtx( xfer->xroot->xfer_mtx, USB_MS_TO_TICKS(dbg.ss_delay)); /* make sure we don't time out */ start_ticks = ticks; } #endif xfer->flags.manual_status = 0; } else { break; } } usbd_xfer_set_frames(xfer, 1); } usbd_transfer_start(xfer); while (usbd_transfer_pending(xfer)) { cv_wait(&udev->ctrlreq_cv, xfer->xroot->xfer_mtx); } err = xfer->error; if (err) { break; } /* get actual length of DATA stage */ if (xfer->aframes < 2) { acttemp = 0; } else { acttemp = usbd_xfer_frame_len(xfer, 1); } /* check for short packet */ if (temp > acttemp) { temp = acttemp; length = temp; } if (temp > 0) { if (req->bmRequestType & UT_READ) { #if USB_HAVE_USER_IO if (flags & USB_USER_DATA_PTR) { USB_XFER_UNLOCK(xfer); err = usbd_copy_out_user(xfer->frbuffers + 1, 0, data, temp); USB_XFER_LOCK(xfer); if (err) { err = USB_ERR_INVAL; break; } } else #endif usbd_copy_out(xfer->frbuffers + 1, 0, data, temp); } } /* * Clear "frlengths[0]" so that we don't send the setup * packet again: */ usbd_xfer_set_frame_len(xfer, 0, 0); /* update length and data pointer */ length -= temp; data = USB_ADD_BYTES(data, temp); if (actlen) { (*actlen) += temp; } /* check for timeout */ delta_ticks = ticks - start_ticks; if (delta_ticks > max_ticks) { if (!err) { err = USB_ERR_TIMEOUT; } } if (err) { break; } } if (err) { /* * Make sure that the control endpoint is no longer * blocked in case of a non-transfer related error: */ usbd_transfer_stop(xfer); } USB_XFER_UNLOCK(xfer); done: usbd_sr_lock(udev); if (do_unlock) usbd_enum_unlock(udev); if ((mtx != NULL) && (mtx != &Giant)) mtx_lock(mtx); switch (err) { case USB_ERR_NORMAL_COMPLETION: case USB_ERR_SHORT_XFER: case USB_ERR_STALLED: case USB_ERR_CANCELLED: break; default: DPRINTF("I/O error - waiting a bit for TT cleanup\n"); usb_pause_mtx(mtx, hz / 16); break; } return ((usb_error_t)err); } /*------------------------------------------------------------------------* * usbd_do_request_proc - factored out code * * This function is factored out code. It does basically the same like * usbd_do_request_flags, except it will check the status of the * passed process argument before doing the USB request. If the * process is draining the USB_ERR_IOERROR code will be returned. It * is assumed that the mutex associated with the process is locked * when calling this function. *------------------------------------------------------------------------*/ usb_error_t usbd_do_request_proc(struct usb_device *udev, struct usb_process *pproc, struct usb_device_request *req, void *data, uint16_t flags, uint16_t *actlen, usb_timeout_t timeout) { usb_error_t err; uint16_t len; /* get request data length */ len = UGETW(req->wLength); /* check if the device is being detached */ if (usb_proc_is_gone(pproc)) { err = USB_ERR_IOERROR; goto done; } /* forward the USB request */ err = usbd_do_request_flags(udev, pproc->up_mtx, req, data, flags, actlen, timeout); done: /* on failure we zero the data */ /* on short packet we zero the unused data */ if ((len != 0) && (req->bmRequestType & UE_DIR_IN)) { if (err) memset(data, 0, len); else if (actlen && *actlen != len) memset(((uint8_t *)data) + *actlen, 0, len - *actlen); } return (err); } /*------------------------------------------------------------------------* * usbd_req_reset_port * * This function will instruct a USB HUB to perform a reset sequence * on the specified port number. * * Returns: * 0: Success. The USB device should now be at address zero. * Else: Failure. No USB device is present and the USB port should be * disabled. *------------------------------------------------------------------------*/ usb_error_t usbd_req_reset_port(struct usb_device *udev, struct mtx *mtx, uint8_t port) { struct usb_port_status ps; usb_error_t err; uint16_t n; uint16_t status; uint16_t change; DPRINTF("\n"); /* clear any leftover port reset changes first */ usbd_req_clear_port_feature( udev, mtx, port, UHF_C_PORT_RESET); /* assert port reset on the given port */ err = usbd_req_set_port_feature( udev, mtx, port, UHF_PORT_RESET); /* check for errors */ if (err) goto done; n = 0; while (1) { /* wait for the device to recover from reset */ usb_pause_mtx(mtx, USB_MS_TO_TICKS(usb_port_reset_delay)); n += usb_port_reset_delay; err = usbd_req_get_port_status(udev, mtx, &ps, port); if (err) goto done; status = UGETW(ps.wPortStatus); change = UGETW(ps.wPortChange); /* if the device disappeared, just give up */ if (!(status & UPS_CURRENT_CONNECT_STATUS)) goto done; /* check if reset is complete */ if (change & UPS_C_PORT_RESET) break; /* * Some Virtual Machines like VirtualBox 4.x fail to * generate a port reset change event. Check if reset * is no longer asserted. */ if (!(status & UPS_RESET)) break; /* check for timeout */ if (n > 1000) { n = 0; break; } } /* clear port reset first */ err = usbd_req_clear_port_feature( udev, mtx, port, UHF_C_PORT_RESET); if (err) goto done; /* check for timeout */ if (n == 0) { err = USB_ERR_TIMEOUT; goto done; } /* wait for the device to recover from reset */ usb_pause_mtx(mtx, USB_MS_TO_TICKS(usb_port_reset_recovery)); done: DPRINTFN(2, "port %d reset returning error=%s\n", port, usbd_errstr(err)); return (err); } /*------------------------------------------------------------------------* * usbd_req_warm_reset_port * * This function will instruct an USB HUB to perform a warm reset * sequence on the specified port number. This kind of reset is not * mandatory for LOW-, FULL- and HIGH-speed USB HUBs and is targeted * for SUPER-speed USB HUBs. * * Returns: * 0: Success. The USB device should now be available again. * Else: Failure. No USB device is present and the USB port should be * disabled. *------------------------------------------------------------------------*/ usb_error_t usbd_req_warm_reset_port(struct usb_device *udev, struct mtx *mtx, uint8_t port) { struct usb_port_status ps; usb_error_t err; uint16_t n; uint16_t status; uint16_t change; DPRINTF("\n"); err = usbd_req_get_port_status(udev, mtx, &ps, port); if (err) goto done; status = UGETW(ps.wPortStatus); switch (UPS_PORT_LINK_STATE_GET(status)) { case UPS_PORT_LS_U3: case UPS_PORT_LS_COMP_MODE: case UPS_PORT_LS_LOOPBACK: case UPS_PORT_LS_SS_INA: break; default: DPRINTF("Wrong state for warm reset\n"); return (0); } /* clear any leftover warm port reset changes first */ usbd_req_clear_port_feature(udev, mtx, port, UHF_C_BH_PORT_RESET); /* set warm port reset */ err = usbd_req_set_port_feature(udev, mtx, port, UHF_BH_PORT_RESET); if (err) goto done; n = 0; while (1) { /* wait for the device to recover from reset */ usb_pause_mtx(mtx, USB_MS_TO_TICKS(usb_port_reset_delay)); n += usb_port_reset_delay; err = usbd_req_get_port_status(udev, mtx, &ps, port); if (err) goto done; status = UGETW(ps.wPortStatus); change = UGETW(ps.wPortChange); /* if the device disappeared, just give up */ if (!(status & UPS_CURRENT_CONNECT_STATUS)) goto done; /* check if reset is complete */ if (change & UPS_C_BH_PORT_RESET) break; /* check for timeout */ if (n > 1000) { n = 0; break; } } /* clear port reset first */ err = usbd_req_clear_port_feature( udev, mtx, port, UHF_C_BH_PORT_RESET); if (err) goto done; /* check for timeout */ if (n == 0) { err = USB_ERR_TIMEOUT; goto done; } /* wait for the device to recover from reset */ usb_pause_mtx(mtx, USB_MS_TO_TICKS(usb_port_reset_recovery)); done: DPRINTFN(2, "port %d warm reset returning error=%s\n", port, usbd_errstr(err)); return (err); } /*------------------------------------------------------------------------* * usbd_req_get_desc * * This function can be used to retrieve USB descriptors. It contains * some additional logic like zeroing of missing descriptor bytes and * retrying an USB descriptor in case of failure. The "min_len" * argument specifies the minimum descriptor length. The "max_len" * argument specifies the maximum descriptor length. If the real * descriptor length is less than the minimum length the missing * byte(s) will be zeroed. The type field, the second byte of the USB * descriptor, will get forced to the correct type. If the "actlen" * pointer is non-NULL, the actual length of the transfer will get * stored in the 16-bit unsigned integer which it is pointing to. The * first byte of the descriptor will not get updated. If the "actlen" * pointer is NULL the first byte of the descriptor will get updated * to reflect the actual length instead. If "min_len" is not equal to * "max_len" then this function will try to retrive the beginning of * the descriptor and base the maximum length on the first byte of the * descriptor. * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_desc(struct usb_device *udev, struct mtx *mtx, uint16_t *actlen, void *desc, uint16_t min_len, uint16_t max_len, uint16_t id, uint8_t type, uint8_t index, uint8_t retries) { struct usb_device_request req; uint8_t *buf; usb_error_t err; DPRINTFN(4, "id=%d, type=%d, index=%d, max_len=%d\n", id, type, index, max_len); req.bmRequestType = UT_READ_DEVICE; req.bRequest = UR_GET_DESCRIPTOR; USETW2(req.wValue, type, index); USETW(req.wIndex, id); while (1) { if ((min_len < 2) || (max_len < 2)) { err = USB_ERR_INVAL; goto done; } USETW(req.wLength, min_len); err = usbd_do_request_flags(udev, mtx, &req, desc, 0, NULL, 500 /* ms */); if (err) { if (!retries) { goto done; } retries--; usb_pause_mtx(mtx, hz / 5); continue; } buf = desc; if (min_len == max_len) { /* enforce correct length */ if ((buf[0] > min_len) && (actlen == NULL)) buf[0] = min_len; /* enforce correct type */ buf[1] = type; goto done; } /* range check */ if (max_len > buf[0]) { max_len = buf[0]; } /* zero minimum data */ while (min_len > max_len) { min_len--; buf[min_len] = 0; } /* set new minimum length */ min_len = max_len; } done: if (actlen != NULL) { if (err) *actlen = 0; else *actlen = min_len; } return (err); } /*------------------------------------------------------------------------* * usbd_req_get_string_any * * This function will return the string given by "string_index" * using the first language ID. The maximum length "len" includes * the terminating zero. The "len" argument should be twice as * big pluss 2 bytes, compared with the actual maximum string length ! * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_string_any(struct usb_device *udev, struct mtx *mtx, char *buf, uint16_t len, uint8_t string_index) { char *s; uint8_t *temp; uint16_t i; uint16_t n; uint16_t c; uint8_t swap; usb_error_t err; if (len == 0) { /* should not happen */ return (USB_ERR_NORMAL_COMPLETION); } if (string_index == 0) { /* this is the language table */ buf[0] = 0; return (USB_ERR_INVAL); } if (udev->flags.no_strings) { buf[0] = 0; return (USB_ERR_STALLED); } err = usbd_req_get_string_desc (udev, mtx, buf, len, udev->langid, string_index); if (err) { buf[0] = 0; return (err); } temp = (uint8_t *)buf; if (temp[0] < 2) { /* string length is too short */ buf[0] = 0; return (USB_ERR_INVAL); } /* reserve one byte for terminating zero */ len--; /* find maximum length */ s = buf; n = (temp[0] / 2) - 1; if (n > len) { n = len; } /* skip descriptor header */ temp += 2; /* reset swap state */ swap = 3; /* convert and filter */ for (i = 0; (i != n); i++) { c = UGETW(temp + (2 * i)); /* convert from Unicode, handle buggy strings */ if (((c & 0xff00) == 0) && (swap & 1)) { /* Little Endian, default */ *s = c; swap = 1; } else if (((c & 0x00ff) == 0) && (swap & 2)) { /* Big Endian */ *s = c >> 8; swap = 2; } else { /* silently skip bad character */ continue; } /* * Filter by default - We only allow alphanumerical * and a few more to avoid any problems with scripts * and daemons. */ if (isalpha(*s) || isdigit(*s) || *s == '-' || *s == '+' || *s == ' ' || *s == '.' || *s == ',') { /* allowed */ s++; } /* silently skip bad character */ } *s = 0; /* zero terminate resulting string */ return (USB_ERR_NORMAL_COMPLETION); } /*------------------------------------------------------------------------* * usbd_req_get_string_desc * * If you don't know the language ID, consider using * "usbd_req_get_string_any()". * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_string_desc(struct usb_device *udev, struct mtx *mtx, void *sdesc, uint16_t max_len, uint16_t lang_id, uint8_t string_index) { return (usbd_req_get_desc(udev, mtx, NULL, sdesc, 2, max_len, lang_id, UDESC_STRING, string_index, 0)); } /*------------------------------------------------------------------------* * usbd_req_get_config_desc_ptr * * This function is used in device side mode to retrieve the pointer * to the generated config descriptor. This saves allocating space for * an additional config descriptor when setting the configuration. * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_descriptor_ptr(struct usb_device *udev, struct usb_config_descriptor **ppcd, uint16_t wValue) { struct usb_device_request req; usb_handle_req_t *hr_func; const void *ptr; uint16_t len; usb_error_t err; req.bmRequestType = UT_READ_DEVICE; req.bRequest = UR_GET_DESCRIPTOR; USETW(req.wValue, wValue); USETW(req.wIndex, 0); USETW(req.wLength, 0); ptr = NULL; len = 0; hr_func = usbd_get_hr_func(udev); if (hr_func == NULL) err = USB_ERR_INVAL; else { USB_BUS_LOCK(udev->bus); err = (hr_func) (udev, &req, &ptr, &len); USB_BUS_UNLOCK(udev->bus); } if (err) ptr = NULL; else if (ptr == NULL) err = USB_ERR_INVAL; *ppcd = __DECONST(struct usb_config_descriptor *, ptr); return (err); } /*------------------------------------------------------------------------* * usbd_req_get_config_desc * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_config_desc(struct usb_device *udev, struct mtx *mtx, struct usb_config_descriptor *d, uint8_t conf_index) { usb_error_t err; DPRINTFN(4, "confidx=%d\n", conf_index); err = usbd_req_get_desc(udev, mtx, NULL, d, sizeof(*d), sizeof(*d), 0, UDESC_CONFIG, conf_index, 0); if (err) { goto done; } /* Extra sanity checking */ if (UGETW(d->wTotalLength) < (uint16_t)sizeof(*d)) { err = USB_ERR_INVAL; } done: return (err); } /*------------------------------------------------------------------------* * usbd_alloc_config_desc * * This function is used to allocate a zeroed configuration * descriptor. * * Returns: * NULL: Failure * Else: Success *------------------------------------------------------------------------*/ void * usbd_alloc_config_desc(struct usb_device *udev, uint32_t size) { if (size > USB_CONFIG_MAX) { DPRINTF("Configuration descriptor too big\n"); return (NULL); } #if (USB_HAVE_FIXED_CONFIG == 0) return (malloc(size, M_USBDEV, M_ZERO | M_WAITOK)); #else memset(udev->config_data, 0, sizeof(udev->config_data)); return (udev->config_data); #endif } /*------------------------------------------------------------------------* * usbd_alloc_config_desc * * This function is used to free a configuration descriptor. *------------------------------------------------------------------------*/ void usbd_free_config_desc(struct usb_device *udev, void *ptr) { #if (USB_HAVE_FIXED_CONFIG == 0) free(ptr, M_USBDEV); #endif } /*------------------------------------------------------------------------* * usbd_req_get_config_desc_full * * This function gets the complete USB configuration descriptor and * ensures that "wTotalLength" is correct. The returned configuration * descriptor is freed by calling "usbd_free_config_desc()". * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_config_desc_full(struct usb_device *udev, struct mtx *mtx, struct usb_config_descriptor **ppcd, uint8_t index) { struct usb_config_descriptor cd; struct usb_config_descriptor *cdesc; uint32_t len; usb_error_t err; DPRINTFN(4, "index=%d\n", index); *ppcd = NULL; err = usbd_req_get_config_desc(udev, mtx, &cd, index); if (err) return (err); /* get full descriptor */ len = UGETW(cd.wTotalLength); if (len < (uint32_t)sizeof(*cdesc)) { /* corrupt descriptor */ return (USB_ERR_INVAL); } else if (len > USB_CONFIG_MAX) { DPRINTF("Configuration descriptor was truncated\n"); len = USB_CONFIG_MAX; } cdesc = usbd_alloc_config_desc(udev, len); if (cdesc == NULL) return (USB_ERR_NOMEM); err = usbd_req_get_desc(udev, mtx, NULL, cdesc, len, len, 0, UDESC_CONFIG, index, 3); if (err) { usbd_free_config_desc(udev, cdesc); return (err); } /* make sure that the device is not fooling us: */ USETW(cdesc->wTotalLength, len); *ppcd = cdesc; return (0); /* success */ } /*------------------------------------------------------------------------* * usbd_req_get_device_desc * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_device_desc(struct usb_device *udev, struct mtx *mtx, struct usb_device_descriptor *d) { DPRINTFN(4, "\n"); return (usbd_req_get_desc(udev, mtx, NULL, d, sizeof(*d), sizeof(*d), 0, UDESC_DEVICE, 0, 3)); } /*------------------------------------------------------------------------* * usbd_req_get_alt_interface_no * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_alt_interface_no(struct usb_device *udev, struct mtx *mtx, uint8_t *alt_iface_no, uint8_t iface_index) { struct usb_interface *iface = usbd_get_iface(udev, iface_index); struct usb_device_request req; if ((iface == NULL) || (iface->idesc == NULL)) return (USB_ERR_INVAL); req.bmRequestType = UT_READ_INTERFACE; req.bRequest = UR_GET_INTERFACE; USETW(req.wValue, 0); req.wIndex[0] = iface->idesc->bInterfaceNumber; req.wIndex[1] = 0; USETW(req.wLength, 1); return (usbd_do_request(udev, mtx, &req, alt_iface_no)); } /*------------------------------------------------------------------------* * usbd_req_set_alt_interface_no * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_set_alt_interface_no(struct usb_device *udev, struct mtx *mtx, uint8_t iface_index, uint8_t alt_no) { struct usb_interface *iface = usbd_get_iface(udev, iface_index); struct usb_device_request req; if ((iface == NULL) || (iface->idesc == NULL)) return (USB_ERR_INVAL); req.bmRequestType = UT_WRITE_INTERFACE; req.bRequest = UR_SET_INTERFACE; req.wValue[0] = alt_no; req.wValue[1] = 0; req.wIndex[0] = iface->idesc->bInterfaceNumber; req.wIndex[1] = 0; USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_get_device_status * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_device_status(struct usb_device *udev, struct mtx *mtx, struct usb_status *st) { struct usb_device_request req; req.bmRequestType = UT_READ_DEVICE; req.bRequest = UR_GET_STATUS; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, sizeof(*st)); return (usbd_do_request(udev, mtx, &req, st)); } /*------------------------------------------------------------------------* * usbd_req_get_hub_descriptor * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_hub_descriptor(struct usb_device *udev, struct mtx *mtx, struct usb_hub_descriptor *hd, uint8_t nports) { struct usb_device_request req; uint16_t len = (nports + 7 + (8 * 8)) / 8; req.bmRequestType = UT_READ_CLASS_DEVICE; req.bRequest = UR_GET_DESCRIPTOR; USETW2(req.wValue, UDESC_HUB, 0); USETW(req.wIndex, 0); USETW(req.wLength, len); return (usbd_do_request(udev, mtx, &req, hd)); } /*------------------------------------------------------------------------* * usbd_req_get_ss_hub_descriptor * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_ss_hub_descriptor(struct usb_device *udev, struct mtx *mtx, struct usb_hub_ss_descriptor *hd, uint8_t nports) { struct usb_device_request req; uint16_t len = sizeof(*hd) - 32 + 1 + ((nports + 7) / 8); req.bmRequestType = UT_READ_CLASS_DEVICE; req.bRequest = UR_GET_DESCRIPTOR; USETW2(req.wValue, UDESC_SS_HUB, 0); USETW(req.wIndex, 0); USETW(req.wLength, len); return (usbd_do_request(udev, mtx, &req, hd)); } /*------------------------------------------------------------------------* * usbd_req_get_hub_status * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_hub_status(struct usb_device *udev, struct mtx *mtx, struct usb_hub_status *st) { struct usb_device_request req; req.bmRequestType = UT_READ_CLASS_DEVICE; req.bRequest = UR_GET_STATUS; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, sizeof(struct usb_hub_status)); return (usbd_do_request(udev, mtx, &req, st)); } /*------------------------------------------------------------------------* * usbd_req_set_address * * This function is used to set the address for an USB device. After * port reset the USB device will respond at address zero. * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_set_address(struct usb_device *udev, struct mtx *mtx, uint16_t addr) { struct usb_device_request req; usb_error_t err; DPRINTFN(6, "setting device address=%d\n", addr); req.bmRequestType = UT_WRITE_DEVICE; req.bRequest = UR_SET_ADDRESS; USETW(req.wValue, addr); USETW(req.wIndex, 0); USETW(req.wLength, 0); err = USB_ERR_INVAL; /* check if USB controller handles set address */ if (udev->bus->methods->set_address != NULL) err = (udev->bus->methods->set_address) (udev, mtx, addr); if (err != USB_ERR_INVAL) goto done; /* Setting the address should not take more than 1 second ! */ err = usbd_do_request_flags(udev, mtx, &req, NULL, USB_DELAY_STATUS_STAGE, NULL, 1000); done: /* allow device time to set new address */ usb_pause_mtx(mtx, USB_MS_TO_TICKS(usb_set_address_settle)); return (err); } /*------------------------------------------------------------------------* * usbd_req_get_port_status * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_port_status(struct usb_device *udev, struct mtx *mtx, struct usb_port_status *ps, uint8_t port) { struct usb_device_request req; req.bmRequestType = UT_READ_CLASS_OTHER; req.bRequest = UR_GET_STATUS; USETW(req.wValue, 0); req.wIndex[0] = port; req.wIndex[1] = 0; USETW(req.wLength, sizeof *ps); return (usbd_do_request(udev, mtx, &req, ps)); } /*------------------------------------------------------------------------* * usbd_req_clear_hub_feature * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_clear_hub_feature(struct usb_device *udev, struct mtx *mtx, uint16_t sel) { struct usb_device_request req; req.bmRequestType = UT_WRITE_CLASS_DEVICE; req.bRequest = UR_CLEAR_FEATURE; USETW(req.wValue, sel); USETW(req.wIndex, 0); USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_set_hub_feature * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_set_hub_feature(struct usb_device *udev, struct mtx *mtx, uint16_t sel) { struct usb_device_request req; req.bmRequestType = UT_WRITE_CLASS_DEVICE; req.bRequest = UR_SET_FEATURE; USETW(req.wValue, sel); USETW(req.wIndex, 0); USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_set_hub_u1_timeout * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_set_hub_u1_timeout(struct usb_device *udev, struct mtx *mtx, uint8_t port, uint8_t timeout) { struct usb_device_request req; req.bmRequestType = UT_WRITE_CLASS_OTHER; req.bRequest = UR_SET_FEATURE; USETW(req.wValue, UHF_PORT_U1_TIMEOUT); req.wIndex[0] = port; req.wIndex[1] = timeout; USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_set_hub_u2_timeout * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_set_hub_u2_timeout(struct usb_device *udev, struct mtx *mtx, uint8_t port, uint8_t timeout) { struct usb_device_request req; req.bmRequestType = UT_WRITE_CLASS_OTHER; req.bRequest = UR_SET_FEATURE; USETW(req.wValue, UHF_PORT_U2_TIMEOUT); req.wIndex[0] = port; req.wIndex[1] = timeout; USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_set_hub_depth * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_set_hub_depth(struct usb_device *udev, struct mtx *mtx, uint16_t depth) { struct usb_device_request req; req.bmRequestType = UT_WRITE_CLASS_DEVICE; req.bRequest = UR_SET_HUB_DEPTH; USETW(req.wValue, depth); USETW(req.wIndex, 0); USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_clear_port_feature * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_clear_port_feature(struct usb_device *udev, struct mtx *mtx, uint8_t port, uint16_t sel) { struct usb_device_request req; req.bmRequestType = UT_WRITE_CLASS_OTHER; req.bRequest = UR_CLEAR_FEATURE; USETW(req.wValue, sel); req.wIndex[0] = port; req.wIndex[1] = 0; USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_set_port_feature * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_set_port_feature(struct usb_device *udev, struct mtx *mtx, uint8_t port, uint16_t sel) { struct usb_device_request req; req.bmRequestType = UT_WRITE_CLASS_OTHER; req.bRequest = UR_SET_FEATURE; USETW(req.wValue, sel); req.wIndex[0] = port; req.wIndex[1] = 0; USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_set_protocol * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_set_protocol(struct usb_device *udev, struct mtx *mtx, uint8_t iface_index, uint16_t report) { struct usb_interface *iface = usbd_get_iface(udev, iface_index); struct usb_device_request req; if ((iface == NULL) || (iface->idesc == NULL)) { return (USB_ERR_INVAL); } DPRINTFN(5, "iface=%p, report=%d, endpt=%d\n", iface, report, iface->idesc->bInterfaceNumber); req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UR_SET_PROTOCOL; USETW(req.wValue, report); req.wIndex[0] = iface->idesc->bInterfaceNumber; req.wIndex[1] = 0; USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_set_report * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_set_report(struct usb_device *udev, struct mtx *mtx, void *data, uint16_t len, uint8_t iface_index, uint8_t type, uint8_t id) { struct usb_interface *iface = usbd_get_iface(udev, iface_index); struct usb_device_request req; if ((iface == NULL) || (iface->idesc == NULL)) { return (USB_ERR_INVAL); } DPRINTFN(5, "len=%d\n", len); req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UR_SET_REPORT; USETW2(req.wValue, type, id); req.wIndex[0] = iface->idesc->bInterfaceNumber; req.wIndex[1] = 0; USETW(req.wLength, len); return (usbd_do_request(udev, mtx, &req, data)); } /*------------------------------------------------------------------------* * usbd_req_get_report * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_report(struct usb_device *udev, struct mtx *mtx, void *data, uint16_t len, uint8_t iface_index, uint8_t type, uint8_t id) { struct usb_interface *iface = usbd_get_iface(udev, iface_index); struct usb_device_request req; if ((iface == NULL) || (iface->idesc == NULL)) { return (USB_ERR_INVAL); } DPRINTFN(5, "len=%d\n", len); req.bmRequestType = UT_READ_CLASS_INTERFACE; req.bRequest = UR_GET_REPORT; USETW2(req.wValue, type, id); req.wIndex[0] = iface->idesc->bInterfaceNumber; req.wIndex[1] = 0; USETW(req.wLength, len); return (usbd_do_request(udev, mtx, &req, data)); } /*------------------------------------------------------------------------* * usbd_req_set_idle * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_set_idle(struct usb_device *udev, struct mtx *mtx, uint8_t iface_index, uint8_t duration, uint8_t id) { struct usb_interface *iface = usbd_get_iface(udev, iface_index); struct usb_device_request req; if ((iface == NULL) || (iface->idesc == NULL)) { return (USB_ERR_INVAL); } DPRINTFN(5, "%d %d\n", duration, id); req.bmRequestType = UT_WRITE_CLASS_INTERFACE; req.bRequest = UR_SET_IDLE; USETW2(req.wValue, duration, id); req.wIndex[0] = iface->idesc->bInterfaceNumber; req.wIndex[1] = 0; USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_get_report_descriptor * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_report_descriptor(struct usb_device *udev, struct mtx *mtx, void *d, uint16_t size, uint8_t iface_index) { struct usb_interface *iface = usbd_get_iface(udev, iface_index); struct usb_device_request req; if ((iface == NULL) || (iface->idesc == NULL)) { return (USB_ERR_INVAL); } req.bmRequestType = UT_READ_INTERFACE; req.bRequest = UR_GET_DESCRIPTOR; USETW2(req.wValue, UDESC_REPORT, 0); /* report id should be 0 */ req.wIndex[0] = iface->idesc->bInterfaceNumber; req.wIndex[1] = 0; USETW(req.wLength, size); return (usbd_do_request(udev, mtx, &req, d)); } /*------------------------------------------------------------------------* * usbd_req_set_config * * This function is used to select the current configuration number in * both USB device side mode and USB host side mode. When setting the * configuration the function of the interfaces can change. * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_set_config(struct usb_device *udev, struct mtx *mtx, uint8_t conf) { struct usb_device_request req; DPRINTF("setting config %d\n", conf); /* do "set configuration" request */ req.bmRequestType = UT_WRITE_DEVICE; req.bRequest = UR_SET_CONFIG; req.wValue[0] = conf; req.wValue[1] = 0; USETW(req.wIndex, 0); USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_get_config * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_get_config(struct usb_device *udev, struct mtx *mtx, uint8_t *pconf) { struct usb_device_request req; req.bmRequestType = UT_READ_DEVICE; req.bRequest = UR_GET_CONFIG; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, 1); return (usbd_do_request(udev, mtx, &req, pconf)); } /*------------------------------------------------------------------------* * usbd_setup_device_desc *------------------------------------------------------------------------*/ usb_error_t usbd_setup_device_desc(struct usb_device *udev, struct mtx *mtx) { usb_error_t err; /* * Get the first 8 bytes of the device descriptor ! * * NOTE: "usbd_do_request()" will check the device descriptor * next time we do a request to see if the maximum packet size * changed! The 8 first bytes of the device descriptor * contains the maximum packet size to use on control endpoint * 0. If this value is different from "USB_MAX_IPACKET" a new * USB control request will be setup! */ switch (udev->speed) { case USB_SPEED_FULL: if (usb_full_ddesc != 0) { /* get full device descriptor */ err = usbd_req_get_device_desc(udev, mtx, &udev->ddesc); if (err == 0) break; } /* get partial device descriptor, some devices crash on this */ err = usbd_req_get_desc(udev, mtx, NULL, &udev->ddesc, USB_MAX_IPACKET, USB_MAX_IPACKET, 0, UDESC_DEVICE, 0, 0); if (err != 0) break; /* get the full device descriptor */ err = usbd_req_get_device_desc(udev, mtx, &udev->ddesc); break; default: DPRINTF("Minimum bMaxPacketSize is large enough " "to hold the complete device descriptor or " "only one bMaxPacketSize choice\n"); /* get the full device descriptor */ err = usbd_req_get_device_desc(udev, mtx, &udev->ddesc); /* try one more time, if error */ if (err != 0) err = usbd_req_get_device_desc(udev, mtx, &udev->ddesc); break; } if (err != 0) { DPRINTFN(0, "getting device descriptor " "at addr %d failed, %s\n", udev->address, usbd_errstr(err)); return (err); } DPRINTF("adding unit addr=%d, rev=%02x, class=%d, " "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n", udev->address, UGETW(udev->ddesc.bcdUSB), udev->ddesc.bDeviceClass, udev->ddesc.bDeviceSubClass, udev->ddesc.bDeviceProtocol, udev->ddesc.bMaxPacketSize, udev->ddesc.bLength, udev->speed); return (err); } /*------------------------------------------------------------------------* * usbd_req_re_enumerate * * NOTE: After this function returns the hardware is in the * unconfigured state! The application is responsible for setting a * new configuration. * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_re_enumerate(struct usb_device *udev, struct mtx *mtx) { struct usb_device *parent_hub; usb_error_t err; uint8_t old_addr; uint8_t do_retry = 1; if (udev->flags.usb_mode != USB_MODE_HOST) { return (USB_ERR_INVAL); } old_addr = udev->address; parent_hub = udev->parent_hub; if (parent_hub == NULL) { return (USB_ERR_INVAL); } retry: #if USB_HAVE_TT_SUPPORT /* * Try to reset the High Speed parent HUB of a LOW- or FULL- * speed device, if any. */ if (udev->parent_hs_hub != NULL && udev->speed != USB_SPEED_HIGH) { DPRINTF("Trying to reset parent High Speed TT.\n"); if (udev->parent_hs_hub == parent_hub && (uhub_count_active_host_ports(parent_hub, USB_SPEED_LOW) + uhub_count_active_host_ports(parent_hub, USB_SPEED_FULL)) == 1) { /* we can reset the whole TT */ err = usbd_req_reset_tt(parent_hub, NULL, udev->hs_port_no); } else { /* only reset a particular device and endpoint */ err = usbd_req_clear_tt_buffer(udev->parent_hs_hub, NULL, udev->hs_port_no, old_addr, UE_CONTROL, 0); } if (err) { DPRINTF("Resetting parent High " "Speed TT failed (%s).\n", usbd_errstr(err)); } } #endif /* Try to warm reset first */ if (parent_hub->speed == USB_SPEED_SUPER) usbd_req_warm_reset_port(parent_hub, mtx, udev->port_no); /* Try to reset the parent HUB port. */ err = usbd_req_reset_port(parent_hub, mtx, udev->port_no); if (err) { DPRINTFN(0, "addr=%d, port reset failed, %s\n", old_addr, usbd_errstr(err)); goto done; } /* * After that the port has been reset our device should be at * address zero: */ udev->address = USB_START_ADDR; /* reset "bMaxPacketSize" */ udev->ddesc.bMaxPacketSize = USB_MAX_IPACKET; /* reset USB state */ usb_set_device_state(udev, USB_STATE_POWERED); /* * Restore device address: */ err = usbd_req_set_address(udev, mtx, old_addr); if (err) { /* XXX ignore any errors! */ DPRINTFN(0, "addr=%d, set address failed! (%s, ignored)\n", old_addr, usbd_errstr(err)); } /* * Restore device address, if the controller driver did not * set a new one: */ if (udev->address == USB_START_ADDR) udev->address = old_addr; /* setup the device descriptor and the initial "wMaxPacketSize" */ err = usbd_setup_device_desc(udev, mtx); done: if (err && do_retry) { /* give the USB firmware some time to load */ usb_pause_mtx(mtx, hz / 2); /* no more retries after this retry */ do_retry = 0; /* try again */ goto retry; } /* restore address */ if (udev->address == USB_START_ADDR) udev->address = old_addr; /* update state, if successful */ if (err == 0) usb_set_device_state(udev, USB_STATE_ADDRESSED); return (err); } /*------------------------------------------------------------------------* * usbd_req_clear_device_feature * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_clear_device_feature(struct usb_device *udev, struct mtx *mtx, uint16_t sel) { struct usb_device_request req; req.bmRequestType = UT_WRITE_DEVICE; req.bRequest = UR_CLEAR_FEATURE; USETW(req.wValue, sel); USETW(req.wIndex, 0); USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_set_device_feature * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_set_device_feature(struct usb_device *udev, struct mtx *mtx, uint16_t sel) { struct usb_device_request req; req.bmRequestType = UT_WRITE_DEVICE; req.bRequest = UR_SET_FEATURE; USETW(req.wValue, sel); USETW(req.wIndex, 0); USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_reset_tt * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_reset_tt(struct usb_device *udev, struct mtx *mtx, uint8_t port) { struct usb_device_request req; /* For single TT HUBs the port should be 1 */ if (udev->ddesc.bDeviceClass == UDCLASS_HUB && udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBSTT) port = 1; req.bmRequestType = UT_WRITE_CLASS_OTHER; req.bRequest = UR_RESET_TT; USETW(req.wValue, 0); req.wIndex[0] = port; req.wIndex[1] = 0; USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_clear_tt_buffer * * For single TT HUBs the port should be 1. * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_clear_tt_buffer(struct usb_device *udev, struct mtx *mtx, uint8_t port, uint8_t addr, uint8_t type, uint8_t endpoint) { struct usb_device_request req; uint16_t wValue; /* For single TT HUBs the port should be 1 */ if (udev->ddesc.bDeviceClass == UDCLASS_HUB && udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBSTT) port = 1; wValue = (endpoint & 0xF) | ((addr & 0x7F) << 4) | ((endpoint & 0x80) << 8) | ((type & 3) << 12); req.bmRequestType = UT_WRITE_CLASS_OTHER; req.bRequest = UR_CLEAR_TT_BUFFER; USETW(req.wValue, wValue); req.wIndex[0] = port; req.wIndex[1] = 0; USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_set_port_link_state * * USB 3.0 specific request * * Returns: * 0: Success * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_set_port_link_state(struct usb_device *udev, struct mtx *mtx, uint8_t port, uint8_t link_state) { struct usb_device_request req; req.bmRequestType = UT_WRITE_CLASS_OTHER; req.bRequest = UR_SET_FEATURE; USETW(req.wValue, UHF_PORT_LINK_STATE); req.wIndex[0] = port; req.wIndex[1] = link_state; USETW(req.wLength, 0); return (usbd_do_request(udev, mtx, &req, 0)); } /*------------------------------------------------------------------------* * usbd_req_set_lpm_info * * USB 2.0 specific request for Link Power Management. * * Returns: * 0: Success * USB_ERR_PENDING_REQUESTS: NYET * USB_ERR_TIMEOUT: TIMEOUT * USB_ERR_STALL: STALL * Else: Failure *------------------------------------------------------------------------*/ usb_error_t usbd_req_set_lpm_info(struct usb_device *udev, struct mtx *mtx, uint8_t port, uint8_t besl, uint8_t addr, uint8_t rwe) { struct usb_device_request req; usb_error_t err; uint8_t buf[1]; req.bmRequestType = UT_WRITE_CLASS_OTHER; req.bRequest = UR_SET_AND_TEST; USETW(req.wValue, UHF_PORT_L1); req.wIndex[0] = (port & 0xF) | ((besl & 0xF) << 4); req.wIndex[1] = (addr & 0x7F) | (rwe ? 0x80 : 0x00); USETW(req.wLength, sizeof(buf)); /* set default value in case of short transfer */ buf[0] = 0x00; err = usbd_do_request(udev, mtx, &req, buf); if (err) return (err); switch (buf[0]) { case 0x00: /* SUCCESS */ break; case 0x10: /* NYET */ err = USB_ERR_PENDING_REQUESTS; break; case 0x11: /* TIMEOUT */ err = USB_ERR_TIMEOUT; break; case 0x30: /* STALL */ err = USB_ERR_STALLED; break; default: /* reserved */ err = USB_ERR_IOERROR; break; } return (err); } Index: head/sys/dev/usb/wlan/if_rsu.c =================================================================== --- head/sys/dev/usb/wlan/if_rsu.c (revision 276700) +++ head/sys/dev/usb/wlan/if_rsu.c (revision 276701) @@ -1,2472 +1,2472 @@ /* $OpenBSD: if_rsu.c,v 1.17 2013/04/15 09:23:01 mglocker Exp $ */ /*- * Copyright (c) 2010 Damien Bergamini * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include __FBSDID("$FreeBSD$"); /* * Driver for Realtek RTL8188SU/RTL8191SU/RTL8192SU. * * TODO: * o 11n support * o h/w crypto * o hostap / ibss / mesh */ #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 "usbdevs.h" #define USB_DEBUG_VAR rsu_debug #include #include #ifdef USB_DEBUG static int rsu_debug = 0; SYSCTL_NODE(_hw_usb, OID_AUTO, rsu, CTLFLAG_RW, 0, "USB rsu"); -SYSCTL_INT(_hw_usb_rsu, OID_AUTO, debug, CTLFLAG_RW, &rsu_debug, 0, +SYSCTL_INT(_hw_usb_rsu, OID_AUTO, debug, CTLFLAG_RWTUN, &rsu_debug, 0, "Debug level"); #endif static const STRUCT_USB_HOST_ID rsu_devs[] = { #define RSU_HT_NOT_SUPPORTED 0 #define RSU_HT_SUPPORTED 1 #define RSU_DEV_HT(v,p) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, \ RSU_HT_SUPPORTED) } #define RSU_DEV(v,p) { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, \ RSU_HT_NOT_SUPPORTED) } RSU_DEV(ASUS, RTL8192SU), RSU_DEV(AZUREWAVE, RTL8192SU_4), RSU_DEV_HT(ACCTON, RTL8192SU), RSU_DEV_HT(ASUS, USBN10), RSU_DEV_HT(AZUREWAVE, RTL8192SU_1), RSU_DEV_HT(AZUREWAVE, RTL8192SU_2), RSU_DEV_HT(AZUREWAVE, RTL8192SU_3), RSU_DEV_HT(AZUREWAVE, RTL8192SU_5), RSU_DEV_HT(BELKIN, RTL8192SU_1), RSU_DEV_HT(BELKIN, RTL8192SU_2), RSU_DEV_HT(BELKIN, RTL8192SU_3), RSU_DEV_HT(CONCEPTRONIC2, RTL8192SU_1), RSU_DEV_HT(CONCEPTRONIC2, RTL8192SU_2), RSU_DEV_HT(CONCEPTRONIC2, RTL8192SU_3), RSU_DEV_HT(COREGA, RTL8192SU), RSU_DEV_HT(DLINK2, DWA131A1), RSU_DEV_HT(DLINK2, RTL8192SU_1), RSU_DEV_HT(DLINK2, RTL8192SU_2), RSU_DEV_HT(EDIMAX, RTL8192SU_1), RSU_DEV_HT(EDIMAX, RTL8192SU_2), RSU_DEV_HT(EDIMAX, EW7622UMN), RSU_DEV_HT(GUILLEMOT, HWGUN54), RSU_DEV_HT(GUILLEMOT, HWNUM300), RSU_DEV_HT(HAWKING, RTL8192SU_1), RSU_DEV_HT(HAWKING, RTL8192SU_2), RSU_DEV_HT(PLANEX2, GWUSNANO), RSU_DEV_HT(REALTEK, RTL8171), RSU_DEV_HT(REALTEK, RTL8172), RSU_DEV_HT(REALTEK, RTL8173), RSU_DEV_HT(REALTEK, RTL8174), RSU_DEV_HT(REALTEK, RTL8192SU), RSU_DEV_HT(REALTEK, RTL8712), RSU_DEV_HT(REALTEK, RTL8713), RSU_DEV_HT(SENAO, RTL8192SU_1), RSU_DEV_HT(SENAO, RTL8192SU_2), RSU_DEV_HT(SITECOMEU, WL349V1), RSU_DEV_HT(SITECOMEU, WL353), RSU_DEV_HT(SWEEX2, LW154), RSU_DEV_HT(TRENDNET, TEW646UBH), #undef RSU_DEV_HT #undef RSU_DEV }; static device_probe_t rsu_match; static device_attach_t rsu_attach; static device_detach_t rsu_detach; static usb_callback_t rsu_bulk_tx_callback_be_bk; static usb_callback_t rsu_bulk_tx_callback_vi_vo; static usb_callback_t rsu_bulk_rx_callback; static usb_error_t rsu_do_request(struct rsu_softc *, struct usb_device_request *, void *); static struct ieee80211vap * rsu_vap_create(struct ieee80211com *, const char name[], int, enum ieee80211_opmode, int, const uint8_t bssid[], const uint8_t mac[]); static void rsu_vap_delete(struct ieee80211vap *); static void rsu_scan_start(struct ieee80211com *); static void rsu_scan_end(struct ieee80211com *); static void rsu_set_channel(struct ieee80211com *); static void rsu_update_mcast(struct ifnet *); static int rsu_alloc_rx_list(struct rsu_softc *); static void rsu_free_rx_list(struct rsu_softc *); static int rsu_alloc_tx_list(struct rsu_softc *); static void rsu_free_tx_list(struct rsu_softc *); static void rsu_free_list(struct rsu_softc *, struct rsu_data [], int); static struct rsu_data *_rsu_getbuf(struct rsu_softc *); static struct rsu_data *rsu_getbuf(struct rsu_softc *); static int rsu_write_region_1(struct rsu_softc *, uint16_t, uint8_t *, int); static void rsu_write_1(struct rsu_softc *, uint16_t, uint8_t); static void rsu_write_2(struct rsu_softc *, uint16_t, uint16_t); static void rsu_write_4(struct rsu_softc *, uint16_t, uint32_t); static int rsu_read_region_1(struct rsu_softc *, uint16_t, uint8_t *, int); static uint8_t rsu_read_1(struct rsu_softc *, uint16_t); static uint16_t rsu_read_2(struct rsu_softc *, uint16_t); static uint32_t rsu_read_4(struct rsu_softc *, uint16_t); static int rsu_fw_iocmd(struct rsu_softc *, uint32_t); static uint8_t rsu_efuse_read_1(struct rsu_softc *, uint16_t); static int rsu_read_rom(struct rsu_softc *); static int rsu_fw_cmd(struct rsu_softc *, uint8_t, void *, int); static void rsu_calib_task(void *, int); static int rsu_newstate(struct ieee80211vap *, enum ieee80211_state, int); #ifdef notyet static void rsu_set_key(struct rsu_softc *, const struct ieee80211_key *); static void rsu_delete_key(struct rsu_softc *, const struct ieee80211_key *); #endif static int rsu_site_survey(struct rsu_softc *, struct ieee80211vap *); static int rsu_join_bss(struct rsu_softc *, struct ieee80211_node *); static int rsu_disconnect(struct rsu_softc *); static void rsu_event_survey(struct rsu_softc *, uint8_t *, int); static void rsu_event_join_bss(struct rsu_softc *, uint8_t *, int); static void rsu_rx_event(struct rsu_softc *, uint8_t, uint8_t *, int); static void rsu_rx_multi_event(struct rsu_softc *, uint8_t *, int); static int8_t rsu_get_rssi(struct rsu_softc *, int, void *); static struct mbuf * rsu_rx_frame(struct rsu_softc *, uint8_t *, int, int *); static struct mbuf * rsu_rx_multi_frame(struct rsu_softc *, uint8_t *, int, int *); static struct mbuf * rsu_rxeof(struct usb_xfer *, struct rsu_data *, int *); static void rsu_txeof(struct usb_xfer *, struct rsu_data *); static int rsu_raw_xmit(struct ieee80211_node *, struct mbuf *, const struct ieee80211_bpf_params *); static void rsu_init(void *); static void rsu_init_locked(struct rsu_softc *); static int rsu_tx_start(struct rsu_softc *, struct ieee80211_node *, struct mbuf *, struct rsu_data *); static void rsu_start(struct ifnet *); static void rsu_start_locked(struct ifnet *); static int rsu_ioctl(struct ifnet *, u_long, caddr_t); static void rsu_stop(struct ifnet *, int); static void rsu_stop_locked(struct ifnet *, int); static void rsu_ms_delay(struct rsu_softc *); static device_method_t rsu_methods[] = { DEVMETHOD(device_probe, rsu_match), DEVMETHOD(device_attach, rsu_attach), DEVMETHOD(device_detach, rsu_detach), DEVMETHOD_END }; static driver_t rsu_driver = { .name = "rsu", .methods = rsu_methods, .size = sizeof(struct rsu_softc) }; static devclass_t rsu_devclass; DRIVER_MODULE(rsu, uhub, rsu_driver, rsu_devclass, NULL, 0); MODULE_DEPEND(rsu, wlan, 1, 1, 1); MODULE_DEPEND(rsu, usb, 1, 1, 1); MODULE_DEPEND(rsu, firmware, 1, 1, 1); MODULE_VERSION(rsu, 1); static uint8_t rsu_wme_ac_xfer_map[4] = { [WME_AC_BE] = RSU_BULK_TX_BE_BK, [WME_AC_BK] = RSU_BULK_TX_BE_BK, [WME_AC_VI] = RSU_BULK_TX_VI_VO, [WME_AC_VO] = RSU_BULK_TX_VI_VO, }; static const struct usb_config rsu_config[RSU_N_TRANSFER] = { [RSU_BULK_RX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = RSU_RXBUFSZ, .flags = { .pipe_bof = 1, .short_xfer_ok = 1 }, .callback = rsu_bulk_rx_callback }, [RSU_BULK_TX_BE_BK] = { .type = UE_BULK, .endpoint = 0x06, .direction = UE_DIR_OUT, .bufsize = RSU_TXBUFSZ, .flags = { .ext_buffer = 1, .pipe_bof = 1, .force_short_xfer = 1 }, .callback = rsu_bulk_tx_callback_be_bk, .timeout = RSU_TX_TIMEOUT }, [RSU_BULK_TX_VI_VO] = { .type = UE_BULK, .endpoint = 0x04, .direction = UE_DIR_OUT, .bufsize = RSU_TXBUFSZ, .flags = { .ext_buffer = 1, .pipe_bof = 1, .force_short_xfer = 1 }, .callback = rsu_bulk_tx_callback_vi_vo, .timeout = RSU_TX_TIMEOUT }, }; static int rsu_match(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); if (uaa->usb_mode != USB_MODE_HOST || uaa->info.bIfaceIndex != 0 || uaa->info.bConfigIndex != 0) return (ENXIO); return (usbd_lookup_id_by_uaa(rsu_devs, sizeof(rsu_devs), uaa)); } static int rsu_attach(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); struct rsu_softc *sc = device_get_softc(self); struct ifnet *ifp; struct ieee80211com *ic; int error; uint8_t iface_index, bands; device_set_usb_desc(self); sc->sc_udev = uaa->device; sc->sc_dev = self; mtx_init(&sc->sc_mtx, device_get_nameunit(self), MTX_NETWORK_LOCK, MTX_DEF); TIMEOUT_TASK_INIT(taskqueue_thread, &sc->calib_task, 0, rsu_calib_task, sc); /* Allocate Tx/Rx buffers. */ error = rsu_alloc_rx_list(sc); if (error != 0) { device_printf(sc->sc_dev, "could not allocate Rx buffers\n"); goto fail_usb; } error = rsu_alloc_tx_list(sc); if (error != 0) { device_printf(sc->sc_dev, "could not allocate Tx buffers\n"); rsu_free_rx_list(sc); goto fail_usb; } iface_index = 0; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, rsu_config, RSU_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(sc->sc_dev, "could not allocate USB transfers, err=%s\n", usbd_errstr(error)); goto fail_usb; } RSU_LOCK(sc); /* Read chip revision. */ sc->cut = MS(rsu_read_4(sc, R92S_PMC_FSM), R92S_PMC_FSM_CUT); if (sc->cut != 3) sc->cut = (sc->cut >> 1) + 1; error = rsu_read_rom(sc); RSU_UNLOCK(sc); if (error != 0) { device_printf(self, "could not read ROM\n"); goto fail_rom; } IEEE80211_ADDR_COPY(sc->sc_bssid, &sc->rom[0x12]); device_printf(self, "MAC/BB RTL8712 cut %d\n", sc->cut); ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211); if (ifp == NULL) { device_printf(self, "cannot allocate interface\n"); goto fail_ifalloc; } ic = ifp->if_l2com; ifp->if_softc = sc; if_initname(ifp, "rsu", device_get_unit(self)); ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; ifp->if_init = rsu_init; ifp->if_ioctl = rsu_ioctl; ifp->if_start = rsu_start; IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen); ifp->if_snd.ifq_drv_maxlen = ifqmaxlen; IFQ_SET_READY(&ifp->if_snd); ifp->if_capabilities |= IFCAP_RXCSUM; ifp->if_capenable |= IFCAP_RXCSUM; ifp->if_hwassist = CSUM_TCP; ic->ic_ifp = ifp; ic->ic_phytype = IEEE80211_T_OFDM; /* Not only, but not used. */ ic->ic_opmode = IEEE80211_M_STA; /* Default to BSS mode. */ /* Set device capabilities. */ ic->ic_caps = IEEE80211_C_STA | /* station mode */ IEEE80211_C_BGSCAN | /* Background scan. */ IEEE80211_C_SHPREAMBLE | /* Short preamble supported. */ IEEE80211_C_SHSLOT | /* Short slot time supported. */ IEEE80211_C_WPA; /* WPA/RSN. */ #if 0 /* Check if HT support is present. */ if (usb_lookup(rsu_devs_noht, uaa->vendor, uaa->product) == NULL) { /* Set HT capabilities. */ ic->ic_htcaps = IEEE80211_HTCAP_CBW20_40 | IEEE80211_HTCAP_DSSSCCK40; /* Set supported HT rates. */ for (i = 0; i < 2; i++) ic->ic_sup_mcs[i] = 0xff; } #endif /* Set supported .11b and .11g rates. */ bands = 0; setbit(&bands, IEEE80211_MODE_11B); setbit(&bands, IEEE80211_MODE_11G); ieee80211_init_channels(ic, NULL, &bands); ieee80211_ifattach(ic, sc->sc_bssid); ic->ic_raw_xmit = rsu_raw_xmit; ic->ic_scan_start = rsu_scan_start; ic->ic_scan_end = rsu_scan_end; ic->ic_set_channel = rsu_set_channel; ic->ic_vap_create = rsu_vap_create; ic->ic_vap_delete = rsu_vap_delete; ic->ic_update_mcast = rsu_update_mcast; ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap), RSU_TX_RADIOTAP_PRESENT, &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap), RSU_RX_RADIOTAP_PRESENT); if (bootverbose) ieee80211_announce(ic); return (0); fail_ifalloc: fail_rom: usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER); fail_usb: mtx_destroy(&sc->sc_mtx); return (ENXIO); } static int rsu_detach(device_t self) { struct rsu_softc *sc = device_get_softc(self); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; rsu_stop(ifp, 1); usbd_transfer_unsetup(sc->sc_xfer, RSU_N_TRANSFER); ieee80211_ifdetach(ic); taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task); /* Free Tx/Rx buffers. */ rsu_free_tx_list(sc); rsu_free_rx_list(sc); if_free(ifp); mtx_destroy(&sc->sc_mtx); return (0); } static usb_error_t rsu_do_request(struct rsu_softc *sc, struct usb_device_request *req, void *data) { usb_error_t err; int ntries = 10; RSU_ASSERT_LOCKED(sc); while (ntries--) { err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx, req, data, 0, NULL, 250 /* ms */); if (err == 0 || err == USB_ERR_NOT_CONFIGURED) break; DPRINTFN(1, "Control request failed, %s (retrying)\n", usbd_errstr(err)); usb_pause_mtx(&sc->sc_mtx, hz / 100); } return (err); } static struct ieee80211vap * rsu_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit, enum ieee80211_opmode opmode, int flags, const uint8_t bssid[IEEE80211_ADDR_LEN], const uint8_t mac[IEEE80211_ADDR_LEN]) { struct rsu_vap *uvp; struct ieee80211vap *vap; if (!TAILQ_EMPTY(&ic->ic_vaps)) /* only one at a time */ return (NULL); uvp = (struct rsu_vap *) malloc(sizeof(struct rsu_vap), M_80211_VAP, M_NOWAIT | M_ZERO); if (uvp == NULL) return (NULL); vap = &uvp->vap; if (ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac) != 0) { /* out of memory */ free(uvp, M_80211_VAP); return (NULL); } /* override state transition machine */ uvp->newstate = vap->iv_newstate; vap->iv_newstate = rsu_newstate; /* complete setup */ ieee80211_vap_attach(vap, ieee80211_media_change, ieee80211_media_status); ic->ic_opmode = opmode; return (vap); } static void rsu_vap_delete(struct ieee80211vap *vap) { struct rsu_vap *uvp = RSU_VAP(vap); ieee80211_vap_detach(vap); free(uvp, M_80211_VAP); } static void rsu_scan_start(struct ieee80211com *ic) { int error; struct ifnet *ifp = ic->ic_ifp; struct rsu_softc *sc = ifp->if_softc; /* Scanning is done by the firmware. */ RSU_LOCK(sc); error = rsu_site_survey(sc, TAILQ_FIRST(&ic->ic_vaps)); RSU_UNLOCK(sc); if (error != 0) device_printf(sc->sc_dev, "could not send site survey command\n"); } static void rsu_scan_end(struct ieee80211com *ic) { /* Nothing to do here. */ } static void rsu_set_channel(struct ieee80211com *ic __unused) { /* We are unable to switch channels, yet. */ } static void rsu_update_mcast(struct ifnet *ifp) { /* XXX do nothing? */ } static int rsu_alloc_list(struct rsu_softc *sc, struct rsu_data data[], int ndata, int maxsz) { int i, error; for (i = 0; i < ndata; i++) { struct rsu_data *dp = &data[i]; dp->sc = sc; dp->m = NULL; dp->buf = malloc(maxsz, M_USBDEV, M_NOWAIT); if (dp->buf == NULL) { device_printf(sc->sc_dev, "could not allocate buffer\n"); error = ENOMEM; goto fail; } dp->ni = NULL; } return (0); fail: rsu_free_list(sc, data, ndata); return (error); } static int rsu_alloc_rx_list(struct rsu_softc *sc) { int error, i; error = rsu_alloc_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT, RSU_RXBUFSZ); if (error != 0) return (error); STAILQ_INIT(&sc->sc_rx_active); STAILQ_INIT(&sc->sc_rx_inactive); for (i = 0; i < RSU_RX_LIST_COUNT; i++) STAILQ_INSERT_HEAD(&sc->sc_rx_inactive, &sc->sc_rx[i], next); return (0); } static int rsu_alloc_tx_list(struct rsu_softc *sc) { int error, i; error = rsu_alloc_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT, RSU_TXBUFSZ); if (error != 0) return (error); STAILQ_INIT(&sc->sc_tx_inactive); for (i = 0; i != RSU_N_TRANSFER; i++) { STAILQ_INIT(&sc->sc_tx_active[i]); STAILQ_INIT(&sc->sc_tx_pending[i]); } for (i = 0; i < RSU_TX_LIST_COUNT; i++) { STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, &sc->sc_tx[i], next); } return (0); } static void rsu_free_tx_list(struct rsu_softc *sc) { int i; /* prevent further allocations from TX list(s) */ STAILQ_INIT(&sc->sc_tx_inactive); for (i = 0; i != RSU_N_TRANSFER; i++) { STAILQ_INIT(&sc->sc_tx_active[i]); STAILQ_INIT(&sc->sc_tx_pending[i]); } rsu_free_list(sc, sc->sc_tx, RSU_TX_LIST_COUNT); } static void rsu_free_rx_list(struct rsu_softc *sc) { /* prevent further allocations from RX list(s) */ STAILQ_INIT(&sc->sc_rx_inactive); STAILQ_INIT(&sc->sc_rx_active); rsu_free_list(sc, sc->sc_rx, RSU_RX_LIST_COUNT); } static void rsu_free_list(struct rsu_softc *sc, struct rsu_data data[], int ndata) { int i; for (i = 0; i < ndata; i++) { struct rsu_data *dp = &data[i]; if (dp->buf != NULL) { free(dp->buf, M_USBDEV); dp->buf = NULL; } if (dp->ni != NULL) { ieee80211_free_node(dp->ni); dp->ni = NULL; } } } static struct rsu_data * _rsu_getbuf(struct rsu_softc *sc) { struct rsu_data *bf; bf = STAILQ_FIRST(&sc->sc_tx_inactive); if (bf != NULL) STAILQ_REMOVE_HEAD(&sc->sc_tx_inactive, next); else bf = NULL; if (bf == NULL) DPRINTF("out of xmit buffers\n"); return (bf); } static struct rsu_data * rsu_getbuf(struct rsu_softc *sc) { struct rsu_data *bf; RSU_ASSERT_LOCKED(sc); bf = _rsu_getbuf(sc); if (bf == NULL) { struct ifnet *ifp = sc->sc_ifp; DPRINTF("stop queue\n"); ifp->if_drv_flags |= IFF_DRV_OACTIVE; } return (bf); } static int rsu_write_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf, int len) { usb_device_request_t req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = R92S_REQ_REGS; USETW(req.wValue, addr); USETW(req.wIndex, 0); USETW(req.wLength, len); return (rsu_do_request(sc, &req, buf)); } static void rsu_write_1(struct rsu_softc *sc, uint16_t addr, uint8_t val) { rsu_write_region_1(sc, addr, &val, 1); } static void rsu_write_2(struct rsu_softc *sc, uint16_t addr, uint16_t val) { val = htole16(val); rsu_write_region_1(sc, addr, (uint8_t *)&val, 2); } static void rsu_write_4(struct rsu_softc *sc, uint16_t addr, uint32_t val) { val = htole32(val); rsu_write_region_1(sc, addr, (uint8_t *)&val, 4); } static int rsu_read_region_1(struct rsu_softc *sc, uint16_t addr, uint8_t *buf, int len) { usb_device_request_t req; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = R92S_REQ_REGS; USETW(req.wValue, addr); USETW(req.wIndex, 0); USETW(req.wLength, len); return (rsu_do_request(sc, &req, buf)); } static uint8_t rsu_read_1(struct rsu_softc *sc, uint16_t addr) { uint8_t val; if (rsu_read_region_1(sc, addr, &val, 1) != 0) return (0xff); return (val); } static uint16_t rsu_read_2(struct rsu_softc *sc, uint16_t addr) { uint16_t val; if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 2) != 0) return (0xffff); return (le16toh(val)); } static uint32_t rsu_read_4(struct rsu_softc *sc, uint16_t addr) { uint32_t val; if (rsu_read_region_1(sc, addr, (uint8_t *)&val, 4) != 0) return (0xffffffff); return (le32toh(val)); } static int rsu_fw_iocmd(struct rsu_softc *sc, uint32_t iocmd) { int ntries; rsu_write_4(sc, R92S_IOCMD_CTRL, iocmd); rsu_ms_delay(sc); for (ntries = 0; ntries < 50; ntries++) { if (rsu_read_4(sc, R92S_IOCMD_CTRL) == 0) return (0); rsu_ms_delay(sc); } return (ETIMEDOUT); } static uint8_t rsu_efuse_read_1(struct rsu_softc *sc, uint16_t addr) { uint32_t reg; int ntries; reg = rsu_read_4(sc, R92S_EFUSE_CTRL); reg = RW(reg, R92S_EFUSE_CTRL_ADDR, addr); reg &= ~R92S_EFUSE_CTRL_VALID; rsu_write_4(sc, R92S_EFUSE_CTRL, reg); /* Wait for read operation to complete. */ for (ntries = 0; ntries < 100; ntries++) { reg = rsu_read_4(sc, R92S_EFUSE_CTRL); if (reg & R92S_EFUSE_CTRL_VALID) return (MS(reg, R92S_EFUSE_CTRL_DATA)); rsu_ms_delay(sc); } device_printf(sc->sc_dev, "could not read efuse byte at address 0x%x\n", addr); return (0xff); } static int rsu_read_rom(struct rsu_softc *sc) { uint8_t *rom = sc->rom; uint16_t addr = 0; uint32_t reg; uint8_t off, msk; int i; /* Make sure that ROM type is eFuse and that autoload succeeded. */ reg = rsu_read_1(sc, R92S_EE_9346CR); if ((reg & (R92S_9356SEL | R92S_EEPROM_EN)) != R92S_EEPROM_EN) return (EIO); /* Turn on 2.5V to prevent eFuse leakage. */ reg = rsu_read_1(sc, R92S_EFUSE_TEST + 3); rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg | 0x80); rsu_ms_delay(sc); rsu_write_1(sc, R92S_EFUSE_TEST + 3, reg & ~0x80); /* Read full ROM image. */ memset(&sc->rom, 0xff, sizeof(sc->rom)); while (addr < 512) { reg = rsu_efuse_read_1(sc, addr); if (reg == 0xff) break; addr++; off = reg >> 4; msk = reg & 0xf; for (i = 0; i < 4; i++) { if (msk & (1 << i)) continue; rom[off * 8 + i * 2 + 0] = rsu_efuse_read_1(sc, addr); addr++; rom[off * 8 + i * 2 + 1] = rsu_efuse_read_1(sc, addr); addr++; } } #ifdef USB_DEBUG if (rsu_debug >= 5) { /* Dump ROM content. */ printf("\n"); for (i = 0; i < sizeof(sc->rom); i++) printf("%02x:", rom[i]); printf("\n"); } #endif return (0); } static int rsu_fw_cmd(struct rsu_softc *sc, uint8_t code, void *buf, int len) { const uint8_t which = rsu_wme_ac_xfer_map[WME_AC_VO]; struct rsu_data *data; struct r92s_tx_desc *txd; struct r92s_fw_cmd_hdr *cmd; int cmdsz; int xferlen; data = rsu_getbuf(sc); if (data == NULL) return (ENOMEM); /* Round-up command length to a multiple of 8 bytes. */ cmdsz = (len + 7) & ~7; xferlen = sizeof(*txd) + sizeof(*cmd) + cmdsz; KASSERT(xferlen <= RSU_TXBUFSZ, ("%s: invalid length", __func__)); memset(data->buf, 0, xferlen); /* Setup Tx descriptor. */ txd = (struct r92s_tx_desc *)data->buf; txd->txdw0 = htole32( SM(R92S_TXDW0_OFFSET, sizeof(*txd)) | SM(R92S_TXDW0_PKTLEN, sizeof(*cmd) + cmdsz) | R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG); txd->txdw1 = htole32(SM(R92S_TXDW1_QSEL, R92S_TXDW1_QSEL_H2C)); /* Setup command header. */ cmd = (struct r92s_fw_cmd_hdr *)&txd[1]; cmd->len = htole16(cmdsz); cmd->code = code; cmd->seq = sc->cmd_seq; sc->cmd_seq = (sc->cmd_seq + 1) & 0x7f; /* Copy command payload. */ memcpy(&cmd[1], buf, len); DPRINTFN(2, "Tx cmd code=0x%x len=0x%x\n", code, cmdsz); data->buflen = xferlen; STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next); usbd_transfer_start(sc->sc_xfer[which]); return (0); } /* ARGSUSED */ static void rsu_calib_task(void *arg, int pending __unused) { struct rsu_softc *sc = arg; uint32_t reg; DPRINTFN(6, "running calibration task\n"); RSU_LOCK(sc); #ifdef notyet /* Read WPS PBC status. */ rsu_write_1(sc, R92S_MAC_PINMUX_CTRL, R92S_GPIOMUX_EN | SM(R92S_GPIOSEL_GPIO, R92S_GPIOSEL_GPIO_JTAG)); rsu_write_1(sc, R92S_GPIO_IO_SEL, rsu_read_1(sc, R92S_GPIO_IO_SEL) & ~R92S_GPIO_WPS); reg = rsu_read_1(sc, R92S_GPIO_CTRL); if (reg != 0xff && (reg & R92S_GPIO_WPS)) DPRINTF(("WPS PBC is pushed\n")); #endif /* Read current signal level. */ if (rsu_fw_iocmd(sc, 0xf4000001) == 0) { reg = rsu_read_4(sc, R92S_IOCMD_DATA); DPRINTFN(8, "RSSI=%d%%\n", reg >> 4); } if (sc->sc_calibrating) taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task, hz); RSU_UNLOCK(sc); } static int rsu_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg) { struct rsu_vap *uvp = RSU_VAP(vap); struct ieee80211com *ic = vap->iv_ic; struct rsu_softc *sc = ic->ic_ifp->if_softc; struct ieee80211_node *ni; struct ieee80211_rateset *rs; enum ieee80211_state ostate; int error, startcal = 0; ostate = vap->iv_state; DPRINTF("%s -> %s\n", ieee80211_state_name[ostate], ieee80211_state_name[nstate]); IEEE80211_UNLOCK(ic); if (ostate == IEEE80211_S_RUN) { RSU_LOCK(sc); /* Stop calibration. */ sc->sc_calibrating = 0; RSU_UNLOCK(sc); taskqueue_drain_timeout(taskqueue_thread, &sc->calib_task); /* Disassociate from our current BSS. */ RSU_LOCK(sc); rsu_disconnect(sc); } else RSU_LOCK(sc); switch (nstate) { case IEEE80211_S_INIT: break; case IEEE80211_S_AUTH: ni = ieee80211_ref_node(vap->iv_bss); error = rsu_join_bss(sc, ni); ieee80211_free_node(ni); if (error != 0) { device_printf(sc->sc_dev, "could not send join command\n"); } break; case IEEE80211_S_RUN: ni = ieee80211_ref_node(vap->iv_bss); rs = &ni->ni_rates; /* Indicate highest supported rate. */ ni->ni_txrate = rs->rs_rates[rs->rs_nrates - 1]; ieee80211_free_node(ni); startcal = 1; break; default: break; } sc->sc_calibrating = 1; /* Start periodic calibration. */ taskqueue_enqueue_timeout(taskqueue_thread, &sc->calib_task, hz); RSU_UNLOCK(sc); IEEE80211_LOCK(ic); return (uvp->newstate(vap, nstate, arg)); } #ifdef notyet static void rsu_set_key(struct rsu_softc *sc, const struct ieee80211_key *k) { struct r92s_fw_cmd_set_key key; memset(&key, 0, sizeof(key)); /* Map net80211 cipher to HW crypto algorithm. */ switch (k->wk_cipher->ic_cipher) { case IEEE80211_CIPHER_WEP: if (k->wk_keylen < 8) key.algo = R92S_KEY_ALGO_WEP40; else key.algo = R92S_KEY_ALGO_WEP104; break; case IEEE80211_CIPHER_TKIP: key.algo = R92S_KEY_ALGO_TKIP; break; case IEEE80211_CIPHER_AES_CCM: key.algo = R92S_KEY_ALGO_AES; break; default: return; } key.id = k->wk_keyix; key.grpkey = (k->wk_flags & IEEE80211_KEY_GROUP) != 0; memcpy(key.key, k->wk_key, MIN(k->wk_keylen, sizeof(key.key))); (void)rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key)); } static void rsu_delete_key(struct rsu_softc *sc, const struct ieee80211_key *k) { struct r92s_fw_cmd_set_key key; memset(&key, 0, sizeof(key)); key.id = k->wk_keyix; (void)rsu_fw_cmd(sc, R92S_CMD_SET_KEY, &key, sizeof(key)); } #endif static int rsu_site_survey(struct rsu_softc *sc, struct ieee80211vap *vap) { struct r92s_fw_cmd_sitesurvey cmd; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; memset(&cmd, 0, sizeof(cmd)); if ((ic->ic_flags & IEEE80211_F_ASCAN) || sc->scan_pass == 1) cmd.active = htole32(1); cmd.limit = htole32(48); if (sc->scan_pass == 1 && vap->iv_des_nssid > 0) { /* Do a directed scan for second pass. */ cmd.ssidlen = htole32(vap->iv_des_ssid[0].len); memcpy(cmd.ssid, vap->iv_des_ssid[0].ssid, vap->iv_des_ssid[0].len); } DPRINTF("sending site survey command, pass=%d\n", sc->scan_pass); return (rsu_fw_cmd(sc, R92S_CMD_SITE_SURVEY, &cmd, sizeof(cmd))); } static int rsu_join_bss(struct rsu_softc *sc, struct ieee80211_node *ni) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211vap *vap = ni->ni_vap; struct ndis_wlan_bssid_ex *bss; struct ndis_802_11_fixed_ies *fixed; struct r92s_fw_cmd_auth auth; uint8_t buf[sizeof(*bss) + 128] __aligned(4); uint8_t *frm; uint8_t opmode; int error; /* Let the FW decide the opmode based on the capinfo field. */ opmode = NDIS802_11AUTOUNKNOWN; DPRINTF("setting operating mode to %d\n", opmode); error = rsu_fw_cmd(sc, R92S_CMD_SET_OPMODE, &opmode, sizeof(opmode)); if (error != 0) return (error); memset(&auth, 0, sizeof(auth)); if (vap->iv_flags & IEEE80211_F_WPA) { auth.mode = R92S_AUTHMODE_WPA; auth.dot1x = (ni->ni_authmode == IEEE80211_AUTH_8021X); } else auth.mode = R92S_AUTHMODE_OPEN; DPRINTF("setting auth mode to %d\n", auth.mode); error = rsu_fw_cmd(sc, R92S_CMD_SET_AUTH, &auth, sizeof(auth)); if (error != 0) return (error); memset(buf, 0, sizeof(buf)); bss = (struct ndis_wlan_bssid_ex *)buf; IEEE80211_ADDR_COPY(bss->macaddr, ni->ni_bssid); bss->ssid.ssidlen = htole32(ni->ni_esslen); memcpy(bss->ssid.ssid, ni->ni_essid, ni->ni_esslen); if (vap->iv_flags & (IEEE80211_F_PRIVACY | IEEE80211_F_WPA)) bss->privacy = htole32(1); bss->rssi = htole32(ni->ni_avgrssi); if (ic->ic_curmode == IEEE80211_MODE_11B) bss->networktype = htole32(NDIS802_11DS); else bss->networktype = htole32(NDIS802_11OFDM24); bss->config.len = htole32(sizeof(bss->config)); bss->config.bintval = htole32(ni->ni_intval); bss->config.dsconfig = htole32(ieee80211_chan2ieee(ic, ni->ni_chan)); bss->inframode = htole32(NDIS802_11INFRASTRUCTURE); memcpy(bss->supprates, ni->ni_rates.rs_rates, ni->ni_rates.rs_nrates); /* Write the fixed fields of the beacon frame. */ fixed = (struct ndis_802_11_fixed_ies *)&bss[1]; memcpy(&fixed->tstamp, ni->ni_tstamp.data, 8); fixed->bintval = htole16(ni->ni_intval); fixed->capabilities = htole16(ni->ni_capinfo); /* Write IEs to be included in the association request. */ frm = (uint8_t *)&fixed[1]; frm = ieee80211_add_rsn(frm, vap); frm = ieee80211_add_wpa(frm, vap); frm = ieee80211_add_qos(frm, ni); if (ni->ni_flags & IEEE80211_NODE_HT) frm = ieee80211_add_htcap(frm, ni); bss->ieslen = htole32(frm - (uint8_t *)fixed); bss->len = htole32(((frm - buf) + 3) & ~3); DPRINTF("sending join bss command to %s chan %d\n", ether_sprintf(bss->macaddr), le32toh(bss->config.dsconfig)); return (rsu_fw_cmd(sc, R92S_CMD_JOIN_BSS, buf, sizeof(buf))); } static int rsu_disconnect(struct rsu_softc *sc) { uint32_t zero = 0; /* :-) */ /* Disassociate from our current BSS. */ DPRINTF("sending disconnect command\n"); return (rsu_fw_cmd(sc, R92S_CMD_DISCONNECT, &zero, sizeof(zero))); } static void rsu_event_survey(struct rsu_softc *sc, uint8_t *buf, int len) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211_frame *wh; struct ieee80211_channel *c; struct ndis_wlan_bssid_ex *bss; struct mbuf *m; int pktlen; if (__predict_false(len < sizeof(*bss))) return; bss = (struct ndis_wlan_bssid_ex *)buf; if (__predict_false(len < sizeof(*bss) + le32toh(bss->ieslen))) return; DPRINTFN(2, "found BSS %s: len=%d chan=%d inframode=%d " "networktype=%d privacy=%d\n", ether_sprintf(bss->macaddr), le32toh(bss->len), le32toh(bss->config.dsconfig), le32toh(bss->inframode), le32toh(bss->networktype), le32toh(bss->privacy)); /* Build a fake beacon frame to let net80211 do all the parsing. */ pktlen = sizeof(*wh) + le32toh(bss->ieslen); if (__predict_false(pktlen > MCLBYTES)) return; m = m_get2(pktlen, M_NOWAIT, MT_DATA, M_PKTHDR); if (__predict_false(m == NULL)) return; wh = mtod(m, struct ieee80211_frame *); wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_BEACON; wh->i_fc[1] = IEEE80211_FC1_DIR_NODS; USETW(wh->i_dur, 0); IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr); IEEE80211_ADDR_COPY(wh->i_addr2, bss->macaddr); IEEE80211_ADDR_COPY(wh->i_addr3, bss->macaddr); *(uint16_t *)wh->i_seq = 0; memcpy(&wh[1], (uint8_t *)&bss[1], le32toh(bss->ieslen)); /* Finalize mbuf. */ m->m_pkthdr.len = m->m_len = pktlen; m->m_pkthdr.rcvif = ifp; /* Fix the channel. */ c = ieee80211_find_channel_byieee(ic, le32toh(bss->config.dsconfig), IEEE80211_CHAN_G); if (c) { ic->ic_curchan = c; ieee80211_radiotap_chan_change(ic); } /* XXX avoid a LOR */ RSU_UNLOCK(sc); ieee80211_input_all(ic, m, le32toh(bss->rssi), 0); RSU_LOCK(sc); } static void rsu_event_join_bss(struct rsu_softc *sc, uint8_t *buf, int len) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); struct ieee80211_node *ni = vap->iv_bss; struct r92s_event_join_bss *rsp; uint32_t tmp; int res; if (__predict_false(len < sizeof(*rsp))) return; rsp = (struct r92s_event_join_bss *)buf; res = (int)le32toh(rsp->join_res); DPRINTF("Rx join BSS event len=%d res=%d\n", len, res); if (res <= 0) { RSU_UNLOCK(sc); ieee80211_new_state(vap, IEEE80211_S_SCAN, -1); RSU_LOCK(sc); return; } tmp = le32toh(rsp->associd); if (tmp >= vap->iv_max_aid) { DPRINTF("Assoc ID overflow\n"); tmp = 1; } DPRINTF("associated with %s associd=%d\n", ether_sprintf(rsp->bss.macaddr), tmp); ni->ni_associd = tmp | 0xc000; RSU_UNLOCK(sc); ieee80211_new_state(vap, IEEE80211_S_RUN, IEEE80211_FC0_SUBTYPE_ASSOC_RESP); RSU_LOCK(sc); } static void rsu_rx_event(struct rsu_softc *sc, uint8_t code, uint8_t *buf, int len) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); DPRINTFN(4, "Rx event code=%d len=%d\n", code, len); switch (code) { case R92S_EVT_SURVEY: if (vap->iv_state == IEEE80211_S_SCAN) rsu_event_survey(sc, buf, len); break; case R92S_EVT_SURVEY_DONE: DPRINTF("site survey pass %d done, found %d BSS\n", sc->scan_pass, le32toh(*(uint32_t *)buf)); if (vap->iv_state != IEEE80211_S_SCAN) break; /* Ignore if not scanning. */ if (sc->scan_pass == 0 && vap->iv_des_nssid != 0) { /* Schedule a directed scan for hidden APs. */ sc->scan_pass = 1; RSU_UNLOCK(sc); ieee80211_new_state(vap, IEEE80211_S_SCAN, -1); RSU_LOCK(sc); break; } sc->scan_pass = 0; break; case R92S_EVT_JOIN_BSS: if (vap->iv_state == IEEE80211_S_AUTH) rsu_event_join_bss(sc, buf, len); break; #if 0 XXX This event is occurring regularly, possibly due to some power saving event XXX and disrupts the WLAN traffic. Disable for now. case R92S_EVT_DEL_STA: DPRINTF("disassociated from %s\n", ether_sprintf(buf)); if (vap->iv_state == IEEE80211_S_RUN && IEEE80211_ADDR_EQ(vap->iv_bss->ni_bssid, buf)) { RSU_UNLOCK(sc); ieee80211_new_state(vap, IEEE80211_S_SCAN, -1); RSU_LOCK(sc); } break; #endif case R92S_EVT_WPS_PBC: DPRINTF("WPS PBC pushed.\n"); break; case R92S_EVT_FWDBG: if (ifp->if_flags & IFF_DEBUG) { buf[60] = '\0'; printf("FWDBG: %s\n", (char *)buf); } break; default: break; } } static void rsu_rx_multi_event(struct rsu_softc *sc, uint8_t *buf, int len) { struct r92s_fw_cmd_hdr *cmd; int cmdsz; DPRINTFN(6, "Rx events len=%d\n", len); /* Skip Rx status. */ buf += sizeof(struct r92s_rx_stat); len -= sizeof(struct r92s_rx_stat); /* Process all events. */ for (;;) { /* Check that command header fits. */ if (__predict_false(len < sizeof(*cmd))) break; cmd = (struct r92s_fw_cmd_hdr *)buf; /* Check that command payload fits. */ cmdsz = le16toh(cmd->len); if (__predict_false(len < sizeof(*cmd) + cmdsz)) break; /* Process firmware event. */ rsu_rx_event(sc, cmd->code, (uint8_t *)&cmd[1], cmdsz); if (!(cmd->seq & R92S_FW_CMD_MORE)) break; buf += sizeof(*cmd) + cmdsz; len -= sizeof(*cmd) + cmdsz; } } static int8_t rsu_get_rssi(struct rsu_softc *sc, int rate, void *physt) { static const int8_t cckoff[] = { 14, -2, -20, -40 }; struct r92s_rx_phystat *phy; struct r92s_rx_cck *cck; uint8_t rpt; int8_t rssi; if (rate <= 3) { cck = (struct r92s_rx_cck *)physt; rpt = (cck->agc_rpt >> 6) & 0x3; rssi = cck->agc_rpt & 0x3e; rssi = cckoff[rpt] - rssi; } else { /* OFDM/HT. */ phy = (struct r92s_rx_phystat *)physt; rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 106; } return (rssi); } static struct mbuf * rsu_rx_frame(struct rsu_softc *sc, uint8_t *buf, int pktlen, int *rssi) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211_frame *wh; struct r92s_rx_stat *stat; uint32_t rxdw0, rxdw3; struct mbuf *m; uint8_t rate; int infosz; stat = (struct r92s_rx_stat *)buf; rxdw0 = le32toh(stat->rxdw0); rxdw3 = le32toh(stat->rxdw3); if (__predict_false(rxdw0 & R92S_RXDW0_CRCERR)) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); return NULL; } if (__predict_false(pktlen < sizeof(*wh) || pktlen > MCLBYTES)) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); return NULL; } rate = MS(rxdw3, R92S_RXDW3_RATE); infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8; /* Get RSSI from PHY status descriptor if present. */ if (infosz != 0) *rssi = rsu_get_rssi(sc, rate, &stat[1]); else *rssi = 0; DPRINTFN(5, "Rx frame len=%d rate=%d infosz=%d rssi=%d\n", pktlen, rate, infosz, *rssi); m = m_get2(pktlen, M_NOWAIT, MT_DATA, M_PKTHDR); if (__predict_false(m == NULL)) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); return NULL; } /* Finalize mbuf. */ m->m_pkthdr.rcvif = ifp; /* Hardware does Rx TCP checksum offload. */ if (rxdw3 & R92S_RXDW3_TCPCHKVALID) { if (__predict_true(rxdw3 & R92S_RXDW3_TCPCHKRPT)) m->m_pkthdr.csum_flags |= CSUM_DATA_VALID; } wh = (struct ieee80211_frame *)((uint8_t *)&stat[1] + infosz); memcpy(mtod(m, uint8_t *), wh, pktlen); m->m_pkthdr.len = m->m_len = pktlen; if (ieee80211_radiotap_active(ic)) { struct rsu_rx_radiotap_header *tap = &sc->sc_rxtap; /* Map HW rate index to 802.11 rate. */ tap->wr_flags = 2; if (!(rxdw3 & R92S_RXDW3_HTC)) { switch (rate) { /* CCK. */ case 0: tap->wr_rate = 2; break; case 1: tap->wr_rate = 4; break; case 2: tap->wr_rate = 11; break; case 3: tap->wr_rate = 22; break; /* OFDM. */ case 4: tap->wr_rate = 12; break; case 5: tap->wr_rate = 18; break; case 6: tap->wr_rate = 24; break; case 7: tap->wr_rate = 36; break; case 8: tap->wr_rate = 48; break; case 9: tap->wr_rate = 72; break; case 10: tap->wr_rate = 96; break; case 11: tap->wr_rate = 108; break; } } else if (rate >= 12) { /* MCS0~15. */ /* Bit 7 set means HT MCS instead of rate. */ tap->wr_rate = 0x80 | (rate - 12); } tap->wr_dbm_antsignal = *rssi; tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq); tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags); } return (m); } static struct mbuf * rsu_rx_multi_frame(struct rsu_softc *sc, uint8_t *buf, int len, int *rssi) { struct r92s_rx_stat *stat; uint32_t rxdw0; int totlen, pktlen, infosz, npkts; struct mbuf *m, *m0 = NULL, *prevm = NULL; /* Get the number of encapsulated frames. */ stat = (struct r92s_rx_stat *)buf; npkts = MS(le32toh(stat->rxdw2), R92S_RXDW2_PKTCNT); DPRINTFN(6, "Rx %d frames in one chunk\n", npkts); /* Process all of them. */ while (npkts-- > 0) { if (__predict_false(len < sizeof(*stat))) break; stat = (struct r92s_rx_stat *)buf; rxdw0 = le32toh(stat->rxdw0); pktlen = MS(rxdw0, R92S_RXDW0_PKTLEN); if (__predict_false(pktlen == 0)) break; infosz = MS(rxdw0, R92S_RXDW0_INFOSZ) * 8; /* Make sure everything fits in xfer. */ totlen = sizeof(*stat) + infosz + pktlen; if (__predict_false(totlen > len)) break; /* Process 802.11 frame. */ m = rsu_rx_frame(sc, buf, pktlen, rssi); if (m0 == NULL) m0 = m; if (prevm == NULL) prevm = m; else { prevm->m_next = m; prevm = m; } /* Next chunk is 128-byte aligned. */ totlen = (totlen + 127) & ~127; buf += totlen; len -= totlen; } return (m0); } static struct mbuf * rsu_rxeof(struct usb_xfer *xfer, struct rsu_data *data, int *rssi) { struct rsu_softc *sc = data->sc; struct r92s_rx_stat *stat; int len; usbd_xfer_status(xfer, &len, NULL, NULL, NULL); if (__predict_false(len < sizeof(*stat))) { DPRINTF("xfer too short %d\n", len); if_inc_counter(sc->sc_ifp, IFCOUNTER_IERRORS, 1); return (NULL); } /* Determine if it is a firmware C2H event or an 802.11 frame. */ stat = (struct r92s_rx_stat *)data->buf; if ((le32toh(stat->rxdw1) & 0x1ff) == 0x1ff) { rsu_rx_multi_event(sc, data->buf, len); /* No packets to process. */ return (NULL); } else return (rsu_rx_multi_frame(sc, data->buf, len, rssi)); } static void rsu_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error) { struct rsu_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211_frame *wh; struct ieee80211_node *ni; struct mbuf *m = NULL, *next; struct rsu_data *data; int rssi = 1; RSU_ASSERT_LOCKED(sc); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: data = STAILQ_FIRST(&sc->sc_rx_active); if (data == NULL) goto tr_setup; STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next); m = rsu_rxeof(xfer, data, &rssi); STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: data = STAILQ_FIRST(&sc->sc_rx_inactive); if (data == NULL) { KASSERT(m == NULL, ("mbuf isn't NULL")); return; } STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next); STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next); usbd_xfer_set_frame_data(xfer, 0, data->buf, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); /* * To avoid LOR we should unlock our private mutex here to call * ieee80211_input() because here is at the end of a USB * callback and safe to unlock. */ RSU_UNLOCK(sc); while (m != NULL) { next = m->m_next; m->m_next = NULL; wh = mtod(m, struct ieee80211_frame *); ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh); if (ni != NULL) { (void)ieee80211_input(ni, m, rssi, 0); ieee80211_free_node(ni); } else (void)ieee80211_input_all(ic, m, rssi, 0); m = next; } RSU_LOCK(sc); break; default: /* needs it to the inactive queue due to a error. */ data = STAILQ_FIRST(&sc->sc_rx_active); if (data != NULL) { STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next); STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next); } if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } break; } } static void rsu_txeof(struct usb_xfer *xfer, struct rsu_data *data) { struct rsu_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct mbuf *m; RSU_ASSERT_LOCKED(sc); /* * Do any tx complete callback. Note this must be done before releasing * the node reference. */ if (data->m) { m = data->m; if (m->m_flags & M_TXCB) { /* XXX status? */ ieee80211_process_callback(data->ni, m, 0); } m_freem(m); data->m = NULL; } if (data->ni) { ieee80211_free_node(data->ni); data->ni = NULL; } if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; } static void rsu_bulk_tx_callback_sub(struct usb_xfer *xfer, usb_error_t error, uint8_t which) { struct rsu_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct rsu_data *data; RSU_ASSERT_LOCKED(sc); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: data = STAILQ_FIRST(&sc->sc_tx_active[which]); if (data == NULL) goto tr_setup; DPRINTF("transfer done %p\n", data); STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next); rsu_txeof(xfer, data); STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, data, next); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: data = STAILQ_FIRST(&sc->sc_tx_pending[which]); if (data == NULL) { DPRINTF("empty pending queue sc %p\n", sc); return; } STAILQ_REMOVE_HEAD(&sc->sc_tx_pending[which], next); STAILQ_INSERT_TAIL(&sc->sc_tx_active[which], data, next); usbd_xfer_set_frame_data(xfer, 0, data->buf, data->buflen); DPRINTF("submitting transfer %p\n", data); usbd_transfer_submit(xfer); break; default: data = STAILQ_FIRST(&sc->sc_tx_active[which]); if (data != NULL) { STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next); rsu_txeof(xfer, data); STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, data, next); } if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void rsu_bulk_tx_callback_be_bk(struct usb_xfer *xfer, usb_error_t error) { rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_BE_BK); } static void rsu_bulk_tx_callback_vi_vo(struct usb_xfer *xfer, usb_error_t error) { rsu_bulk_tx_callback_sub(xfer, error, RSU_BULK_TX_VI_VO); } static int rsu_tx_start(struct rsu_softc *sc, struct ieee80211_node *ni, struct mbuf *m0, struct rsu_data *data) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211vap *vap = ni->ni_vap; struct ieee80211_frame *wh; struct ieee80211_key *k = NULL; struct r92s_tx_desc *txd; uint8_t type; uint8_t tid = 0; uint8_t which; int hasqos; int xferlen; RSU_ASSERT_LOCKED(sc); wh = mtod(m0, struct ieee80211_frame *); type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK; if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) { k = ieee80211_crypto_encap(ni, m0); if (k == NULL) { device_printf(sc->sc_dev, "ieee80211_crypto_encap returns NULL.\n"); /* XXX we don't expect the fragmented frames */ m_freem(m0); return (ENOBUFS); } wh = mtod(m0, struct ieee80211_frame *); } switch (type) { case IEEE80211_FC0_TYPE_CTL: case IEEE80211_FC0_TYPE_MGT: which = rsu_wme_ac_xfer_map[WME_AC_VO]; break; default: which = rsu_wme_ac_xfer_map[M_WME_GETAC(m0)]; break; } hasqos = 0; /* Fill Tx descriptor. */ txd = (struct r92s_tx_desc *)data->buf; memset(txd, 0, sizeof(*txd)); txd->txdw0 |= htole32( SM(R92S_TXDW0_PKTLEN, m0->m_pkthdr.len) | SM(R92S_TXDW0_OFFSET, sizeof(*txd)) | R92S_TXDW0_OWN | R92S_TXDW0_FSG | R92S_TXDW0_LSG); txd->txdw1 |= htole32( SM(R92S_TXDW1_MACID, R92S_MACID_BSS) | SM(R92S_TXDW1_QSEL, R92S_TXDW1_QSEL_BE)); if (!hasqos) txd->txdw1 |= htole32(R92S_TXDW1_NONQOS); #ifdef notyet if (k != NULL) { switch (k->wk_cipher->ic_cipher) { case IEEE80211_CIPHER_WEP: cipher = R92S_TXDW1_CIPHER_WEP; break; case IEEE80211_CIPHER_TKIP: cipher = R92S_TXDW1_CIPHER_TKIP; break; case IEEE80211_CIPHER_AES_CCM: cipher = R92S_TXDW1_CIPHER_AES; break; default: cipher = R92S_TXDW1_CIPHER_NONE; } txd->txdw1 |= htole32( SM(R92S_TXDW1_CIPHER, cipher) | SM(R92S_TXDW1_KEYIDX, k->k_id)); } #endif txd->txdw2 |= htole32(R92S_TXDW2_BK); if (IEEE80211_IS_MULTICAST(wh->i_addr1)) txd->txdw2 |= htole32(R92S_TXDW2_BMCAST); /* * Firmware will use and increment the sequence number for the * specified TID. */ txd->txdw3 |= htole32(SM(R92S_TXDW3_SEQ, tid)); if (ieee80211_radiotap_active_vap(vap)) { struct rsu_tx_radiotap_header *tap = &sc->sc_txtap; tap->wt_flags = 0; tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq); tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags); ieee80211_radiotap_tx(vap, m0); } xferlen = sizeof(*txd) + m0->m_pkthdr.len; m_copydata(m0, 0, m0->m_pkthdr.len, (caddr_t)&txd[1]); data->buflen = xferlen; data->ni = ni; data->m = m0; STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next); /* start transfer, if any */ usbd_transfer_start(sc->sc_xfer[which]); return (0); } static void rsu_start(struct ifnet *ifp) { struct rsu_softc *sc = ifp->if_softc; if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) return; RSU_LOCK(sc); rsu_start_locked(ifp); RSU_UNLOCK(sc); } static void rsu_start_locked(struct ifnet *ifp) { struct rsu_softc *sc = ifp->if_softc; struct ieee80211_node *ni; struct rsu_data *bf; struct mbuf *m; RSU_ASSERT_LOCKED(sc); for (;;) { IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; ni = (struct ieee80211_node *)m->m_pkthdr.rcvif; m->m_pkthdr.rcvif = NULL; bf = rsu_getbuf(sc); if (bf == NULL) { if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1); m_freem(m); ieee80211_free_node(ni); } else if (rsu_tx_start(sc, ni, m, bf) != 0) { if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next); ieee80211_free_node(ni); } } } static int rsu_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) { struct ieee80211com *ic = ifp->if_l2com; struct ifreq *ifr = (struct ifreq *) data; int error = 0, startall = 0; switch (cmd) { case SIOCSIFFLAGS: if (ifp->if_flags & IFF_UP) { if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) { rsu_init(ifp->if_softc); startall = 1; } } else { if (ifp->if_drv_flags & IFF_DRV_RUNNING) rsu_stop(ifp, 1); } if (startall) ieee80211_start_all(ic); break; case SIOCGIFMEDIA: error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd); break; case SIOCGIFADDR: error = ether_ioctl(ifp, cmd, data); break; default: error = EINVAL; break; } return (error); } /* * Power on sequence for A-cut adapters. */ static void rsu_power_on_acut(struct rsu_softc *sc) { uint32_t reg; rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53); rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57); /* Enable AFE macro block's bandgap and Mbias. */ rsu_write_1(sc, R92S_AFE_MISC, rsu_read_1(sc, R92S_AFE_MISC) | R92S_AFE_MISC_BGEN | R92S_AFE_MISC_MBEN); /* Enable LDOA15 block. */ rsu_write_1(sc, R92S_LDOA15_CTRL, rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN); rsu_write_1(sc, R92S_SPS1_CTRL, rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_LDEN); usb_pause_mtx(&sc->sc_mtx, 2 * hz); /* Enable switch regulator block. */ rsu_write_1(sc, R92S_SPS1_CTRL, rsu_read_1(sc, R92S_SPS1_CTRL) | R92S_SPS1_SWEN); rsu_write_4(sc, R92S_SPS1_CTRL, 0x00a7b267); rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08); rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20); rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x90); /* Enable AFE clock. */ rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1, rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04); /* Enable AFE PLL macro block. */ rsu_write_1(sc, R92S_AFE_PLL_CTRL, rsu_read_1(sc, R92S_AFE_PLL_CTRL) | 0x11); /* Attach AFE PLL to MACTOP/BB. */ rsu_write_1(sc, R92S_SYS_ISO_CTRL, rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11); /* Switch to 40MHz clock instead of 80MHz. */ rsu_write_2(sc, R92S_SYS_CLKR, rsu_read_2(sc, R92S_SYS_CLKR) & ~R92S_SYS_CLKSEL); /* Enable MAC clock. */ rsu_write_2(sc, R92S_SYS_CLKR, rsu_read_2(sc, R92S_SYS_CLKR) | R92S_MAC_CLK_EN | R92S_SYS_CLK_EN); rsu_write_1(sc, R92S_PMC_FSM, 0x02); /* Enable digital core and IOREG R/W. */ rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08); rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80); /* Switch the control path to firmware. */ reg = rsu_read_2(sc, R92S_SYS_CLKR); reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL; rsu_write_2(sc, R92S_SYS_CLKR, reg); rsu_write_2(sc, R92S_CR, 0x37fc); /* Fix USB RX FIFO issue. */ rsu_write_1(sc, 0xfe5c, rsu_read_1(sc, 0xfe5c) | 0x80); rsu_write_1(sc, 0x00ab, rsu_read_1(sc, 0x00ab) | 0xc0); rsu_write_1(sc, R92S_SYS_CLKR, rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL); } /* * Power on sequence for B-cut and C-cut adapters. */ static void rsu_power_on_bcut(struct rsu_softc *sc) { uint32_t reg; int ntries; /* Prevent eFuse leakage. */ rsu_write_1(sc, 0x37, 0xb0); usb_pause_mtx(&sc->sc_mtx, hz / 100); rsu_write_1(sc, 0x37, 0x30); /* Switch the control path to hardware. */ reg = rsu_read_2(sc, R92S_SYS_CLKR); if (reg & R92S_FWHW_SEL) { rsu_write_2(sc, R92S_SYS_CLKR, reg & ~(R92S_SWHW_SEL | R92S_FWHW_SEL)); } rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) & ~0x8c); rsu_ms_delay(sc); rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x53); rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x57); reg = rsu_read_1(sc, R92S_AFE_MISC); rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN); rsu_write_1(sc, R92S_AFE_MISC, reg | R92S_AFE_MISC_BGEN | R92S_AFE_MISC_MBEN | R92S_AFE_MISC_I32_EN); /* Enable PLL. */ rsu_write_1(sc, R92S_LDOA15_CTRL, rsu_read_1(sc, R92S_LDOA15_CTRL) | R92S_LDA15_EN); rsu_write_1(sc, R92S_LDOV12D_CTRL, rsu_read_1(sc, R92S_LDOV12D_CTRL) | R92S_LDV12_EN); rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) | 0x08); rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x20); /* Support 64KB IMEM. */ rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, rsu_read_1(sc, R92S_SYS_ISO_CTRL + 1) & ~0x97); /* Enable AFE clock. */ rsu_write_1(sc, R92S_AFE_XTAL_CTRL + 1, rsu_read_1(sc, R92S_AFE_XTAL_CTRL + 1) & ~0x04); /* Enable AFE PLL macro block. */ reg = rsu_read_1(sc, R92S_AFE_PLL_CTRL); rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11); rsu_ms_delay(sc); rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x51); rsu_ms_delay(sc); rsu_write_1(sc, R92S_AFE_PLL_CTRL, reg | 0x11); rsu_ms_delay(sc); /* Attach AFE PLL to MACTOP/BB. */ rsu_write_1(sc, R92S_SYS_ISO_CTRL, rsu_read_1(sc, R92S_SYS_ISO_CTRL) & ~0x11); /* Switch to 40MHz clock. */ rsu_write_1(sc, R92S_SYS_CLKR, 0x00); /* Disable CPU clock and 80MHz SSC. */ rsu_write_1(sc, R92S_SYS_CLKR, rsu_read_1(sc, R92S_SYS_CLKR) | 0xa0); /* Enable MAC clock. */ rsu_write_2(sc, R92S_SYS_CLKR, rsu_read_2(sc, R92S_SYS_CLKR) | R92S_MAC_CLK_EN | R92S_SYS_CLK_EN); rsu_write_1(sc, R92S_PMC_FSM, 0x02); /* Enable digital core and IOREG R/W. */ rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x08); rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, rsu_read_1(sc, R92S_SYS_FUNC_EN + 1) | 0x80); /* Switch the control path to firmware. */ reg = rsu_read_2(sc, R92S_SYS_CLKR); reg = (reg & ~R92S_SWHW_SEL) | R92S_FWHW_SEL; rsu_write_2(sc, R92S_SYS_CLKR, reg); rsu_write_2(sc, R92S_CR, 0x37fc); /* Fix USB RX FIFO issue. */ rsu_write_1(sc, 0xfe5c, rsu_read_1(sc, 0xfe5c) | 0x80); rsu_write_1(sc, R92S_SYS_CLKR, rsu_read_1(sc, R92S_SYS_CLKR) & ~R92S_SYS_CPU_CLKSEL); rsu_write_1(sc, 0xfe1c, 0x80); /* Make sure TxDMA is ready to download firmware. */ for (ntries = 0; ntries < 20; ntries++) { reg = rsu_read_1(sc, R92S_TCR); if ((reg & (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT)) == (R92S_TCR_IMEM_CHK_RPT | R92S_TCR_EMEM_CHK_RPT)) break; rsu_ms_delay(sc); } if (ntries == 20) { DPRINTF("TxDMA is not ready\n"); /* Reset TxDMA. */ reg = rsu_read_1(sc, R92S_CR); rsu_write_1(sc, R92S_CR, reg & ~R92S_CR_TXDMA_EN); rsu_ms_delay(sc); rsu_write_1(sc, R92S_CR, reg | R92S_CR_TXDMA_EN); } } static void rsu_power_off(struct rsu_softc *sc) { /* Turn RF off. */ rsu_write_1(sc, R92S_RF_CTRL, 0x00); usb_pause_mtx(&sc->sc_mtx, hz / 200); /* Turn MAC off. */ /* Switch control path. */ rsu_write_1(sc, R92S_SYS_CLKR + 1, 0x38); /* Reset MACTOP. */ rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x70); rsu_write_1(sc, R92S_PMC_FSM, 0x06); rsu_write_1(sc, R92S_SYS_ISO_CTRL + 0, 0xf9); rsu_write_1(sc, R92S_SYS_ISO_CTRL + 1, 0xe8); /* Disable AFE PLL. */ rsu_write_1(sc, R92S_AFE_PLL_CTRL, 0x00); /* Disable A15V. */ rsu_write_1(sc, R92S_LDOA15_CTRL, 0x54); /* Disable eFuse 1.2V. */ rsu_write_1(sc, R92S_SYS_FUNC_EN + 1, 0x50); rsu_write_1(sc, R92S_LDOV12D_CTRL, 0x24); /* Enable AFE macro block's bandgap and Mbias. */ rsu_write_1(sc, R92S_AFE_MISC, 0x30); /* Disable 1.6V LDO. */ rsu_write_1(sc, R92S_SPS0_CTRL + 0, 0x56); rsu_write_1(sc, R92S_SPS0_CTRL + 1, 0x43); } static int rsu_fw_loadsection(struct rsu_softc *sc, const uint8_t *buf, int len) { const uint8_t which = rsu_wme_ac_xfer_map[WME_AC_VO]; struct rsu_data *data; struct r92s_tx_desc *txd; int mlen; while (len > 0) { data = rsu_getbuf(sc); if (data == NULL) return (ENOMEM); txd = (struct r92s_tx_desc *)data->buf; memset(txd, 0, sizeof(*txd)); if (len <= RSU_TXBUFSZ - sizeof(*txd)) { /* Last chunk. */ txd->txdw0 |= htole32(R92S_TXDW0_LINIP); mlen = len; } else mlen = RSU_TXBUFSZ - sizeof(*txd); txd->txdw0 |= htole32(SM(R92S_TXDW0_PKTLEN, mlen)); memcpy(&txd[1], buf, mlen); data->buflen = sizeof(*txd) + mlen; DPRINTF("starting transfer %p\n", data); STAILQ_INSERT_TAIL(&sc->sc_tx_pending[which], data, next); buf += mlen; len -= mlen; } usbd_transfer_start(sc->sc_xfer[which]); return (0); } static int rsu_load_firmware(struct rsu_softc *sc) { const struct r92s_fw_hdr *hdr; struct r92s_fw_priv *dmem; const uint8_t *imem, *emem; int imemsz, ememsz; const struct firmware *fw; size_t size; uint32_t reg; int ntries, error; if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY) { DPRINTF("Firmware already loaded\n"); return (0); } RSU_UNLOCK(sc); /* Read firmware image from the filesystem. */ if ((fw = firmware_get("rsu-rtl8712fw")) == NULL) { device_printf(sc->sc_dev, "%s: failed load firmware of file rsu-rtl8712fw\n", __func__); RSU_LOCK(sc); return (ENXIO); } RSU_LOCK(sc); size = fw->datasize; if (size < sizeof(*hdr)) { device_printf(sc->sc_dev, "firmware too short\n"); error = EINVAL; goto fail; } hdr = (const struct r92s_fw_hdr *)fw->data; if (hdr->signature != htole16(0x8712) && hdr->signature != htole16(0x8192)) { device_printf(sc->sc_dev, "invalid firmware signature 0x%x\n", le16toh(hdr->signature)); error = EINVAL; goto fail; } DPRINTF("FW V%d %02x-%02x %02x:%02x\n", le16toh(hdr->version), hdr->month, hdr->day, hdr->hour, hdr->minute); /* Make sure that driver and firmware are in sync. */ if (hdr->privsz != htole32(sizeof(*dmem))) { device_printf(sc->sc_dev, "unsupported firmware image\n"); error = EINVAL; goto fail; } /* Get FW sections sizes. */ imemsz = le32toh(hdr->imemsz); ememsz = le32toh(hdr->sramsz); /* Check that all FW sections fit in image. */ if (size < sizeof(*hdr) + imemsz + ememsz) { device_printf(sc->sc_dev, "firmware too short\n"); error = EINVAL; goto fail; } imem = (const uint8_t *)&hdr[1]; emem = imem + imemsz; /* Load IMEM section. */ error = rsu_fw_loadsection(sc, imem, imemsz); if (error != 0) { device_printf(sc->sc_dev, "could not load firmware section %s\n", "IMEM"); goto fail; } /* Wait for load to complete. */ for (ntries = 0; ntries != 50; ntries++) { usb_pause_mtx(&sc->sc_mtx, hz / 100); reg = rsu_read_1(sc, R92S_TCR); if (reg & R92S_TCR_IMEM_CODE_DONE) break; } if (ntries == 50) { device_printf(sc->sc_dev, "timeout waiting for IMEM transfer\n"); error = ETIMEDOUT; goto fail; } /* Load EMEM section. */ error = rsu_fw_loadsection(sc, emem, ememsz); if (error != 0) { device_printf(sc->sc_dev, "could not load firmware section %s\n", "EMEM"); goto fail; } /* Wait for load to complete. */ for (ntries = 0; ntries != 50; ntries++) { usb_pause_mtx(&sc->sc_mtx, hz / 100); reg = rsu_read_2(sc, R92S_TCR); if (reg & R92S_TCR_EMEM_CODE_DONE) break; } if (ntries == 50) { device_printf(sc->sc_dev, "timeout waiting for EMEM transfer\n"); error = ETIMEDOUT; goto fail; } /* Enable CPU. */ rsu_write_1(sc, R92S_SYS_CLKR, rsu_read_1(sc, R92S_SYS_CLKR) | R92S_SYS_CPU_CLKSEL); if (!(rsu_read_1(sc, R92S_SYS_CLKR) & R92S_SYS_CPU_CLKSEL)) { device_printf(sc->sc_dev, "could not enable system clock\n"); error = EIO; goto fail; } rsu_write_2(sc, R92S_SYS_FUNC_EN, rsu_read_2(sc, R92S_SYS_FUNC_EN) | R92S_FEN_CPUEN); if (!(rsu_read_2(sc, R92S_SYS_FUNC_EN) & R92S_FEN_CPUEN)) { device_printf(sc->sc_dev, "could not enable microcontroller\n"); error = EIO; goto fail; } /* Wait for CPU to initialize. */ for (ntries = 0; ntries < 100; ntries++) { if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_IMEM_RDY) break; rsu_ms_delay(sc); } if (ntries == 100) { device_printf(sc->sc_dev, "timeout waiting for microcontroller\n"); error = ETIMEDOUT; goto fail; } /* Update DMEM section before loading. */ dmem = __DECONST(struct r92s_fw_priv *, &hdr->priv); memset(dmem, 0, sizeof(*dmem)); dmem->hci_sel = R92S_HCI_SEL_USB | R92S_HCI_SEL_8172; dmem->nendpoints = 0; dmem->rf_config = 0x12; /* 1T2R */ dmem->vcs_type = R92S_VCS_TYPE_AUTO; dmem->vcs_mode = R92S_VCS_MODE_RTS_CTS; #ifdef notyet dmem->bw40_en = (ic->ic_htcaps & IEEE80211_HTCAP_CBW20_40) != 0; #endif dmem->turbo_mode = 1; /* Load DMEM section. */ error = rsu_fw_loadsection(sc, (uint8_t *)dmem, sizeof(*dmem)); if (error != 0) { device_printf(sc->sc_dev, "could not load firmware section %s\n", "DMEM"); goto fail; } /* Wait for load to complete. */ for (ntries = 0; ntries < 100; ntries++) { if (rsu_read_1(sc, R92S_TCR) & R92S_TCR_DMEM_CODE_DONE) break; rsu_ms_delay(sc); } if (ntries == 100) { device_printf(sc->sc_dev, "timeout waiting for %s transfer\n", "DMEM"); error = ETIMEDOUT; goto fail; } /* Wait for firmware readiness. */ for (ntries = 0; ntries < 60; ntries++) { if (!(rsu_read_1(sc, R92S_TCR) & R92S_TCR_FWRDY)) break; rsu_ms_delay(sc); } if (ntries == 60) { device_printf(sc->sc_dev, "timeout waiting for firmware readiness\n"); error = ETIMEDOUT; goto fail; } fail: firmware_put(fw, FIRMWARE_UNLOAD); return (error); } static int rsu_raw_xmit(struct ieee80211_node *ni, struct mbuf *m, const struct ieee80211_bpf_params *params) { struct ieee80211com *ic = ni->ni_ic; struct ifnet *ifp = ic->ic_ifp; struct rsu_softc *sc = ifp->if_softc; struct rsu_data *bf; /* prevent management frames from being sent if we're not ready */ if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) { m_freem(m); ieee80211_free_node(ni); return (ENETDOWN); } RSU_LOCK(sc); bf = rsu_getbuf(sc); if (bf == NULL) { ieee80211_free_node(ni); m_freem(m); RSU_UNLOCK(sc); return (ENOBUFS); } if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); if (rsu_tx_start(sc, ni, m, bf) != 0) { ieee80211_free_node(ni); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next); RSU_UNLOCK(sc); return (EIO); } RSU_UNLOCK(sc); return (0); } static void rsu_init(void *arg) { struct rsu_softc *sc = arg; RSU_LOCK(sc); rsu_init_locked(arg); RSU_UNLOCK(sc); } static void rsu_init_locked(struct rsu_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct r92s_set_pwr_mode cmd; int error; int i; /* Init host async commands ring. */ sc->cmdq.cur = sc->cmdq.next = sc->cmdq.queued = 0; /* Power on adapter. */ if (sc->cut == 1) rsu_power_on_acut(sc); else rsu_power_on_bcut(sc); /* Load firmware. */ error = rsu_load_firmware(sc); if (error != 0) goto fail; /* Enable Rx TCP checksum offload. */ rsu_write_4(sc, R92S_RCR, rsu_read_4(sc, R92S_RCR) | 0x04000000); /* Append PHY status. */ rsu_write_4(sc, R92S_RCR, rsu_read_4(sc, R92S_RCR) | 0x02000000); rsu_write_4(sc, R92S_CR, rsu_read_4(sc, R92S_CR) & ~0xff000000); /* Use 128 bytes pages. */ rsu_write_1(sc, 0x00b5, rsu_read_1(sc, 0x00b5) | 0x01); /* Enable USB Rx aggregation. */ rsu_write_1(sc, 0x00bd, rsu_read_1(sc, 0x00bd) | 0x80); /* Set USB Rx aggregation threshold. */ rsu_write_1(sc, 0x00d9, 0x01); /* Set USB Rx aggregation timeout (1.7ms/4). */ rsu_write_1(sc, 0xfe5b, 0x04); /* Fix USB Rx FIFO issue. */ rsu_write_1(sc, 0xfe5c, rsu_read_1(sc, 0xfe5c) | 0x80); /* Set MAC address. */ rsu_write_region_1(sc, R92S_MACID, IF_LLADDR(ifp), IEEE80211_ADDR_LEN); /* It really takes 1.5 seconds for the firmware to boot: */ usb_pause_mtx(&sc->sc_mtx, (3 * hz) / 2); DPRINTF("setting MAC address to %s\n", ether_sprintf(IF_LLADDR(ifp))); error = rsu_fw_cmd(sc, R92S_CMD_SET_MAC_ADDRESS, IF_LLADDR(ifp), IEEE80211_ADDR_LEN); if (error != 0) { device_printf(sc->sc_dev, "could not set MAC address\n"); goto fail; } rsu_write_1(sc, R92S_USB_HRPWM, R92S_USB_HRPWM_PS_ST_ACTIVE | R92S_USB_HRPWM_PS_ALL_ON); memset(&cmd, 0, sizeof(cmd)); cmd.mode = R92S_PS_MODE_ACTIVE; DPRINTF("setting ps mode to %d\n", cmd.mode); error = rsu_fw_cmd(sc, R92S_CMD_SET_PWR_MODE, &cmd, sizeof(cmd)); if (error != 0) { device_printf(sc->sc_dev, "could not set PS mode\n"); goto fail; } #if 0 if (ic->ic_htcaps & IEEE80211_HTCAP_CBW20_40) { /* Enable 40MHz mode. */ error = rsu_fw_iocmd(sc, SM(R92S_IOCMD_CLASS, 0xf4) | SM(R92S_IOCMD_INDEX, 0x00) | SM(R92S_IOCMD_VALUE, 0x0007)); if (error != 0) { device_printf(sc->sc_dev, "could not enable 40MHz mode\n"); goto fail; } } /* Set default channel. */ ic->ic_bss->ni_chan = ic->ic_ibss_chan; #endif sc->scan_pass = 0; usbd_transfer_start(sc->sc_xfer[RSU_BULK_RX]); /* We're ready to go. */ ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; ifp->if_drv_flags |= IFF_DRV_RUNNING; return; fail: /* Need to stop all failed transfers, if any */ for (i = 0; i != RSU_N_TRANSFER; i++) usbd_transfer_stop(sc->sc_xfer[i]); } static void rsu_stop(struct ifnet *ifp, int disable) { struct rsu_softc *sc = ifp->if_softc; RSU_LOCK(sc); rsu_stop_locked(ifp, disable); RSU_UNLOCK(sc); } static void rsu_stop_locked(struct ifnet *ifp, int disable __unused) { struct rsu_softc *sc = ifp->if_softc; int i; ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); sc->sc_calibrating = 0; taskqueue_cancel_timeout(taskqueue_thread, &sc->calib_task, NULL); /* Power off adapter. */ rsu_power_off(sc); for (i = 0; i < RSU_N_TRANSFER; i++) usbd_transfer_stop(sc->sc_xfer[i]); } static void rsu_ms_delay(struct rsu_softc *sc) { usb_pause_mtx(&sc->sc_mtx, hz / 1000); } Index: head/sys/dev/usb/wlan/if_rum.c =================================================================== --- head/sys/dev/usb/wlan/if_rum.c (revision 276700) +++ head/sys/dev/usb/wlan/if_rum.c (revision 276701) @@ -1,2402 +1,2402 @@ /* $FreeBSD$ */ /*- * Copyright (c) 2005-2007 Damien Bergamini * Copyright (c) 2006 Niall O'Higgins * Copyright (c) 2007-2008 Hans Petter Selasky * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include __FBSDID("$FreeBSD$"); /*- * Ralink Technology RT2501USB/RT2601USB chipset driver * http://www.ralinktech.com.tw/ */ #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 #ifdef INET #include #include #include #include #include #endif #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR rum_debug #include #include #include #include #ifdef USB_DEBUG static int rum_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, rum, CTLFLAG_RW, 0, "USB rum"); -SYSCTL_INT(_hw_usb_rum, OID_AUTO, debug, CTLFLAG_RW, &rum_debug, 0, +SYSCTL_INT(_hw_usb_rum, OID_AUTO, debug, CTLFLAG_RWTUN, &rum_debug, 0, "Debug level"); #endif #define N(a) ((int)(sizeof (a) / sizeof ((a)[0]))) static const STRUCT_USB_HOST_ID rum_devs[] = { #define RUM_DEV(v,p) { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) } RUM_DEV(ABOCOM, HWU54DM), RUM_DEV(ABOCOM, RT2573_2), RUM_DEV(ABOCOM, RT2573_3), RUM_DEV(ABOCOM, RT2573_4), RUM_DEV(ABOCOM, WUG2700), RUM_DEV(AMIT, CGWLUSB2GO), RUM_DEV(ASUS, RT2573_1), RUM_DEV(ASUS, RT2573_2), RUM_DEV(BELKIN, F5D7050A), RUM_DEV(BELKIN, F5D9050V3), RUM_DEV(CISCOLINKSYS, WUSB54GC), RUM_DEV(CISCOLINKSYS, WUSB54GR), RUM_DEV(CONCEPTRONIC2, C54RU2), RUM_DEV(COREGA, CGWLUSB2GL), RUM_DEV(COREGA, CGWLUSB2GPX), RUM_DEV(DICKSMITH, CWD854F), RUM_DEV(DICKSMITH, RT2573), RUM_DEV(EDIMAX, EW7318USG), RUM_DEV(DLINK2, DWLG122C1), RUM_DEV(DLINK2, WUA1340), RUM_DEV(DLINK2, DWA111), RUM_DEV(DLINK2, DWA110), RUM_DEV(GIGABYTE, GNWB01GS), RUM_DEV(GIGABYTE, GNWI05GS), RUM_DEV(GIGASET, RT2573), RUM_DEV(GOODWAY, RT2573), RUM_DEV(GUILLEMOT, HWGUSB254LB), RUM_DEV(GUILLEMOT, HWGUSB254V2AP), RUM_DEV(HUAWEI3COM, WUB320G), RUM_DEV(MELCO, G54HP), RUM_DEV(MELCO, SG54HP), RUM_DEV(MELCO, SG54HG), RUM_DEV(MELCO, WLIUCG), RUM_DEV(MELCO, WLRUCG), RUM_DEV(MELCO, WLRUCGAOSS), RUM_DEV(MSI, RT2573_1), RUM_DEV(MSI, RT2573_2), RUM_DEV(MSI, RT2573_3), RUM_DEV(MSI, RT2573_4), RUM_DEV(NOVATECH, RT2573), RUM_DEV(PLANEX2, GWUS54HP), RUM_DEV(PLANEX2, GWUS54MINI2), RUM_DEV(PLANEX2, GWUSMM), RUM_DEV(QCOM, RT2573), RUM_DEV(QCOM, RT2573_2), RUM_DEV(QCOM, RT2573_3), RUM_DEV(RALINK, RT2573), RUM_DEV(RALINK, RT2573_2), RUM_DEV(RALINK, RT2671), RUM_DEV(SITECOMEU, WL113R2), RUM_DEV(SITECOMEU, WL172), RUM_DEV(SPARKLAN, RT2573), RUM_DEV(SURECOM, RT2573), #undef RUM_DEV }; static device_probe_t rum_match; static device_attach_t rum_attach; static device_detach_t rum_detach; static usb_callback_t rum_bulk_read_callback; static usb_callback_t rum_bulk_write_callback; static usb_error_t rum_do_request(struct rum_softc *sc, struct usb_device_request *req, void *data); static struct ieee80211vap *rum_vap_create(struct ieee80211com *, const char [IFNAMSIZ], int, enum ieee80211_opmode, int, const uint8_t [IEEE80211_ADDR_LEN], const uint8_t [IEEE80211_ADDR_LEN]); static void rum_vap_delete(struct ieee80211vap *); static void rum_tx_free(struct rum_tx_data *, int); static void rum_setup_tx_list(struct rum_softc *); static void rum_unsetup_tx_list(struct rum_softc *); static int rum_newstate(struct ieee80211vap *, enum ieee80211_state, int); static void rum_setup_tx_desc(struct rum_softc *, struct rum_tx_desc *, uint32_t, uint16_t, int, int); static int rum_tx_mgt(struct rum_softc *, struct mbuf *, struct ieee80211_node *); static int rum_tx_raw(struct rum_softc *, struct mbuf *, struct ieee80211_node *, const struct ieee80211_bpf_params *); static int rum_tx_data(struct rum_softc *, struct mbuf *, struct ieee80211_node *); static void rum_start(struct ifnet *); static int rum_ioctl(struct ifnet *, u_long, caddr_t); static void rum_eeprom_read(struct rum_softc *, uint16_t, void *, int); static uint32_t rum_read(struct rum_softc *, uint16_t); static void rum_read_multi(struct rum_softc *, uint16_t, void *, int); static usb_error_t rum_write(struct rum_softc *, uint16_t, uint32_t); static usb_error_t rum_write_multi(struct rum_softc *, uint16_t, void *, size_t); static void rum_bbp_write(struct rum_softc *, uint8_t, uint8_t); static uint8_t rum_bbp_read(struct rum_softc *, uint8_t); static void rum_rf_write(struct rum_softc *, uint8_t, uint32_t); static void rum_select_antenna(struct rum_softc *); static void rum_enable_mrr(struct rum_softc *); static void rum_set_txpreamble(struct rum_softc *); static void rum_set_basicrates(struct rum_softc *); static void rum_select_band(struct rum_softc *, struct ieee80211_channel *); static void rum_set_chan(struct rum_softc *, struct ieee80211_channel *); static void rum_enable_tsf_sync(struct rum_softc *); static void rum_enable_tsf(struct rum_softc *); static void rum_update_slot(struct ifnet *); static void rum_set_bssid(struct rum_softc *, const uint8_t *); static void rum_set_macaddr(struct rum_softc *, const uint8_t *); static void rum_update_mcast(struct ifnet *); static void rum_update_promisc(struct ifnet *); static void rum_setpromisc(struct rum_softc *); static const char *rum_get_rf(int); static void rum_read_eeprom(struct rum_softc *); static int rum_bbp_init(struct rum_softc *); static void rum_init_locked(struct rum_softc *); static void rum_init(void *); static void rum_stop(struct rum_softc *); static void rum_load_microcode(struct rum_softc *, const uint8_t *, size_t); static void rum_prepare_beacon(struct rum_softc *, struct ieee80211vap *); static int rum_raw_xmit(struct ieee80211_node *, struct mbuf *, const struct ieee80211_bpf_params *); static void rum_scan_start(struct ieee80211com *); static void rum_scan_end(struct ieee80211com *); static void rum_set_channel(struct ieee80211com *); static int rum_get_rssi(struct rum_softc *, uint8_t); static void rum_ratectl_start(struct rum_softc *, struct ieee80211_node *); static void rum_ratectl_timeout(void *); static void rum_ratectl_task(void *, int); static int rum_pause(struct rum_softc *, int); static const struct { uint32_t reg; uint32_t val; } rum_def_mac[] = { { RT2573_TXRX_CSR0, 0x025fb032 }, { RT2573_TXRX_CSR1, 0x9eaa9eaf }, { RT2573_TXRX_CSR2, 0x8a8b8c8d }, { RT2573_TXRX_CSR3, 0x00858687 }, { RT2573_TXRX_CSR7, 0x2e31353b }, { RT2573_TXRX_CSR8, 0x2a2a2a2c }, { RT2573_TXRX_CSR15, 0x0000000f }, { RT2573_MAC_CSR6, 0x00000fff }, { RT2573_MAC_CSR8, 0x016c030a }, { RT2573_MAC_CSR10, 0x00000718 }, { RT2573_MAC_CSR12, 0x00000004 }, { RT2573_MAC_CSR13, 0x00007f00 }, { RT2573_SEC_CSR0, 0x00000000 }, { RT2573_SEC_CSR1, 0x00000000 }, { RT2573_SEC_CSR5, 0x00000000 }, { RT2573_PHY_CSR1, 0x000023b0 }, { RT2573_PHY_CSR5, 0x00040a06 }, { RT2573_PHY_CSR6, 0x00080606 }, { RT2573_PHY_CSR7, 0x00000408 }, { RT2573_AIFSN_CSR, 0x00002273 }, { RT2573_CWMIN_CSR, 0x00002344 }, { RT2573_CWMAX_CSR, 0x000034aa } }; static const struct { uint8_t reg; uint8_t val; } rum_def_bbp[] = { { 3, 0x80 }, { 15, 0x30 }, { 17, 0x20 }, { 21, 0xc8 }, { 22, 0x38 }, { 23, 0x06 }, { 24, 0xfe }, { 25, 0x0a }, { 26, 0x0d }, { 32, 0x0b }, { 34, 0x12 }, { 37, 0x07 }, { 39, 0xf8 }, { 41, 0x60 }, { 53, 0x10 }, { 54, 0x18 }, { 60, 0x10 }, { 61, 0x04 }, { 62, 0x04 }, { 75, 0xfe }, { 86, 0xfe }, { 88, 0xfe }, { 90, 0x0f }, { 99, 0x00 }, { 102, 0x16 }, { 107, 0x04 } }; static const struct rfprog { uint8_t chan; uint32_t r1, r2, r3, r4; } rum_rf5226[] = { { 1, 0x00b03, 0x001e1, 0x1a014, 0x30282 }, { 2, 0x00b03, 0x001e1, 0x1a014, 0x30287 }, { 3, 0x00b03, 0x001e2, 0x1a014, 0x30282 }, { 4, 0x00b03, 0x001e2, 0x1a014, 0x30287 }, { 5, 0x00b03, 0x001e3, 0x1a014, 0x30282 }, { 6, 0x00b03, 0x001e3, 0x1a014, 0x30287 }, { 7, 0x00b03, 0x001e4, 0x1a014, 0x30282 }, { 8, 0x00b03, 0x001e4, 0x1a014, 0x30287 }, { 9, 0x00b03, 0x001e5, 0x1a014, 0x30282 }, { 10, 0x00b03, 0x001e5, 0x1a014, 0x30287 }, { 11, 0x00b03, 0x001e6, 0x1a014, 0x30282 }, { 12, 0x00b03, 0x001e6, 0x1a014, 0x30287 }, { 13, 0x00b03, 0x001e7, 0x1a014, 0x30282 }, { 14, 0x00b03, 0x001e8, 0x1a014, 0x30284 }, { 34, 0x00b03, 0x20266, 0x36014, 0x30282 }, { 38, 0x00b03, 0x20267, 0x36014, 0x30284 }, { 42, 0x00b03, 0x20268, 0x36014, 0x30286 }, { 46, 0x00b03, 0x20269, 0x36014, 0x30288 }, { 36, 0x00b03, 0x00266, 0x26014, 0x30288 }, { 40, 0x00b03, 0x00268, 0x26014, 0x30280 }, { 44, 0x00b03, 0x00269, 0x26014, 0x30282 }, { 48, 0x00b03, 0x0026a, 0x26014, 0x30284 }, { 52, 0x00b03, 0x0026b, 0x26014, 0x30286 }, { 56, 0x00b03, 0x0026c, 0x26014, 0x30288 }, { 60, 0x00b03, 0x0026e, 0x26014, 0x30280 }, { 64, 0x00b03, 0x0026f, 0x26014, 0x30282 }, { 100, 0x00b03, 0x0028a, 0x2e014, 0x30280 }, { 104, 0x00b03, 0x0028b, 0x2e014, 0x30282 }, { 108, 0x00b03, 0x0028c, 0x2e014, 0x30284 }, { 112, 0x00b03, 0x0028d, 0x2e014, 0x30286 }, { 116, 0x00b03, 0x0028e, 0x2e014, 0x30288 }, { 120, 0x00b03, 0x002a0, 0x2e014, 0x30280 }, { 124, 0x00b03, 0x002a1, 0x2e014, 0x30282 }, { 128, 0x00b03, 0x002a2, 0x2e014, 0x30284 }, { 132, 0x00b03, 0x002a3, 0x2e014, 0x30286 }, { 136, 0x00b03, 0x002a4, 0x2e014, 0x30288 }, { 140, 0x00b03, 0x002a6, 0x2e014, 0x30280 }, { 149, 0x00b03, 0x002a8, 0x2e014, 0x30287 }, { 153, 0x00b03, 0x002a9, 0x2e014, 0x30289 }, { 157, 0x00b03, 0x002ab, 0x2e014, 0x30281 }, { 161, 0x00b03, 0x002ac, 0x2e014, 0x30283 }, { 165, 0x00b03, 0x002ad, 0x2e014, 0x30285 } }, rum_rf5225[] = { { 1, 0x00b33, 0x011e1, 0x1a014, 0x30282 }, { 2, 0x00b33, 0x011e1, 0x1a014, 0x30287 }, { 3, 0x00b33, 0x011e2, 0x1a014, 0x30282 }, { 4, 0x00b33, 0x011e2, 0x1a014, 0x30287 }, { 5, 0x00b33, 0x011e3, 0x1a014, 0x30282 }, { 6, 0x00b33, 0x011e3, 0x1a014, 0x30287 }, { 7, 0x00b33, 0x011e4, 0x1a014, 0x30282 }, { 8, 0x00b33, 0x011e4, 0x1a014, 0x30287 }, { 9, 0x00b33, 0x011e5, 0x1a014, 0x30282 }, { 10, 0x00b33, 0x011e5, 0x1a014, 0x30287 }, { 11, 0x00b33, 0x011e6, 0x1a014, 0x30282 }, { 12, 0x00b33, 0x011e6, 0x1a014, 0x30287 }, { 13, 0x00b33, 0x011e7, 0x1a014, 0x30282 }, { 14, 0x00b33, 0x011e8, 0x1a014, 0x30284 }, { 34, 0x00b33, 0x01266, 0x26014, 0x30282 }, { 38, 0x00b33, 0x01267, 0x26014, 0x30284 }, { 42, 0x00b33, 0x01268, 0x26014, 0x30286 }, { 46, 0x00b33, 0x01269, 0x26014, 0x30288 }, { 36, 0x00b33, 0x01266, 0x26014, 0x30288 }, { 40, 0x00b33, 0x01268, 0x26014, 0x30280 }, { 44, 0x00b33, 0x01269, 0x26014, 0x30282 }, { 48, 0x00b33, 0x0126a, 0x26014, 0x30284 }, { 52, 0x00b33, 0x0126b, 0x26014, 0x30286 }, { 56, 0x00b33, 0x0126c, 0x26014, 0x30288 }, { 60, 0x00b33, 0x0126e, 0x26014, 0x30280 }, { 64, 0x00b33, 0x0126f, 0x26014, 0x30282 }, { 100, 0x00b33, 0x0128a, 0x2e014, 0x30280 }, { 104, 0x00b33, 0x0128b, 0x2e014, 0x30282 }, { 108, 0x00b33, 0x0128c, 0x2e014, 0x30284 }, { 112, 0x00b33, 0x0128d, 0x2e014, 0x30286 }, { 116, 0x00b33, 0x0128e, 0x2e014, 0x30288 }, { 120, 0x00b33, 0x012a0, 0x2e014, 0x30280 }, { 124, 0x00b33, 0x012a1, 0x2e014, 0x30282 }, { 128, 0x00b33, 0x012a2, 0x2e014, 0x30284 }, { 132, 0x00b33, 0x012a3, 0x2e014, 0x30286 }, { 136, 0x00b33, 0x012a4, 0x2e014, 0x30288 }, { 140, 0x00b33, 0x012a6, 0x2e014, 0x30280 }, { 149, 0x00b33, 0x012a8, 0x2e014, 0x30287 }, { 153, 0x00b33, 0x012a9, 0x2e014, 0x30289 }, { 157, 0x00b33, 0x012ab, 0x2e014, 0x30281 }, { 161, 0x00b33, 0x012ac, 0x2e014, 0x30283 }, { 165, 0x00b33, 0x012ad, 0x2e014, 0x30285 } }; static const struct usb_config rum_config[RUM_N_TRANSFER] = { [RUM_BULK_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = (MCLBYTES + RT2573_TX_DESC_SIZE + 8), .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = rum_bulk_write_callback, .timeout = 5000, /* ms */ }, [RUM_BULK_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = (MCLBYTES + RT2573_RX_DESC_SIZE), .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = rum_bulk_read_callback, }, }; static int rum_match(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != 0) return (ENXIO); if (uaa->info.bIfaceIndex != RT2573_IFACE_INDEX) return (ENXIO); return (usbd_lookup_id_by_uaa(rum_devs, sizeof(rum_devs), uaa)); } static int rum_attach(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); struct rum_softc *sc = device_get_softc(self); struct ieee80211com *ic; struct ifnet *ifp; uint8_t iface_index, bands; uint32_t tmp; int error, ntries; device_set_usb_desc(self); sc->sc_udev = uaa->device; sc->sc_dev = self; mtx_init(&sc->sc_mtx, device_get_nameunit(self), MTX_NETWORK_LOCK, MTX_DEF); iface_index = RT2573_IFACE_INDEX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, rum_config, RUM_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(self, "could not allocate USB transfers, " "err=%s\n", usbd_errstr(error)); goto detach; } RUM_LOCK(sc); /* retrieve RT2573 rev. no */ for (ntries = 0; ntries < 100; ntries++) { if ((tmp = rum_read(sc, RT2573_MAC_CSR0)) != 0) break; if (rum_pause(sc, hz / 100)) break; } if (ntries == 100) { device_printf(sc->sc_dev, "timeout waiting for chip to settle\n"); RUM_UNLOCK(sc); goto detach; } /* retrieve MAC address and various other things from EEPROM */ rum_read_eeprom(sc); device_printf(sc->sc_dev, "MAC/BBP RT2573 (rev 0x%05x), RF %s\n", tmp, rum_get_rf(sc->rf_rev)); rum_load_microcode(sc, rt2573_ucode, sizeof(rt2573_ucode)); RUM_UNLOCK(sc); ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211); if (ifp == NULL) { device_printf(sc->sc_dev, "can not if_alloc()\n"); goto detach; } ic = ifp->if_l2com; ifp->if_softc = sc; if_initname(ifp, "rum", device_get_unit(sc->sc_dev)); ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; ifp->if_init = rum_init; ifp->if_ioctl = rum_ioctl; ifp->if_start = rum_start; IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen); ifp->if_snd.ifq_drv_maxlen = ifqmaxlen; IFQ_SET_READY(&ifp->if_snd); ic->ic_ifp = ifp; ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */ /* set device capabilities */ ic->ic_caps = IEEE80211_C_STA /* station mode supported */ | IEEE80211_C_IBSS /* IBSS mode supported */ | IEEE80211_C_MONITOR /* monitor mode supported */ | IEEE80211_C_HOSTAP /* HostAp mode supported */ | IEEE80211_C_TXPMGT /* tx power management */ | IEEE80211_C_SHPREAMBLE /* short preamble supported */ | IEEE80211_C_SHSLOT /* short slot time supported */ | IEEE80211_C_BGSCAN /* bg scanning supported */ | IEEE80211_C_WPA /* 802.11i */ ; bands = 0; setbit(&bands, IEEE80211_MODE_11B); setbit(&bands, IEEE80211_MODE_11G); if (sc->rf_rev == RT2573_RF_5225 || sc->rf_rev == RT2573_RF_5226) setbit(&bands, IEEE80211_MODE_11A); ieee80211_init_channels(ic, NULL, &bands); ieee80211_ifattach(ic, sc->sc_bssid); ic->ic_update_promisc = rum_update_promisc; ic->ic_raw_xmit = rum_raw_xmit; ic->ic_scan_start = rum_scan_start; ic->ic_scan_end = rum_scan_end; ic->ic_set_channel = rum_set_channel; ic->ic_vap_create = rum_vap_create; ic->ic_vap_delete = rum_vap_delete; ic->ic_update_mcast = rum_update_mcast; ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap), RT2573_TX_RADIOTAP_PRESENT, &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap), RT2573_RX_RADIOTAP_PRESENT); if (bootverbose) ieee80211_announce(ic); return (0); detach: rum_detach(self); return (ENXIO); /* failure */ } static int rum_detach(device_t self) { struct rum_softc *sc = device_get_softc(self); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic; /* Prevent further ioctls */ RUM_LOCK(sc); sc->sc_detached = 1; RUM_UNLOCK(sc); /* stop all USB transfers */ usbd_transfer_unsetup(sc->sc_xfer, RUM_N_TRANSFER); /* free TX list, if any */ RUM_LOCK(sc); rum_unsetup_tx_list(sc); RUM_UNLOCK(sc); if (ifp) { ic = ifp->if_l2com; ieee80211_ifdetach(ic); if_free(ifp); } mtx_destroy(&sc->sc_mtx); return (0); } static usb_error_t rum_do_request(struct rum_softc *sc, struct usb_device_request *req, void *data) { usb_error_t err; int ntries = 10; while (ntries--) { err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx, req, data, 0, NULL, 250 /* ms */); if (err == 0) break; DPRINTFN(1, "Control request failed, %s (retrying)\n", usbd_errstr(err)); if (rum_pause(sc, hz / 100)) break; } return (err); } static struct ieee80211vap * rum_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit, enum ieee80211_opmode opmode, int flags, const uint8_t bssid[IEEE80211_ADDR_LEN], const uint8_t mac[IEEE80211_ADDR_LEN]) { struct rum_softc *sc = ic->ic_ifp->if_softc; struct rum_vap *rvp; struct ieee80211vap *vap; if (!TAILQ_EMPTY(&ic->ic_vaps)) /* only one at a time */ return NULL; rvp = (struct rum_vap *) malloc(sizeof(struct rum_vap), M_80211_VAP, M_NOWAIT | M_ZERO); if (rvp == NULL) return NULL; vap = &rvp->vap; /* enable s/w bmiss handling for sta mode */ if (ieee80211_vap_setup(ic, vap, name, unit, opmode, flags | IEEE80211_CLONE_NOBEACONS, bssid, mac) != 0) { /* out of memory */ free(rvp, M_80211_VAP); return (NULL); } /* override state transition machine */ rvp->newstate = vap->iv_newstate; vap->iv_newstate = rum_newstate; usb_callout_init_mtx(&rvp->ratectl_ch, &sc->sc_mtx, 0); TASK_INIT(&rvp->ratectl_task, 0, rum_ratectl_task, rvp); ieee80211_ratectl_init(vap); ieee80211_ratectl_setinterval(vap, 1000 /* 1 sec */); /* complete setup */ ieee80211_vap_attach(vap, ieee80211_media_change, ieee80211_media_status); ic->ic_opmode = opmode; return vap; } static void rum_vap_delete(struct ieee80211vap *vap) { struct rum_vap *rvp = RUM_VAP(vap); struct ieee80211com *ic = vap->iv_ic; usb_callout_drain(&rvp->ratectl_ch); ieee80211_draintask(ic, &rvp->ratectl_task); ieee80211_ratectl_deinit(vap); ieee80211_vap_detach(vap); free(rvp, M_80211_VAP); } static void rum_tx_free(struct rum_tx_data *data, int txerr) { struct rum_softc *sc = data->sc; if (data->m != NULL) { if (data->m->m_flags & M_TXCB) ieee80211_process_callback(data->ni, data->m, txerr ? ETIMEDOUT : 0); m_freem(data->m); data->m = NULL; ieee80211_free_node(data->ni); data->ni = NULL; } STAILQ_INSERT_TAIL(&sc->tx_free, data, next); sc->tx_nfree++; } static void rum_setup_tx_list(struct rum_softc *sc) { struct rum_tx_data *data; int i; sc->tx_nfree = 0; STAILQ_INIT(&sc->tx_q); STAILQ_INIT(&sc->tx_free); for (i = 0; i < RUM_TX_LIST_COUNT; i++) { data = &sc->tx_data[i]; data->sc = sc; STAILQ_INSERT_TAIL(&sc->tx_free, data, next); sc->tx_nfree++; } } static void rum_unsetup_tx_list(struct rum_softc *sc) { struct rum_tx_data *data; int i; /* make sure any subsequent use of the queues will fail */ sc->tx_nfree = 0; STAILQ_INIT(&sc->tx_q); STAILQ_INIT(&sc->tx_free); /* free up all node references and mbufs */ for (i = 0; i < RUM_TX_LIST_COUNT; i++) { data = &sc->tx_data[i]; if (data->m != NULL) { m_freem(data->m); data->m = NULL; } if (data->ni != NULL) { ieee80211_free_node(data->ni); data->ni = NULL; } } } static int rum_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg) { struct rum_vap *rvp = RUM_VAP(vap); struct ieee80211com *ic = vap->iv_ic; struct rum_softc *sc = ic->ic_ifp->if_softc; const struct ieee80211_txparam *tp; enum ieee80211_state ostate; struct ieee80211_node *ni; uint32_t tmp; ostate = vap->iv_state; DPRINTF("%s -> %s\n", ieee80211_state_name[ostate], ieee80211_state_name[nstate]); IEEE80211_UNLOCK(ic); RUM_LOCK(sc); usb_callout_stop(&rvp->ratectl_ch); switch (nstate) { case IEEE80211_S_INIT: if (ostate == IEEE80211_S_RUN) { /* abort TSF synchronization */ tmp = rum_read(sc, RT2573_TXRX_CSR9); rum_write(sc, RT2573_TXRX_CSR9, tmp & ~0x00ffffff); } break; case IEEE80211_S_RUN: ni = ieee80211_ref_node(vap->iv_bss); if (vap->iv_opmode != IEEE80211_M_MONITOR) { if (ic->ic_bsschan == IEEE80211_CHAN_ANYC) { RUM_UNLOCK(sc); IEEE80211_LOCK(ic); ieee80211_free_node(ni); return (-1); } rum_update_slot(ic->ic_ifp); rum_enable_mrr(sc); rum_set_txpreamble(sc); rum_set_basicrates(sc); IEEE80211_ADDR_COPY(sc->sc_bssid, ni->ni_bssid); rum_set_bssid(sc, sc->sc_bssid); } if (vap->iv_opmode == IEEE80211_M_HOSTAP || vap->iv_opmode == IEEE80211_M_IBSS) rum_prepare_beacon(sc, vap); if (vap->iv_opmode != IEEE80211_M_MONITOR) rum_enable_tsf_sync(sc); else rum_enable_tsf(sc); /* enable automatic rate adaptation */ tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)]; if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE) rum_ratectl_start(sc, ni); ieee80211_free_node(ni); break; default: break; } RUM_UNLOCK(sc); IEEE80211_LOCK(ic); return (rvp->newstate(vap, nstate, arg)); } static void rum_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct rum_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct ieee80211vap *vap; struct rum_tx_data *data; struct mbuf *m; struct usb_page_cache *pc; unsigned int len; int actlen, sumlen; usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(11, "transfer complete, %d bytes\n", actlen); /* free resources */ data = usbd_xfer_get_priv(xfer); rum_tx_free(data, 0); usbd_xfer_set_priv(xfer, NULL); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: data = STAILQ_FIRST(&sc->tx_q); if (data) { STAILQ_REMOVE_HEAD(&sc->tx_q, next); m = data->m; if (m->m_pkthdr.len > (int)(MCLBYTES + RT2573_TX_DESC_SIZE)) { DPRINTFN(0, "data overflow, %u bytes\n", m->m_pkthdr.len); m->m_pkthdr.len = (MCLBYTES + RT2573_TX_DESC_SIZE); } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, &data->desc, RT2573_TX_DESC_SIZE); usbd_m_copy_in(pc, RT2573_TX_DESC_SIZE, m, 0, m->m_pkthdr.len); vap = data->ni->ni_vap; if (ieee80211_radiotap_active_vap(vap)) { struct rum_tx_radiotap_header *tap = &sc->sc_txtap; tap->wt_flags = 0; tap->wt_rate = data->rate; tap->wt_antenna = sc->tx_ant; ieee80211_radiotap_tx(vap, m); } /* align end on a 4-bytes boundary */ len = (RT2573_TX_DESC_SIZE + m->m_pkthdr.len + 3) & ~3; if ((len % 64) == 0) len += 4; DPRINTFN(11, "sending frame len=%u xferlen=%u\n", m->m_pkthdr.len, len); usbd_xfer_set_frame_len(xfer, 0, len); usbd_xfer_set_priv(xfer, data); usbd_transfer_submit(xfer); } RUM_UNLOCK(sc); rum_start(ifp); RUM_LOCK(sc); break; default: /* Error */ DPRINTFN(11, "transfer error, %s\n", usbd_errstr(error)); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); data = usbd_xfer_get_priv(xfer); if (data != NULL) { rum_tx_free(data, error); usbd_xfer_set_priv(xfer, NULL); } if (error != USB_ERR_CANCELLED) { if (error == USB_ERR_TIMEOUT) device_printf(sc->sc_dev, "device timeout\n"); /* * Try to clear stall first, also if other * errors occur, hence clearing stall * introduces a 50 ms delay: */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void rum_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct rum_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211_node *ni; struct mbuf *m = NULL; struct usb_page_cache *pc; uint32_t flags; uint8_t rssi = 0; int len; usbd_xfer_status(xfer, &len, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(15, "rx done, actlen=%d\n", len); if (len < (int)(RT2573_RX_DESC_SIZE + IEEE80211_MIN_LEN)) { DPRINTF("%s: xfer too short %d\n", device_get_nameunit(sc->sc_dev), len); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } len -= RT2573_RX_DESC_SIZE; pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, &sc->sc_rx_desc, RT2573_RX_DESC_SIZE); rssi = rum_get_rssi(sc, sc->sc_rx_desc.rssi); flags = le32toh(sc->sc_rx_desc.flags); if (flags & RT2573_RX_CRC_ERROR) { /* * This should not happen since we did not * request to receive those frames when we * filled RUM_TXRX_CSR2: */ DPRINTFN(5, "PHY or CRC error\n"); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); if (m == NULL) { DPRINTF("could not allocate mbuf\n"); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } usbd_copy_out(pc, RT2573_RX_DESC_SIZE, mtod(m, uint8_t *), len); /* finalize mbuf */ m->m_pkthdr.rcvif = ifp; m->m_pkthdr.len = m->m_len = (flags >> 16) & 0xfff; if (ieee80211_radiotap_active(ic)) { struct rum_rx_radiotap_header *tap = &sc->sc_rxtap; /* XXX read tsf */ tap->wr_flags = 0; tap->wr_rate = ieee80211_plcp2rate(sc->sc_rx_desc.rate, (flags & RT2573_RX_OFDM) ? IEEE80211_T_OFDM : IEEE80211_T_CCK); tap->wr_antsignal = RT2573_NOISE_FLOOR + rssi; tap->wr_antnoise = RT2573_NOISE_FLOOR; tap->wr_antenna = sc->rx_ant; } /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); /* * At the end of a USB callback it is always safe to unlock * the private mutex of a device! That is why we do the * "ieee80211_input" here, and not some lines up! */ RUM_UNLOCK(sc); if (m) { ni = ieee80211_find_rxnode(ic, mtod(m, struct ieee80211_frame_min *)); if (ni != NULL) { (void) ieee80211_input(ni, m, rssi, RT2573_NOISE_FLOOR); ieee80211_free_node(ni); } else (void) ieee80211_input_all(ic, m, rssi, RT2573_NOISE_FLOOR); } if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0 && !IFQ_IS_EMPTY(&ifp->if_snd)) rum_start(ifp); RUM_LOCK(sc); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static uint8_t rum_plcp_signal(int rate) { switch (rate) { /* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */ case 12: return 0xb; case 18: return 0xf; case 24: return 0xa; case 36: return 0xe; case 48: return 0x9; case 72: return 0xd; case 96: return 0x8; case 108: return 0xc; /* CCK rates (NB: not IEEE std, device-specific) */ case 2: return 0x0; case 4: return 0x1; case 11: return 0x2; case 22: return 0x3; } return 0xff; /* XXX unsupported/unknown rate */ } static void rum_setup_tx_desc(struct rum_softc *sc, struct rum_tx_desc *desc, uint32_t flags, uint16_t xflags, int len, int rate) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; uint16_t plcp_length; int remainder; desc->flags = htole32(flags); desc->flags |= htole32(RT2573_TX_VALID); desc->flags |= htole32(len << 16); desc->xflags = htole16(xflags); desc->wme = htole16(RT2573_QID(0) | RT2573_AIFSN(2) | RT2573_LOGCWMIN(4) | RT2573_LOGCWMAX(10)); /* setup PLCP fields */ desc->plcp_signal = rum_plcp_signal(rate); desc->plcp_service = 4; len += IEEE80211_CRC_LEN; if (ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM) { desc->flags |= htole32(RT2573_TX_OFDM); plcp_length = len & 0xfff; desc->plcp_length_hi = plcp_length >> 6; desc->plcp_length_lo = plcp_length & 0x3f; } else { if (rate == 0) rate = 2; /* avoid division by zero */ plcp_length = (16 * len + rate - 1) / rate; if (rate == 22) { remainder = (16 * len) % 22; if (remainder != 0 && remainder < 7) desc->plcp_service |= RT2573_PLCP_LENGEXT; } desc->plcp_length_hi = plcp_length >> 8; desc->plcp_length_lo = plcp_length & 0xff; if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE)) desc->plcp_signal |= 0x08; } } static int rum_sendprot(struct rum_softc *sc, const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate) { struct ieee80211com *ic = ni->ni_ic; const struct ieee80211_frame *wh; struct rum_tx_data *data; struct mbuf *mprot; int protrate, ackrate, pktlen, flags, isshort; uint16_t dur; RUM_LOCK_ASSERT(sc, MA_OWNED); KASSERT(prot == IEEE80211_PROT_RTSCTS || prot == IEEE80211_PROT_CTSONLY, ("protection %d", prot)); wh = mtod(m, const struct ieee80211_frame *); pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN; protrate = ieee80211_ctl_rate(ic->ic_rt, rate); ackrate = ieee80211_ack_rate(ic->ic_rt, rate); isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0; dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort) + ieee80211_ack_duration(ic->ic_rt, rate, isshort); flags = RT2573_TX_MORE_FRAG; if (prot == IEEE80211_PROT_RTSCTS) { /* NB: CTS is the same size as an ACK */ dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort); flags |= RT2573_TX_NEED_ACK; mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur); } else { mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur); } if (mprot == NULL) { /* XXX stat + msg */ return (ENOBUFS); } data = STAILQ_FIRST(&sc->tx_free); STAILQ_REMOVE_HEAD(&sc->tx_free, next); sc->tx_nfree--; data->m = mprot; data->ni = ieee80211_ref_node(ni); data->rate = protrate; rum_setup_tx_desc(sc, &data->desc, flags, 0, mprot->m_pkthdr.len, protrate); STAILQ_INSERT_TAIL(&sc->tx_q, data, next); usbd_transfer_start(sc->sc_xfer[RUM_BULK_WR]); return 0; } static int rum_tx_mgt(struct rum_softc *sc, struct mbuf *m0, struct ieee80211_node *ni) { struct ieee80211vap *vap = ni->ni_vap; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct rum_tx_data *data; struct ieee80211_frame *wh; const struct ieee80211_txparam *tp; struct ieee80211_key *k; uint32_t flags = 0; uint16_t dur; RUM_LOCK_ASSERT(sc, MA_OWNED); data = STAILQ_FIRST(&sc->tx_free); STAILQ_REMOVE_HEAD(&sc->tx_free, next); sc->tx_nfree--; wh = mtod(m0, struct ieee80211_frame *); if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) { k = ieee80211_crypto_encap(ni, m0); if (k == NULL) { m_freem(m0); return ENOBUFS; } wh = mtod(m0, struct ieee80211_frame *); } tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)]; if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) { flags |= RT2573_TX_NEED_ACK; dur = ieee80211_ack_duration(ic->ic_rt, tp->mgmtrate, ic->ic_flags & IEEE80211_F_SHPREAMBLE); USETW(wh->i_dur, dur); /* tell hardware to add timestamp for probe responses */ if ((wh->i_fc[0] & (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) == (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP)) flags |= RT2573_TX_TIMESTAMP; } data->m = m0; data->ni = ni; data->rate = tp->mgmtrate; rum_setup_tx_desc(sc, &data->desc, flags, 0, m0->m_pkthdr.len, tp->mgmtrate); DPRINTFN(10, "sending mgt frame len=%d rate=%d\n", m0->m_pkthdr.len + (int)RT2573_TX_DESC_SIZE, tp->mgmtrate); STAILQ_INSERT_TAIL(&sc->tx_q, data, next); usbd_transfer_start(sc->sc_xfer[RUM_BULK_WR]); return (0); } static int rum_tx_raw(struct rum_softc *sc, struct mbuf *m0, struct ieee80211_node *ni, const struct ieee80211_bpf_params *params) { struct ieee80211com *ic = ni->ni_ic; struct rum_tx_data *data; uint32_t flags; int rate, error; RUM_LOCK_ASSERT(sc, MA_OWNED); KASSERT(params != NULL, ("no raw xmit params")); rate = params->ibp_rate0; if (!ieee80211_isratevalid(ic->ic_rt, rate)) { m_freem(m0); return EINVAL; } flags = 0; if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0) flags |= RT2573_TX_NEED_ACK; if (params->ibp_flags & (IEEE80211_BPF_RTS|IEEE80211_BPF_CTS)) { error = rum_sendprot(sc, m0, ni, params->ibp_flags & IEEE80211_BPF_RTS ? IEEE80211_PROT_RTSCTS : IEEE80211_PROT_CTSONLY, rate); if (error || sc->tx_nfree == 0) { m_freem(m0); return ENOBUFS; } flags |= RT2573_TX_LONG_RETRY | RT2573_TX_IFS_SIFS; } data = STAILQ_FIRST(&sc->tx_free); STAILQ_REMOVE_HEAD(&sc->tx_free, next); sc->tx_nfree--; data->m = m0; data->ni = ni; data->rate = rate; /* XXX need to setup descriptor ourself */ rum_setup_tx_desc(sc, &data->desc, flags, 0, m0->m_pkthdr.len, rate); DPRINTFN(10, "sending raw frame len=%u rate=%u\n", m0->m_pkthdr.len, rate); STAILQ_INSERT_TAIL(&sc->tx_q, data, next); usbd_transfer_start(sc->sc_xfer[RUM_BULK_WR]); return 0; } static int rum_tx_data(struct rum_softc *sc, struct mbuf *m0, struct ieee80211_node *ni) { struct ieee80211vap *vap = ni->ni_vap; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct rum_tx_data *data; struct ieee80211_frame *wh; const struct ieee80211_txparam *tp; struct ieee80211_key *k; uint32_t flags = 0; uint16_t dur; int error, rate; RUM_LOCK_ASSERT(sc, MA_OWNED); wh = mtod(m0, struct ieee80211_frame *); tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)]; if (IEEE80211_IS_MULTICAST(wh->i_addr1)) rate = tp->mcastrate; else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) rate = tp->ucastrate; else rate = ni->ni_txrate; if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) { k = ieee80211_crypto_encap(ni, m0); if (k == NULL) { m_freem(m0); return ENOBUFS; } /* packet header may have moved, reset our local pointer */ wh = mtod(m0, struct ieee80211_frame *); } if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) { int prot = IEEE80211_PROT_NONE; if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold) prot = IEEE80211_PROT_RTSCTS; else if ((ic->ic_flags & IEEE80211_F_USEPROT) && ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM) prot = ic->ic_protmode; if (prot != IEEE80211_PROT_NONE) { error = rum_sendprot(sc, m0, ni, prot, rate); if (error || sc->tx_nfree == 0) { m_freem(m0); return ENOBUFS; } flags |= RT2573_TX_LONG_RETRY | RT2573_TX_IFS_SIFS; } } data = STAILQ_FIRST(&sc->tx_free); STAILQ_REMOVE_HEAD(&sc->tx_free, next); sc->tx_nfree--; data->m = m0; data->ni = ni; data->rate = rate; if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) { flags |= RT2573_TX_NEED_ACK; flags |= RT2573_TX_MORE_FRAG; dur = ieee80211_ack_duration(ic->ic_rt, rate, ic->ic_flags & IEEE80211_F_SHPREAMBLE); USETW(wh->i_dur, dur); } rum_setup_tx_desc(sc, &data->desc, flags, 0, m0->m_pkthdr.len, rate); DPRINTFN(10, "sending frame len=%d rate=%d\n", m0->m_pkthdr.len + (int)RT2573_TX_DESC_SIZE, rate); STAILQ_INSERT_TAIL(&sc->tx_q, data, next); usbd_transfer_start(sc->sc_xfer[RUM_BULK_WR]); return 0; } static void rum_start(struct ifnet *ifp) { struct rum_softc *sc = ifp->if_softc; struct ieee80211_node *ni; struct mbuf *m; RUM_LOCK(sc); if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) { RUM_UNLOCK(sc); return; } for (;;) { IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; if (sc->tx_nfree < RUM_TX_MINFREE) { IFQ_DRV_PREPEND(&ifp->if_snd, m); ifp->if_drv_flags |= IFF_DRV_OACTIVE; break; } ni = (struct ieee80211_node *) m->m_pkthdr.rcvif; if (rum_tx_data(sc, m, ni) != 0) { ieee80211_free_node(ni); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); break; } } RUM_UNLOCK(sc); } static int rum_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) { struct rum_softc *sc = ifp->if_softc; struct ieee80211com *ic = ifp->if_l2com; struct ifreq *ifr = (struct ifreq *) data; int error; int startall = 0; RUM_LOCK(sc); error = sc->sc_detached ? ENXIO : 0; RUM_UNLOCK(sc); if (error) return (error); switch (cmd) { case SIOCSIFFLAGS: RUM_LOCK(sc); if (ifp->if_flags & IFF_UP) { if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) { rum_init_locked(sc); startall = 1; } else rum_setpromisc(sc); } else { if (ifp->if_drv_flags & IFF_DRV_RUNNING) rum_stop(sc); } RUM_UNLOCK(sc); if (startall) ieee80211_start_all(ic); break; case SIOCGIFMEDIA: error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd); break; case SIOCGIFADDR: error = ether_ioctl(ifp, cmd, data); break; default: error = EINVAL; break; } return error; } static void rum_eeprom_read(struct rum_softc *sc, uint16_t addr, void *buf, int len) { struct usb_device_request req; usb_error_t error; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = RT2573_READ_EEPROM; USETW(req.wValue, 0); USETW(req.wIndex, addr); USETW(req.wLength, len); error = rum_do_request(sc, &req, buf); if (error != 0) { device_printf(sc->sc_dev, "could not read EEPROM: %s\n", usbd_errstr(error)); } } static uint32_t rum_read(struct rum_softc *sc, uint16_t reg) { uint32_t val; rum_read_multi(sc, reg, &val, sizeof val); return le32toh(val); } static void rum_read_multi(struct rum_softc *sc, uint16_t reg, void *buf, int len) { struct usb_device_request req; usb_error_t error; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = RT2573_READ_MULTI_MAC; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, len); error = rum_do_request(sc, &req, buf); if (error != 0) { device_printf(sc->sc_dev, "could not multi read MAC register: %s\n", usbd_errstr(error)); } } static usb_error_t rum_write(struct rum_softc *sc, uint16_t reg, uint32_t val) { uint32_t tmp = htole32(val); return (rum_write_multi(sc, reg, &tmp, sizeof tmp)); } static usb_error_t rum_write_multi(struct rum_softc *sc, uint16_t reg, void *buf, size_t len) { struct usb_device_request req; usb_error_t error; size_t offset; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = RT2573_WRITE_MULTI_MAC; USETW(req.wValue, 0); /* write at most 64 bytes at a time */ for (offset = 0; offset < len; offset += 64) { USETW(req.wIndex, reg + offset); USETW(req.wLength, MIN(len - offset, 64)); error = rum_do_request(sc, &req, (char *)buf + offset); if (error != 0) { device_printf(sc->sc_dev, "could not multi write MAC register: %s\n", usbd_errstr(error)); return (error); } } return (USB_ERR_NORMAL_COMPLETION); } static void rum_bbp_write(struct rum_softc *sc, uint8_t reg, uint8_t val) { uint32_t tmp; int ntries; DPRINTFN(2, "reg=0x%08x\n", reg); for (ntries = 0; ntries < 100; ntries++) { if (!(rum_read(sc, RT2573_PHY_CSR3) & RT2573_BBP_BUSY)) break; if (rum_pause(sc, hz / 100)) break; } if (ntries == 100) { device_printf(sc->sc_dev, "could not write to BBP\n"); return; } tmp = RT2573_BBP_BUSY | (reg & 0x7f) << 8 | val; rum_write(sc, RT2573_PHY_CSR3, tmp); } static uint8_t rum_bbp_read(struct rum_softc *sc, uint8_t reg) { uint32_t val; int ntries; DPRINTFN(2, "reg=0x%08x\n", reg); for (ntries = 0; ntries < 100; ntries++) { if (!(rum_read(sc, RT2573_PHY_CSR3) & RT2573_BBP_BUSY)) break; if (rum_pause(sc, hz / 100)) break; } if (ntries == 100) { device_printf(sc->sc_dev, "could not read BBP\n"); return 0; } val = RT2573_BBP_BUSY | RT2573_BBP_READ | reg << 8; rum_write(sc, RT2573_PHY_CSR3, val); for (ntries = 0; ntries < 100; ntries++) { val = rum_read(sc, RT2573_PHY_CSR3); if (!(val & RT2573_BBP_BUSY)) return val & 0xff; if (rum_pause(sc, hz / 100)) break; } device_printf(sc->sc_dev, "could not read BBP\n"); return 0; } static void rum_rf_write(struct rum_softc *sc, uint8_t reg, uint32_t val) { uint32_t tmp; int ntries; for (ntries = 0; ntries < 100; ntries++) { if (!(rum_read(sc, RT2573_PHY_CSR4) & RT2573_RF_BUSY)) break; if (rum_pause(sc, hz / 100)) break; } if (ntries == 100) { device_printf(sc->sc_dev, "could not write to RF\n"); return; } tmp = RT2573_RF_BUSY | RT2573_RF_20BIT | (val & 0xfffff) << 2 | (reg & 3); rum_write(sc, RT2573_PHY_CSR4, tmp); /* remember last written value in sc */ sc->rf_regs[reg] = val; DPRINTFN(15, "RF R[%u] <- 0x%05x\n", reg & 3, val & 0xfffff); } static void rum_select_antenna(struct rum_softc *sc) { uint8_t bbp4, bbp77; uint32_t tmp; bbp4 = rum_bbp_read(sc, 4); bbp77 = rum_bbp_read(sc, 77); /* TBD */ /* make sure Rx is disabled before switching antenna */ tmp = rum_read(sc, RT2573_TXRX_CSR0); rum_write(sc, RT2573_TXRX_CSR0, tmp | RT2573_DISABLE_RX); rum_bbp_write(sc, 4, bbp4); rum_bbp_write(sc, 77, bbp77); rum_write(sc, RT2573_TXRX_CSR0, tmp); } /* * Enable multi-rate retries for frames sent at OFDM rates. * In 802.11b/g mode, allow fallback to CCK rates. */ static void rum_enable_mrr(struct rum_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; uint32_t tmp; tmp = rum_read(sc, RT2573_TXRX_CSR4); tmp &= ~RT2573_MRR_CCK_FALLBACK; if (!IEEE80211_IS_CHAN_5GHZ(ic->ic_bsschan)) tmp |= RT2573_MRR_CCK_FALLBACK; tmp |= RT2573_MRR_ENABLED; rum_write(sc, RT2573_TXRX_CSR4, tmp); } static void rum_set_txpreamble(struct rum_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; uint32_t tmp; tmp = rum_read(sc, RT2573_TXRX_CSR4); tmp &= ~RT2573_SHORT_PREAMBLE; if (ic->ic_flags & IEEE80211_F_SHPREAMBLE) tmp |= RT2573_SHORT_PREAMBLE; rum_write(sc, RT2573_TXRX_CSR4, tmp); } static void rum_set_basicrates(struct rum_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; /* update basic rate set */ if (ic->ic_curmode == IEEE80211_MODE_11B) { /* 11b basic rates: 1, 2Mbps */ rum_write(sc, RT2573_TXRX_CSR5, 0x3); } else if (IEEE80211_IS_CHAN_5GHZ(ic->ic_bsschan)) { /* 11a basic rates: 6, 12, 24Mbps */ rum_write(sc, RT2573_TXRX_CSR5, 0x150); } else { /* 11b/g basic rates: 1, 2, 5.5, 11Mbps */ rum_write(sc, RT2573_TXRX_CSR5, 0xf); } } /* * Reprogram MAC/BBP to switch to a new band. Values taken from the reference * driver. */ static void rum_select_band(struct rum_softc *sc, struct ieee80211_channel *c) { uint8_t bbp17, bbp35, bbp96, bbp97, bbp98, bbp104; uint32_t tmp; /* update all BBP registers that depend on the band */ bbp17 = 0x20; bbp96 = 0x48; bbp104 = 0x2c; bbp35 = 0x50; bbp97 = 0x48; bbp98 = 0x48; if (IEEE80211_IS_CHAN_5GHZ(c)) { bbp17 += 0x08; bbp96 += 0x10; bbp104 += 0x0c; bbp35 += 0x10; bbp97 += 0x10; bbp98 += 0x10; } if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) || (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) { bbp17 += 0x10; bbp96 += 0x10; bbp104 += 0x10; } sc->bbp17 = bbp17; rum_bbp_write(sc, 17, bbp17); rum_bbp_write(sc, 96, bbp96); rum_bbp_write(sc, 104, bbp104); if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) || (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) { rum_bbp_write(sc, 75, 0x80); rum_bbp_write(sc, 86, 0x80); rum_bbp_write(sc, 88, 0x80); } rum_bbp_write(sc, 35, bbp35); rum_bbp_write(sc, 97, bbp97); rum_bbp_write(sc, 98, bbp98); tmp = rum_read(sc, RT2573_PHY_CSR0); tmp &= ~(RT2573_PA_PE_2GHZ | RT2573_PA_PE_5GHZ); if (IEEE80211_IS_CHAN_2GHZ(c)) tmp |= RT2573_PA_PE_2GHZ; else tmp |= RT2573_PA_PE_5GHZ; rum_write(sc, RT2573_PHY_CSR0, tmp); } static void rum_set_chan(struct rum_softc *sc, struct ieee80211_channel *c) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; const struct rfprog *rfprog; uint8_t bbp3, bbp94 = RT2573_BBPR94_DEFAULT; int8_t power; int i, chan; chan = ieee80211_chan2ieee(ic, c); if (chan == 0 || chan == IEEE80211_CHAN_ANY) return; /* select the appropriate RF settings based on what EEPROM says */ rfprog = (sc->rf_rev == RT2573_RF_5225 || sc->rf_rev == RT2573_RF_2527) ? rum_rf5225 : rum_rf5226; /* find the settings for this channel (we know it exists) */ for (i = 0; rfprog[i].chan != chan; i++); power = sc->txpow[i]; if (power < 0) { bbp94 += power; power = 0; } else if (power > 31) { bbp94 += power - 31; power = 31; } /* * If we are switching from the 2GHz band to the 5GHz band or * vice-versa, BBP registers need to be reprogrammed. */ if (c->ic_flags != ic->ic_curchan->ic_flags) { rum_select_band(sc, c); rum_select_antenna(sc); } ic->ic_curchan = c; rum_rf_write(sc, RT2573_RF1, rfprog[i].r1); rum_rf_write(sc, RT2573_RF2, rfprog[i].r2); rum_rf_write(sc, RT2573_RF3, rfprog[i].r3 | power << 7); rum_rf_write(sc, RT2573_RF4, rfprog[i].r4 | sc->rffreq << 10); rum_rf_write(sc, RT2573_RF1, rfprog[i].r1); rum_rf_write(sc, RT2573_RF2, rfprog[i].r2); rum_rf_write(sc, RT2573_RF3, rfprog[i].r3 | power << 7 | 1); rum_rf_write(sc, RT2573_RF4, rfprog[i].r4 | sc->rffreq << 10); rum_rf_write(sc, RT2573_RF1, rfprog[i].r1); rum_rf_write(sc, RT2573_RF2, rfprog[i].r2); rum_rf_write(sc, RT2573_RF3, rfprog[i].r3 | power << 7); rum_rf_write(sc, RT2573_RF4, rfprog[i].r4 | sc->rffreq << 10); rum_pause(sc, hz / 100); /* enable smart mode for MIMO-capable RFs */ bbp3 = rum_bbp_read(sc, 3); bbp3 &= ~RT2573_SMART_MODE; if (sc->rf_rev == RT2573_RF_5225 || sc->rf_rev == RT2573_RF_2527) bbp3 |= RT2573_SMART_MODE; rum_bbp_write(sc, 3, bbp3); if (bbp94 != RT2573_BBPR94_DEFAULT) rum_bbp_write(sc, 94, bbp94); /* give the chip some extra time to do the switchover */ rum_pause(sc, hz / 100); } /* * Enable TSF synchronization and tell h/w to start sending beacons for IBSS * and HostAP operating modes. */ static void rum_enable_tsf_sync(struct rum_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); uint32_t tmp; if (vap->iv_opmode != IEEE80211_M_STA) { /* * Change default 16ms TBTT adjustment to 8ms. * Must be done before enabling beacon generation. */ rum_write(sc, RT2573_TXRX_CSR10, 1 << 12 | 8); } tmp = rum_read(sc, RT2573_TXRX_CSR9) & 0xff000000; /* set beacon interval (in 1/16ms unit) */ tmp |= vap->iv_bss->ni_intval * 16; tmp |= RT2573_TSF_TICKING | RT2573_ENABLE_TBTT; if (vap->iv_opmode == IEEE80211_M_STA) tmp |= RT2573_TSF_MODE(1); else tmp |= RT2573_TSF_MODE(2) | RT2573_GENERATE_BEACON; rum_write(sc, RT2573_TXRX_CSR9, tmp); } static void rum_enable_tsf(struct rum_softc *sc) { rum_write(sc, RT2573_TXRX_CSR9, (rum_read(sc, RT2573_TXRX_CSR9) & 0xff000000) | RT2573_TSF_TICKING | RT2573_TSF_MODE(2)); } static void rum_update_slot(struct ifnet *ifp) { struct rum_softc *sc = ifp->if_softc; struct ieee80211com *ic = ifp->if_l2com; uint8_t slottime; uint32_t tmp; slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20; tmp = rum_read(sc, RT2573_MAC_CSR9); tmp = (tmp & ~0xff) | slottime; rum_write(sc, RT2573_MAC_CSR9, tmp); DPRINTF("setting slot time to %uus\n", slottime); } static void rum_set_bssid(struct rum_softc *sc, const uint8_t *bssid) { uint32_t tmp; tmp = bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24; rum_write(sc, RT2573_MAC_CSR4, tmp); tmp = bssid[4] | bssid[5] << 8 | RT2573_ONE_BSSID << 16; rum_write(sc, RT2573_MAC_CSR5, tmp); } static void rum_set_macaddr(struct rum_softc *sc, const uint8_t *addr) { uint32_t tmp; tmp = addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24; rum_write(sc, RT2573_MAC_CSR2, tmp); tmp = addr[4] | addr[5] << 8 | 0xff << 16; rum_write(sc, RT2573_MAC_CSR3, tmp); } static void rum_setpromisc(struct rum_softc *sc) { struct ifnet *ifp = sc->sc_ifp; uint32_t tmp; tmp = rum_read(sc, RT2573_TXRX_CSR0); tmp &= ~RT2573_DROP_NOT_TO_ME; if (!(ifp->if_flags & IFF_PROMISC)) tmp |= RT2573_DROP_NOT_TO_ME; rum_write(sc, RT2573_TXRX_CSR0, tmp); DPRINTF("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ? "entering" : "leaving"); } static void rum_update_promisc(struct ifnet *ifp) { struct rum_softc *sc = ifp->if_softc; if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) return; RUM_LOCK(sc); rum_setpromisc(sc); RUM_UNLOCK(sc); } static void rum_update_mcast(struct ifnet *ifp) { static int warning_printed; if (warning_printed == 0) { if_printf(ifp, "need to implement %s\n", __func__); warning_printed = 1; } } static const char * rum_get_rf(int rev) { switch (rev) { case RT2573_RF_2527: return "RT2527 (MIMO XR)"; case RT2573_RF_2528: return "RT2528"; case RT2573_RF_5225: return "RT5225 (MIMO XR)"; case RT2573_RF_5226: return "RT5226"; default: return "unknown"; } } static void rum_read_eeprom(struct rum_softc *sc) { uint16_t val; #ifdef RUM_DEBUG int i; #endif /* read MAC address */ rum_eeprom_read(sc, RT2573_EEPROM_ADDRESS, sc->sc_bssid, 6); rum_eeprom_read(sc, RT2573_EEPROM_ANTENNA, &val, 2); val = le16toh(val); sc->rf_rev = (val >> 11) & 0x1f; sc->hw_radio = (val >> 10) & 0x1; sc->rx_ant = (val >> 4) & 0x3; sc->tx_ant = (val >> 2) & 0x3; sc->nb_ant = val & 0x3; DPRINTF("RF revision=%d\n", sc->rf_rev); rum_eeprom_read(sc, RT2573_EEPROM_CONFIG2, &val, 2); val = le16toh(val); sc->ext_5ghz_lna = (val >> 6) & 0x1; sc->ext_2ghz_lna = (val >> 4) & 0x1; DPRINTF("External 2GHz LNA=%d\nExternal 5GHz LNA=%d\n", sc->ext_2ghz_lna, sc->ext_5ghz_lna); rum_eeprom_read(sc, RT2573_EEPROM_RSSI_2GHZ_OFFSET, &val, 2); val = le16toh(val); if ((val & 0xff) != 0xff) sc->rssi_2ghz_corr = (int8_t)(val & 0xff); /* signed */ /* Only [-10, 10] is valid */ if (sc->rssi_2ghz_corr < -10 || sc->rssi_2ghz_corr > 10) sc->rssi_2ghz_corr = 0; rum_eeprom_read(sc, RT2573_EEPROM_RSSI_5GHZ_OFFSET, &val, 2); val = le16toh(val); if ((val & 0xff) != 0xff) sc->rssi_5ghz_corr = (int8_t)(val & 0xff); /* signed */ /* Only [-10, 10] is valid */ if (sc->rssi_5ghz_corr < -10 || sc->rssi_5ghz_corr > 10) sc->rssi_5ghz_corr = 0; if (sc->ext_2ghz_lna) sc->rssi_2ghz_corr -= 14; if (sc->ext_5ghz_lna) sc->rssi_5ghz_corr -= 14; DPRINTF("RSSI 2GHz corr=%d\nRSSI 5GHz corr=%d\n", sc->rssi_2ghz_corr, sc->rssi_5ghz_corr); rum_eeprom_read(sc, RT2573_EEPROM_FREQ_OFFSET, &val, 2); val = le16toh(val); if ((val & 0xff) != 0xff) sc->rffreq = val & 0xff; DPRINTF("RF freq=%d\n", sc->rffreq); /* read Tx power for all a/b/g channels */ rum_eeprom_read(sc, RT2573_EEPROM_TXPOWER, sc->txpow, 14); /* XXX default Tx power for 802.11a channels */ memset(sc->txpow + 14, 24, sizeof (sc->txpow) - 14); #ifdef RUM_DEBUG for (i = 0; i < 14; i++) DPRINTF("Channel=%d Tx power=%d\n", i + 1, sc->txpow[i]); #endif /* read default values for BBP registers */ rum_eeprom_read(sc, RT2573_EEPROM_BBP_BASE, sc->bbp_prom, 2 * 16); #ifdef RUM_DEBUG for (i = 0; i < 14; i++) { if (sc->bbp_prom[i].reg == 0 || sc->bbp_prom[i].reg == 0xff) continue; DPRINTF("BBP R%d=%02x\n", sc->bbp_prom[i].reg, sc->bbp_prom[i].val); } #endif } static int rum_bbp_init(struct rum_softc *sc) { int i, ntries; /* wait for BBP to be ready */ for (ntries = 0; ntries < 100; ntries++) { const uint8_t val = rum_bbp_read(sc, 0); if (val != 0 && val != 0xff) break; if (rum_pause(sc, hz / 100)) break; } if (ntries == 100) { device_printf(sc->sc_dev, "timeout waiting for BBP\n"); return EIO; } /* initialize BBP registers to default values */ for (i = 0; i < N(rum_def_bbp); i++) rum_bbp_write(sc, rum_def_bbp[i].reg, rum_def_bbp[i].val); /* write vendor-specific BBP values (from EEPROM) */ for (i = 0; i < 16; i++) { if (sc->bbp_prom[i].reg == 0 || sc->bbp_prom[i].reg == 0xff) continue; rum_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val); } return 0; } static void rum_init_locked(struct rum_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; uint32_t tmp; usb_error_t error; int i, ntries; RUM_LOCK_ASSERT(sc, MA_OWNED); rum_stop(sc); /* initialize MAC registers to default values */ for (i = 0; i < N(rum_def_mac); i++) rum_write(sc, rum_def_mac[i].reg, rum_def_mac[i].val); /* set host ready */ rum_write(sc, RT2573_MAC_CSR1, 3); rum_write(sc, RT2573_MAC_CSR1, 0); /* wait for BBP/RF to wakeup */ for (ntries = 0; ntries < 100; ntries++) { if (rum_read(sc, RT2573_MAC_CSR12) & 8) break; rum_write(sc, RT2573_MAC_CSR12, 4); /* force wakeup */ if (rum_pause(sc, hz / 100)) break; } if (ntries == 100) { device_printf(sc->sc_dev, "timeout waiting for BBP/RF to wakeup\n"); goto fail; } if ((error = rum_bbp_init(sc)) != 0) goto fail; /* select default channel */ rum_select_band(sc, ic->ic_curchan); rum_select_antenna(sc); rum_set_chan(sc, ic->ic_curchan); /* clear STA registers */ rum_read_multi(sc, RT2573_STA_CSR0, sc->sta, sizeof sc->sta); rum_set_macaddr(sc, IF_LLADDR(ifp)); /* initialize ASIC */ rum_write(sc, RT2573_MAC_CSR1, 4); /* * Allocate Tx and Rx xfer queues. */ rum_setup_tx_list(sc); /* update Rx filter */ tmp = rum_read(sc, RT2573_TXRX_CSR0) & 0xffff; tmp |= RT2573_DROP_PHY_ERROR | RT2573_DROP_CRC_ERROR; if (ic->ic_opmode != IEEE80211_M_MONITOR) { tmp |= RT2573_DROP_CTL | RT2573_DROP_VER_ERROR | RT2573_DROP_ACKCTS; if (ic->ic_opmode != IEEE80211_M_HOSTAP) tmp |= RT2573_DROP_TODS; if (!(ifp->if_flags & IFF_PROMISC)) tmp |= RT2573_DROP_NOT_TO_ME; } rum_write(sc, RT2573_TXRX_CSR0, tmp); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; ifp->if_drv_flags |= IFF_DRV_RUNNING; usbd_xfer_set_stall(sc->sc_xfer[RUM_BULK_WR]); usbd_transfer_start(sc->sc_xfer[RUM_BULK_RD]); return; fail: rum_stop(sc); #undef N } static void rum_init(void *priv) { struct rum_softc *sc = priv; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; RUM_LOCK(sc); rum_init_locked(sc); RUM_UNLOCK(sc); if (ifp->if_drv_flags & IFF_DRV_RUNNING) ieee80211_start_all(ic); /* start all vap's */ } static void rum_stop(struct rum_softc *sc) { struct ifnet *ifp = sc->sc_ifp; uint32_t tmp; RUM_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); RUM_UNLOCK(sc); /* * Drain the USB transfers, if not already drained: */ usbd_transfer_drain(sc->sc_xfer[RUM_BULK_WR]); usbd_transfer_drain(sc->sc_xfer[RUM_BULK_RD]); RUM_LOCK(sc); rum_unsetup_tx_list(sc); /* disable Rx */ tmp = rum_read(sc, RT2573_TXRX_CSR0); rum_write(sc, RT2573_TXRX_CSR0, tmp | RT2573_DISABLE_RX); /* reset ASIC */ rum_write(sc, RT2573_MAC_CSR1, 3); rum_write(sc, RT2573_MAC_CSR1, 0); } static void rum_load_microcode(struct rum_softc *sc, const uint8_t *ucode, size_t size) { struct usb_device_request req; uint16_t reg = RT2573_MCU_CODE_BASE; usb_error_t err; /* copy firmware image into NIC */ for (; size >= 4; reg += 4, ucode += 4, size -= 4) { err = rum_write(sc, reg, UGETDW(ucode)); if (err) { /* firmware already loaded ? */ device_printf(sc->sc_dev, "Firmware load " "failure! (ignored)\n"); break; } } req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = RT2573_MCU_CNTL; USETW(req.wValue, RT2573_MCU_RUN); USETW(req.wIndex, 0); USETW(req.wLength, 0); err = rum_do_request(sc, &req, NULL); if (err != 0) { device_printf(sc->sc_dev, "could not run firmware: %s\n", usbd_errstr(err)); } /* give the chip some time to boot */ rum_pause(sc, hz / 8); } static void rum_prepare_beacon(struct rum_softc *sc, struct ieee80211vap *vap) { struct ieee80211com *ic = vap->iv_ic; const struct ieee80211_txparam *tp; struct rum_tx_desc desc; struct mbuf *m0; if (vap->iv_bss->ni_chan == IEEE80211_CHAN_ANYC) return; if (ic->ic_bsschan == IEEE80211_CHAN_ANYC) return; m0 = ieee80211_beacon_alloc(vap->iv_bss, &RUM_VAP(vap)->bo); if (m0 == NULL) return; tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_bsschan)]; rum_setup_tx_desc(sc, &desc, RT2573_TX_TIMESTAMP, RT2573_TX_HWSEQ, m0->m_pkthdr.len, tp->mgmtrate); /* copy the first 24 bytes of Tx descriptor into NIC memory */ rum_write_multi(sc, RT2573_HW_BEACON_BASE0, (uint8_t *)&desc, 24); /* copy beacon header and payload into NIC memory */ rum_write_multi(sc, RT2573_HW_BEACON_BASE0 + 24, mtod(m0, uint8_t *), m0->m_pkthdr.len); m_freem(m0); } static int rum_raw_xmit(struct ieee80211_node *ni, struct mbuf *m, const struct ieee80211_bpf_params *params) { struct ifnet *ifp = ni->ni_ic->ic_ifp; struct rum_softc *sc = ifp->if_softc; RUM_LOCK(sc); /* prevent management frames from being sent if we're not ready */ if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) { RUM_UNLOCK(sc); m_freem(m); ieee80211_free_node(ni); return ENETDOWN; } if (sc->tx_nfree < RUM_TX_MINFREE) { ifp->if_drv_flags |= IFF_DRV_OACTIVE; RUM_UNLOCK(sc); m_freem(m); ieee80211_free_node(ni); return EIO; } if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); if (params == NULL) { /* * Legacy path; interpret frame contents to decide * precisely how to send the frame. */ if (rum_tx_mgt(sc, m, ni) != 0) goto bad; } else { /* * Caller supplied explicit parameters to use in * sending the frame. */ if (rum_tx_raw(sc, m, ni, params) != 0) goto bad; } RUM_UNLOCK(sc); return 0; bad: if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); RUM_UNLOCK(sc); ieee80211_free_node(ni); return EIO; } static void rum_ratectl_start(struct rum_softc *sc, struct ieee80211_node *ni) { struct ieee80211vap *vap = ni->ni_vap; struct rum_vap *rvp = RUM_VAP(vap); /* clear statistic registers (STA_CSR0 to STA_CSR5) */ rum_read_multi(sc, RT2573_STA_CSR0, sc->sta, sizeof sc->sta); usb_callout_reset(&rvp->ratectl_ch, hz, rum_ratectl_timeout, rvp); } static void rum_ratectl_timeout(void *arg) { struct rum_vap *rvp = arg; struct ieee80211vap *vap = &rvp->vap; struct ieee80211com *ic = vap->iv_ic; ieee80211_runtask(ic, &rvp->ratectl_task); } static void rum_ratectl_task(void *arg, int pending) { struct rum_vap *rvp = arg; struct ieee80211vap *vap = &rvp->vap; struct ieee80211com *ic = vap->iv_ic; struct ifnet *ifp = ic->ic_ifp; struct rum_softc *sc = ifp->if_softc; struct ieee80211_node *ni; int ok, fail; int sum, retrycnt; RUM_LOCK(sc); /* read and clear statistic registers (STA_CSR0 to STA_CSR10) */ rum_read_multi(sc, RT2573_STA_CSR0, sc->sta, sizeof(sc->sta)); ok = (le32toh(sc->sta[4]) >> 16) + /* TX ok w/o retry */ (le32toh(sc->sta[5]) & 0xffff); /* TX ok w/ retry */ fail = (le32toh(sc->sta[5]) >> 16); /* TX retry-fail count */ sum = ok+fail; retrycnt = (le32toh(sc->sta[5]) & 0xffff) + fail; ni = ieee80211_ref_node(vap->iv_bss); ieee80211_ratectl_tx_update(vap, ni, &sum, &ok, &retrycnt); (void) ieee80211_ratectl_rate(ni, NULL, 0); ieee80211_free_node(ni); if_inc_counter(ifp, IFCOUNTER_OERRORS, fail); /* count TX retry-fail as Tx errors */ usb_callout_reset(&rvp->ratectl_ch, hz, rum_ratectl_timeout, rvp); RUM_UNLOCK(sc); } static void rum_scan_start(struct ieee80211com *ic) { struct ifnet *ifp = ic->ic_ifp; struct rum_softc *sc = ifp->if_softc; uint32_t tmp; RUM_LOCK(sc); /* abort TSF synchronization */ tmp = rum_read(sc, RT2573_TXRX_CSR9); rum_write(sc, RT2573_TXRX_CSR9, tmp & ~0x00ffffff); rum_set_bssid(sc, ifp->if_broadcastaddr); RUM_UNLOCK(sc); } static void rum_scan_end(struct ieee80211com *ic) { struct rum_softc *sc = ic->ic_ifp->if_softc; RUM_LOCK(sc); rum_enable_tsf_sync(sc); rum_set_bssid(sc, sc->sc_bssid); RUM_UNLOCK(sc); } static void rum_set_channel(struct ieee80211com *ic) { struct rum_softc *sc = ic->ic_ifp->if_softc; RUM_LOCK(sc); rum_set_chan(sc, ic->ic_curchan); RUM_UNLOCK(sc); } static int rum_get_rssi(struct rum_softc *sc, uint8_t raw) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; int lna, agc, rssi; lna = (raw >> 5) & 0x3; agc = raw & 0x1f; if (lna == 0) { /* * No RSSI mapping * * NB: Since RSSI is relative to noise floor, -1 is * adequate for caller to know error happened. */ return -1; } rssi = (2 * agc) - RT2573_NOISE_FLOOR; if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan)) { rssi += sc->rssi_2ghz_corr; if (lna == 1) rssi -= 64; else if (lna == 2) rssi -= 74; else if (lna == 3) rssi -= 90; } else { rssi += sc->rssi_5ghz_corr; if (!sc->ext_5ghz_lna && lna != 1) rssi += 4; if (lna == 1) rssi -= 64; else if (lna == 2) rssi -= 86; else if (lna == 3) rssi -= 100; } return rssi; } static int rum_pause(struct rum_softc *sc, int timeout) { usb_pause_mtx(&sc->sc_mtx, timeout); return (0); } static device_method_t rum_methods[] = { /* Device interface */ DEVMETHOD(device_probe, rum_match), DEVMETHOD(device_attach, rum_attach), DEVMETHOD(device_detach, rum_detach), DEVMETHOD_END }; static driver_t rum_driver = { .name = "rum", .methods = rum_methods, .size = sizeof(struct rum_softc), }; static devclass_t rum_devclass; DRIVER_MODULE(rum, uhub, rum_driver, rum_devclass, NULL, 0); MODULE_DEPEND(rum, wlan, 1, 1, 1); MODULE_DEPEND(rum, usb, 1, 1, 1); MODULE_VERSION(rum, 1); Index: head/sys/dev/usb/wlan/if_run.c =================================================================== --- head/sys/dev/usb/wlan/if_run.c (revision 276700) +++ head/sys/dev/usb/wlan/if_run.c (revision 276701) @@ -1,6305 +1,6305 @@ /*- * Copyright (c) 2008,2010 Damien Bergamini * ported to FreeBSD by Akinori Furukoshi * USB Consulting, Hans Petter Selasky * Copyright (c) 2013-2014 Kevin Lo * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include __FBSDID("$FreeBSD$"); /*- * Ralink Technology RT2700U/RT2800U/RT3000U/RT3900E chipset driver. * http://www.ralinktech.com/ */ #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 #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR run_debug #include #include #include #include #ifdef USB_DEBUG #define RUN_DEBUG #endif #ifdef RUN_DEBUG int run_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, run, CTLFLAG_RW, 0, "USB run"); -SYSCTL_INT(_hw_usb_run, OID_AUTO, debug, CTLFLAG_RW, &run_debug, 0, +SYSCTL_INT(_hw_usb_run, OID_AUTO, debug, CTLFLAG_RWTUN, &run_debug, 0, "run debug level"); #endif #define IEEE80211_HAS_ADDR4(wh) \ (((wh)->i_fc[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_DSTODS) /* * Because of LOR in run_key_delete(), use atomic instead. * '& RUN_CMDQ_MASQ' is to loop cmdq[]. */ #define RUN_CMDQ_GET(c) (atomic_fetchadd_32((c), 1) & RUN_CMDQ_MASQ) static const STRUCT_USB_HOST_ID run_devs[] = { #define RUN_DEV(v,p) { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) } #define RUN_DEV_EJECT(v,p) \ { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, RUN_EJECT) } #define RUN_EJECT 1 RUN_DEV(ABOCOM, RT2770), RUN_DEV(ABOCOM, RT2870), RUN_DEV(ABOCOM, RT3070), RUN_DEV(ABOCOM, RT3071), RUN_DEV(ABOCOM, RT3072), RUN_DEV(ABOCOM2, RT2870_1), RUN_DEV(ACCTON, RT2770), RUN_DEV(ACCTON, RT2870_1), RUN_DEV(ACCTON, RT2870_2), RUN_DEV(ACCTON, RT2870_3), RUN_DEV(ACCTON, RT2870_4), RUN_DEV(ACCTON, RT2870_5), RUN_DEV(ACCTON, RT3070), RUN_DEV(ACCTON, RT3070_1), RUN_DEV(ACCTON, RT3070_2), RUN_DEV(ACCTON, RT3070_3), RUN_DEV(ACCTON, RT3070_4), RUN_DEV(ACCTON, RT3070_5), RUN_DEV(AIRTIES, RT3070), RUN_DEV(ALLWIN, RT2070), RUN_DEV(ALLWIN, RT2770), RUN_DEV(ALLWIN, RT2870), RUN_DEV(ALLWIN, RT3070), RUN_DEV(ALLWIN, RT3071), RUN_DEV(ALLWIN, RT3072), RUN_DEV(ALLWIN, RT3572), RUN_DEV(AMIGO, RT2870_1), RUN_DEV(AMIGO, RT2870_2), RUN_DEV(AMIT, CGWLUSB2GNR), RUN_DEV(AMIT, RT2870_1), RUN_DEV(AMIT2, RT2870), RUN_DEV(ASUS, RT2870_1), RUN_DEV(ASUS, RT2870_2), RUN_DEV(ASUS, RT2870_3), RUN_DEV(ASUS, RT2870_4), RUN_DEV(ASUS, RT2870_5), RUN_DEV(ASUS, USBN13), RUN_DEV(ASUS, RT3070_1), RUN_DEV(ASUS, USBN66), RUN_DEV(ASUS, USB_N53), RUN_DEV(ASUS2, USBN11), RUN_DEV(AZUREWAVE, RT2870_1), RUN_DEV(AZUREWAVE, RT2870_2), RUN_DEV(AZUREWAVE, RT3070_1), RUN_DEV(AZUREWAVE, RT3070_2), RUN_DEV(AZUREWAVE, RT3070_3), RUN_DEV(BELKIN, F9L1103), RUN_DEV(BELKIN, F5D8053V3), RUN_DEV(BELKIN, F5D8055), RUN_DEV(BELKIN, F5D8055V2), RUN_DEV(BELKIN, F6D4050V1), RUN_DEV(BELKIN, F6D4050V2), RUN_DEV(BELKIN, RT2870_1), RUN_DEV(BELKIN, RT2870_2), RUN_DEV(CISCOLINKSYS, AE1000), RUN_DEV(CISCOLINKSYS2, RT3070), RUN_DEV(CISCOLINKSYS3, RT3070), RUN_DEV(CONCEPTRONIC2, RT2870_1), RUN_DEV(CONCEPTRONIC2, RT2870_2), RUN_DEV(CONCEPTRONIC2, RT2870_3), RUN_DEV(CONCEPTRONIC2, RT2870_4), RUN_DEV(CONCEPTRONIC2, RT2870_5), RUN_DEV(CONCEPTRONIC2, RT2870_6), RUN_DEV(CONCEPTRONIC2, RT2870_7), RUN_DEV(CONCEPTRONIC2, RT2870_8), RUN_DEV(CONCEPTRONIC2, RT3070_1), RUN_DEV(CONCEPTRONIC2, RT3070_2), RUN_DEV(CONCEPTRONIC2, VIGORN61), RUN_DEV(COREGA, CGWLUSB300GNM), RUN_DEV(COREGA, RT2870_1), RUN_DEV(COREGA, RT2870_2), RUN_DEV(COREGA, RT2870_3), RUN_DEV(COREGA, RT3070), RUN_DEV(CYBERTAN, RT2870), RUN_DEV(DLINK, RT2870), RUN_DEV(DLINK, RT3072), RUN_DEV(DLINK, DWA127), RUN_DEV(DLINK, DWA140B3), RUN_DEV(DLINK, DWA160B2), RUN_DEV(DLINK, DWA140D1), RUN_DEV(DLINK, DWA162), RUN_DEV(DLINK2, DWA130), RUN_DEV(DLINK2, RT2870_1), RUN_DEV(DLINK2, RT2870_2), RUN_DEV(DLINK2, RT3070_1), RUN_DEV(DLINK2, RT3070_2), RUN_DEV(DLINK2, RT3070_3), RUN_DEV(DLINK2, RT3070_4), RUN_DEV(DLINK2, RT3070_5), RUN_DEV(DLINK2, RT3072), RUN_DEV(DLINK2, RT3072_1), RUN_DEV(EDIMAX, EW7717), RUN_DEV(EDIMAX, EW7718), RUN_DEV(EDIMAX, EW7733UND), RUN_DEV(EDIMAX, RT2870_1), RUN_DEV(ENCORE, RT3070_1), RUN_DEV(ENCORE, RT3070_2), RUN_DEV(ENCORE, RT3070_3), RUN_DEV(GIGABYTE, GNWB31N), RUN_DEV(GIGABYTE, GNWB32L), RUN_DEV(GIGABYTE, RT2870_1), RUN_DEV(GIGASET, RT3070_1), RUN_DEV(GIGASET, RT3070_2), RUN_DEV(GUILLEMOT, HWNU300), RUN_DEV(HAWKING, HWUN2), RUN_DEV(HAWKING, RT2870_1), RUN_DEV(HAWKING, RT2870_2), RUN_DEV(HAWKING, RT3070), RUN_DEV(IODATA, RT3072_1), RUN_DEV(IODATA, RT3072_2), RUN_DEV(IODATA, RT3072_3), RUN_DEV(IODATA, RT3072_4), RUN_DEV(LINKSYS4, RT3070), RUN_DEV(LINKSYS4, WUSB100), RUN_DEV(LINKSYS4, WUSB54GCV3), RUN_DEV(LINKSYS4, WUSB600N), RUN_DEV(LINKSYS4, WUSB600NV2), RUN_DEV(LOGITEC, RT2870_1), RUN_DEV(LOGITEC, RT2870_2), RUN_DEV(LOGITEC, RT2870_3), RUN_DEV(LOGITEC, LANW300NU2), RUN_DEV(LOGITEC, LANW150NU2), RUN_DEV(LOGITEC, LANW300NU2S), RUN_DEV(MELCO, RT2870_1), RUN_DEV(MELCO, RT2870_2), RUN_DEV(MELCO, WLIUCAG300N), RUN_DEV(MELCO, WLIUCG300N), RUN_DEV(MELCO, WLIUCG301N), RUN_DEV(MELCO, WLIUCGN), RUN_DEV(MELCO, WLIUCGNM), RUN_DEV(MELCO, WLIUCGNM2), RUN_DEV(MOTOROLA4, RT2770), RUN_DEV(MOTOROLA4, RT3070), RUN_DEV(MSI, RT3070_1), RUN_DEV(MSI, RT3070_2), RUN_DEV(MSI, RT3070_3), RUN_DEV(MSI, RT3070_4), RUN_DEV(MSI, RT3070_5), RUN_DEV(MSI, RT3070_6), RUN_DEV(MSI, RT3070_7), RUN_DEV(MSI, RT3070_8), RUN_DEV(MSI, RT3070_9), RUN_DEV(MSI, RT3070_10), RUN_DEV(MSI, RT3070_11), RUN_DEV(OVISLINK, RT3072), RUN_DEV(PARA, RT3070), RUN_DEV(PEGATRON, RT2870), RUN_DEV(PEGATRON, RT3070), RUN_DEV(PEGATRON, RT3070_2), RUN_DEV(PEGATRON, RT3070_3), RUN_DEV(PHILIPS, RT2870), RUN_DEV(PLANEX2, GWUS300MINIS), RUN_DEV(PLANEX2, GWUSMICRON), RUN_DEV(PLANEX2, RT2870), RUN_DEV(PLANEX2, RT3070), RUN_DEV(QCOM, RT2870), RUN_DEV(QUANTA, RT3070), RUN_DEV(RALINK, RT2070), RUN_DEV(RALINK, RT2770), RUN_DEV(RALINK, RT2870), RUN_DEV(RALINK, RT3070), RUN_DEV(RALINK, RT3071), RUN_DEV(RALINK, RT3072), RUN_DEV(RALINK, RT3370), RUN_DEV(RALINK, RT3572), RUN_DEV(RALINK, RT3573), RUN_DEV(RALINK, RT5370), RUN_DEV(RALINK, RT5572), RUN_DEV(RALINK, RT8070), RUN_DEV(SAMSUNG, WIS09ABGN), RUN_DEV(SAMSUNG2, RT2870_1), RUN_DEV(SENAO, RT2870_1), RUN_DEV(SENAO, RT2870_2), RUN_DEV(SENAO, RT2870_3), RUN_DEV(SENAO, RT2870_4), RUN_DEV(SENAO, RT3070), RUN_DEV(SENAO, RT3071), RUN_DEV(SENAO, RT3072_1), RUN_DEV(SENAO, RT3072_2), RUN_DEV(SENAO, RT3072_3), RUN_DEV(SENAO, RT3072_4), RUN_DEV(SENAO, RT3072_5), RUN_DEV(SITECOMEU, RT2770), RUN_DEV(SITECOMEU, RT2870_1), RUN_DEV(SITECOMEU, RT2870_2), RUN_DEV(SITECOMEU, RT2870_3), RUN_DEV(SITECOMEU, RT2870_4), RUN_DEV(SITECOMEU, RT3070), RUN_DEV(SITECOMEU, RT3070_2), RUN_DEV(SITECOMEU, RT3070_3), RUN_DEV(SITECOMEU, RT3070_4), RUN_DEV(SITECOMEU, RT3071), RUN_DEV(SITECOMEU, RT3072_1), RUN_DEV(SITECOMEU, RT3072_2), RUN_DEV(SITECOMEU, RT3072_3), RUN_DEV(SITECOMEU, RT3072_4), RUN_DEV(SITECOMEU, RT3072_5), RUN_DEV(SITECOMEU, RT3072_6), RUN_DEV(SITECOMEU, WL608), RUN_DEV(SPARKLAN, RT2870_1), RUN_DEV(SPARKLAN, RT3070), RUN_DEV(SWEEX2, LW153), RUN_DEV(SWEEX2, LW303), RUN_DEV(SWEEX2, LW313), RUN_DEV(TOSHIBA, RT3070), RUN_DEV(UMEDIA, RT2870_1), RUN_DEV(ZCOM, RT2870_1), RUN_DEV(ZCOM, RT2870_2), RUN_DEV(ZINWELL, RT2870_1), RUN_DEV(ZINWELL, RT2870_2), RUN_DEV(ZINWELL, RT3070), RUN_DEV(ZINWELL, RT3072_1), RUN_DEV(ZINWELL, RT3072_2), RUN_DEV(ZYXEL, RT2870_1), RUN_DEV(ZYXEL, RT2870_2), RUN_DEV(ZYXEL, RT3070), RUN_DEV_EJECT(ZYXEL, NWD2705), RUN_DEV_EJECT(RALINK, RT_STOR), #undef RUN_DEV_EJECT #undef RUN_DEV }; static device_probe_t run_match; static device_attach_t run_attach; static device_detach_t run_detach; static usb_callback_t run_bulk_rx_callback; static usb_callback_t run_bulk_tx_callback0; static usb_callback_t run_bulk_tx_callback1; static usb_callback_t run_bulk_tx_callback2; static usb_callback_t run_bulk_tx_callback3; static usb_callback_t run_bulk_tx_callback4; static usb_callback_t run_bulk_tx_callback5; static void run_autoinst(void *, struct usb_device *, struct usb_attach_arg *); static int run_driver_loaded(struct module *, int, void *); static void run_bulk_tx_callbackN(struct usb_xfer *xfer, usb_error_t error, u_int index); static struct ieee80211vap *run_vap_create(struct ieee80211com *, const char [IFNAMSIZ], int, enum ieee80211_opmode, int, const uint8_t [IEEE80211_ADDR_LEN], const uint8_t [IEEE80211_ADDR_LEN]); static void run_vap_delete(struct ieee80211vap *); static void run_cmdq_cb(void *, int); static void run_setup_tx_list(struct run_softc *, struct run_endpoint_queue *); static void run_unsetup_tx_list(struct run_softc *, struct run_endpoint_queue *); static int run_load_microcode(struct run_softc *); static int run_reset(struct run_softc *); static usb_error_t run_do_request(struct run_softc *, struct usb_device_request *, void *); static int run_read(struct run_softc *, uint16_t, uint32_t *); static int run_read_region_1(struct run_softc *, uint16_t, uint8_t *, int); static int run_write_2(struct run_softc *, uint16_t, uint16_t); static int run_write(struct run_softc *, uint16_t, uint32_t); static int run_write_region_1(struct run_softc *, uint16_t, const uint8_t *, int); static int run_set_region_4(struct run_softc *, uint16_t, uint32_t, int); static int run_efuse_read(struct run_softc *, uint16_t, uint16_t *, int); static int run_efuse_read_2(struct run_softc *, uint16_t, uint16_t *); static int run_eeprom_read_2(struct run_softc *, uint16_t, uint16_t *); static int run_rt2870_rf_write(struct run_softc *, uint32_t); static int run_rt3070_rf_read(struct run_softc *, uint8_t, uint8_t *); static int run_rt3070_rf_write(struct run_softc *, uint8_t, uint8_t); static int run_bbp_read(struct run_softc *, uint8_t, uint8_t *); static int run_bbp_write(struct run_softc *, uint8_t, uint8_t); static int run_mcu_cmd(struct run_softc *, uint8_t, uint16_t); static const char *run_get_rf(uint16_t); static void run_rt3593_get_txpower(struct run_softc *); static void run_get_txpower(struct run_softc *); static int run_read_eeprom(struct run_softc *); static struct ieee80211_node *run_node_alloc(struct ieee80211vap *, const uint8_t mac[IEEE80211_ADDR_LEN]); static int run_media_change(struct ifnet *); static int run_newstate(struct ieee80211vap *, enum ieee80211_state, int); static int run_wme_update(struct ieee80211com *); static void run_wme_update_cb(void *); static void run_key_update_begin(struct ieee80211vap *); static void run_key_update_end(struct ieee80211vap *); static void run_key_set_cb(void *); static int run_key_set(struct ieee80211vap *, struct ieee80211_key *, const uint8_t mac[IEEE80211_ADDR_LEN]); static void run_key_delete_cb(void *); static int run_key_delete(struct ieee80211vap *, struct ieee80211_key *); static void run_ratectl_to(void *); static void run_ratectl_cb(void *, int); static void run_drain_fifo(void *); static void run_iter_func(void *, struct ieee80211_node *); static void run_newassoc_cb(void *); static void run_newassoc(struct ieee80211_node *, int); static void run_rx_frame(struct run_softc *, struct mbuf *, uint32_t); static void run_tx_free(struct run_endpoint_queue *pq, struct run_tx_data *, int); static void run_set_tx_desc(struct run_softc *, struct run_tx_data *); static int run_tx(struct run_softc *, struct mbuf *, struct ieee80211_node *); static int run_tx_mgt(struct run_softc *, struct mbuf *, struct ieee80211_node *); static int run_sendprot(struct run_softc *, const struct mbuf *, struct ieee80211_node *, int, int); static int run_tx_param(struct run_softc *, struct mbuf *, struct ieee80211_node *, const struct ieee80211_bpf_params *); static int run_raw_xmit(struct ieee80211_node *, struct mbuf *, const struct ieee80211_bpf_params *); static void run_start(struct ifnet *); static int run_ioctl(struct ifnet *, u_long, caddr_t); static void run_iq_calib(struct run_softc *, u_int); static void run_set_agc(struct run_softc *, uint8_t); static void run_select_chan_group(struct run_softc *, int); static void run_set_rx_antenna(struct run_softc *, int); static void run_rt2870_set_chan(struct run_softc *, u_int); static void run_rt3070_set_chan(struct run_softc *, u_int); static void run_rt3572_set_chan(struct run_softc *, u_int); static void run_rt3593_set_chan(struct run_softc *, u_int); static void run_rt5390_set_chan(struct run_softc *, u_int); static void run_rt5592_set_chan(struct run_softc *, u_int); static int run_set_chan(struct run_softc *, struct ieee80211_channel *); static void run_set_channel(struct ieee80211com *); static void run_scan_start(struct ieee80211com *); static void run_scan_end(struct ieee80211com *); static void run_update_beacon(struct ieee80211vap *, int); static void run_update_beacon_cb(void *); static void run_updateprot(struct ieee80211com *); static void run_updateprot_cb(void *); static void run_usb_timeout_cb(void *); static void run_reset_livelock(struct run_softc *); static void run_enable_tsf_sync(struct run_softc *); static void run_enable_mrr(struct run_softc *); static void run_set_txpreamble(struct run_softc *); static void run_set_basicrates(struct run_softc *); static void run_set_leds(struct run_softc *, uint16_t); static void run_set_bssid(struct run_softc *, const uint8_t *); static void run_set_macaddr(struct run_softc *, const uint8_t *); static void run_updateslot(struct ifnet *); static void run_updateslot_cb(void *); static void run_update_mcast(struct ifnet *); static int8_t run_rssi2dbm(struct run_softc *, uint8_t, uint8_t); static void run_update_promisc_locked(struct ifnet *); static void run_update_promisc(struct ifnet *); static void run_rt5390_bbp_init(struct run_softc *); static int run_bbp_init(struct run_softc *); static int run_rt3070_rf_init(struct run_softc *); static void run_rt3593_rf_init(struct run_softc *); static void run_rt5390_rf_init(struct run_softc *); static int run_rt3070_filter_calib(struct run_softc *, uint8_t, uint8_t, uint8_t *); static void run_rt3070_rf_setup(struct run_softc *); static void run_rt3593_rf_setup(struct run_softc *); static void run_rt5390_rf_setup(struct run_softc *); static int run_txrx_enable(struct run_softc *); static void run_adjust_freq_offset(struct run_softc *); static void run_init(void *); static void run_init_locked(struct run_softc *); static void run_stop(void *); static void run_delay(struct run_softc *, u_int); static eventhandler_tag run_etag; static const struct rt2860_rate { uint8_t rate; uint8_t mcs; enum ieee80211_phytype phy; uint8_t ctl_ridx; uint16_t sp_ack_dur; uint16_t lp_ack_dur; } rt2860_rates[] = { { 2, 0, IEEE80211_T_DS, 0, 314, 314 }, { 4, 1, IEEE80211_T_DS, 1, 258, 162 }, { 11, 2, IEEE80211_T_DS, 2, 223, 127 }, { 22, 3, IEEE80211_T_DS, 3, 213, 117 }, { 12, 0, IEEE80211_T_OFDM, 4, 60, 60 }, { 18, 1, IEEE80211_T_OFDM, 4, 52, 52 }, { 24, 2, IEEE80211_T_OFDM, 6, 48, 48 }, { 36, 3, IEEE80211_T_OFDM, 6, 44, 44 }, { 48, 4, IEEE80211_T_OFDM, 8, 44, 44 }, { 72, 5, IEEE80211_T_OFDM, 8, 40, 40 }, { 96, 6, IEEE80211_T_OFDM, 8, 40, 40 }, { 108, 7, IEEE80211_T_OFDM, 8, 40, 40 } }; static const struct { uint16_t reg; uint32_t val; } rt2870_def_mac[] = { RT2870_DEF_MAC }; static const struct { uint8_t reg; uint8_t val; } rt2860_def_bbp[] = { RT2860_DEF_BBP },rt5390_def_bbp[] = { RT5390_DEF_BBP },rt5592_def_bbp[] = { RT5592_DEF_BBP }; /* * Default values for BBP register R196 for RT5592. */ static const uint8_t rt5592_bbp_r196[] = { 0xe0, 0x1f, 0x38, 0x32, 0x08, 0x28, 0x19, 0x0a, 0xff, 0x00, 0x16, 0x10, 0x10, 0x0b, 0x36, 0x2c, 0x26, 0x24, 0x42, 0x36, 0x30, 0x2d, 0x4c, 0x46, 0x3d, 0x40, 0x3e, 0x42, 0x3d, 0x40, 0x3c, 0x34, 0x2c, 0x2f, 0x3c, 0x35, 0x2e, 0x2a, 0x49, 0x41, 0x36, 0x31, 0x30, 0x30, 0x0e, 0x0d, 0x28, 0x21, 0x1c, 0x16, 0x50, 0x4a, 0x43, 0x40, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7d, 0x14, 0x32, 0x2c, 0x36, 0x4c, 0x43, 0x2c, 0x2e, 0x36, 0x30, 0x6e }; static const struct rfprog { uint8_t chan; uint32_t r1, r2, r3, r4; } rt2860_rf2850[] = { RT2860_RF2850 }; struct { uint8_t n, r, k; } rt3070_freqs[] = { RT3070_RF3052 }; static const struct rt5592_freqs { uint16_t n; uint8_t k, m, r; } rt5592_freqs_20mhz[] = { RT5592_RF5592_20MHZ },rt5592_freqs_40mhz[] = { RT5592_RF5592_40MHZ }; static const struct { uint8_t reg; uint8_t val; } rt3070_def_rf[] = { RT3070_DEF_RF },rt3572_def_rf[] = { RT3572_DEF_RF },rt3593_def_rf[] = { RT3593_DEF_RF },rt5390_def_rf[] = { RT5390_DEF_RF },rt5392_def_rf[] = { RT5392_DEF_RF },rt5592_def_rf[] = { RT5592_DEF_RF },rt5592_2ghz_def_rf[] = { RT5592_2GHZ_DEF_RF },rt5592_5ghz_def_rf[] = { RT5592_5GHZ_DEF_RF }; static const struct { u_int firstchan; u_int lastchan; uint8_t reg; uint8_t val; } rt5592_chan_5ghz[] = { RT5592_CHAN_5GHZ }; static const struct usb_config run_config[RUN_N_XFER] = { [RUN_BULK_TX_BE] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .ep_index = 0, .direction = UE_DIR_OUT, .bufsize = RUN_MAX_TXSZ, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = run_bulk_tx_callback0, .timeout = 5000, /* ms */ }, [RUN_BULK_TX_BK] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .ep_index = 1, .bufsize = RUN_MAX_TXSZ, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = run_bulk_tx_callback1, .timeout = 5000, /* ms */ }, [RUN_BULK_TX_VI] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .ep_index = 2, .bufsize = RUN_MAX_TXSZ, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = run_bulk_tx_callback2, .timeout = 5000, /* ms */ }, [RUN_BULK_TX_VO] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .ep_index = 3, .bufsize = RUN_MAX_TXSZ, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = run_bulk_tx_callback3, .timeout = 5000, /* ms */ }, [RUN_BULK_TX_HCCA] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .ep_index = 4, .bufsize = RUN_MAX_TXSZ, .flags = {.pipe_bof = 1,.force_short_xfer = 1,.no_pipe_ok = 1,}, .callback = run_bulk_tx_callback4, .timeout = 5000, /* ms */ }, [RUN_BULK_TX_PRIO] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .ep_index = 5, .bufsize = RUN_MAX_TXSZ, .flags = {.pipe_bof = 1,.force_short_xfer = 1,.no_pipe_ok = 1,}, .callback = run_bulk_tx_callback5, .timeout = 5000, /* ms */ }, [RUN_BULK_RX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = RUN_MAX_RXSZ, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = run_bulk_rx_callback, } }; static void run_autoinst(void *arg, struct usb_device *udev, struct usb_attach_arg *uaa) { struct usb_interface *iface; struct usb_interface_descriptor *id; if (uaa->dev_state != UAA_DEV_READY) return; iface = usbd_get_iface(udev, 0); if (iface == NULL) return; id = iface->idesc; if (id == NULL || id->bInterfaceClass != UICLASS_MASS) return; if (usbd_lookup_id_by_uaa(run_devs, sizeof(run_devs), uaa)) return; if (usb_msc_eject(udev, 0, MSC_EJECT_STOPUNIT) == 0) uaa->dev_state = UAA_DEV_EJECTING; } static int run_driver_loaded(struct module *mod, int what, void *arg) { switch (what) { case MOD_LOAD: run_etag = EVENTHANDLER_REGISTER(usb_dev_configured, run_autoinst, NULL, EVENTHANDLER_PRI_ANY); break; case MOD_UNLOAD: EVENTHANDLER_DEREGISTER(usb_dev_configured, run_etag); break; default: return (EOPNOTSUPP); } return (0); } static int run_match(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != 0) return (ENXIO); if (uaa->info.bIfaceIndex != RT2860_IFACE_INDEX) return (ENXIO); return (usbd_lookup_id_by_uaa(run_devs, sizeof(run_devs), uaa)); } static int run_attach(device_t self) { struct run_softc *sc = device_get_softc(self); struct usb_attach_arg *uaa = device_get_ivars(self); struct ieee80211com *ic; struct ifnet *ifp; uint32_t ver; int ntries, error; uint8_t iface_index, bands; device_set_usb_desc(self); sc->sc_udev = uaa->device; sc->sc_dev = self; if (USB_GET_DRIVER_INFO(uaa) != RUN_EJECT) sc->sc_flags |= RUN_FLAG_FWLOAD_NEEDED; mtx_init(&sc->sc_mtx, device_get_nameunit(sc->sc_dev), MTX_NETWORK_LOCK, MTX_DEF); iface_index = RT2860_IFACE_INDEX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, run_config, RUN_N_XFER, sc, &sc->sc_mtx); if (error) { device_printf(self, "could not allocate USB transfers, " "err=%s\n", usbd_errstr(error)); goto detach; } RUN_LOCK(sc); /* wait for the chip to settle */ for (ntries = 0; ntries < 100; ntries++) { if (run_read(sc, RT2860_ASIC_VER_ID, &ver) != 0) { RUN_UNLOCK(sc); goto detach; } if (ver != 0 && ver != 0xffffffff) break; run_delay(sc, 10); } if (ntries == 100) { device_printf(sc->sc_dev, "timeout waiting for NIC to initialize\n"); RUN_UNLOCK(sc); goto detach; } sc->mac_ver = ver >> 16; sc->mac_rev = ver & 0xffff; /* retrieve RF rev. no and various other things from EEPROM */ run_read_eeprom(sc); device_printf(sc->sc_dev, "MAC/BBP RT%04X (rev 0x%04X), RF %s (MIMO %dT%dR), address %s\n", sc->mac_ver, sc->mac_rev, run_get_rf(sc->rf_rev), sc->ntxchains, sc->nrxchains, ether_sprintf(sc->sc_bssid)); RUN_UNLOCK(sc); ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211); if (ifp == NULL) { device_printf(sc->sc_dev, "can not if_alloc()\n"); goto detach; } ic = ifp->if_l2com; ifp->if_softc = sc; if_initname(ifp, "run", device_get_unit(sc->sc_dev)); ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; ifp->if_init = run_init; ifp->if_ioctl = run_ioctl; ifp->if_start = run_start; IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen); ifp->if_snd.ifq_drv_maxlen = ifqmaxlen; IFQ_SET_READY(&ifp->if_snd); ic->ic_ifp = ifp; ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */ ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */ /* set device capabilities */ ic->ic_caps = IEEE80211_C_STA | /* station mode supported */ IEEE80211_C_MONITOR | /* monitor mode supported */ IEEE80211_C_IBSS | IEEE80211_C_HOSTAP | IEEE80211_C_WDS | /* 4-address traffic works */ IEEE80211_C_MBSS | IEEE80211_C_SHPREAMBLE | /* short preamble supported */ IEEE80211_C_SHSLOT | /* short slot time supported */ IEEE80211_C_WME | /* WME */ IEEE80211_C_WPA; /* WPA1|WPA2(RSN) */ ic->ic_cryptocaps = IEEE80211_CRYPTO_WEP | IEEE80211_CRYPTO_AES_CCM | IEEE80211_CRYPTO_TKIPMIC | IEEE80211_CRYPTO_TKIP; ic->ic_flags |= IEEE80211_F_DATAPAD; ic->ic_flags_ext |= IEEE80211_FEXT_SWBMISS; bands = 0; setbit(&bands, IEEE80211_MODE_11B); setbit(&bands, IEEE80211_MODE_11G); if (sc->rf_rev == RT2860_RF_2750 || sc->rf_rev == RT2860_RF_2850 || sc->rf_rev == RT3070_RF_3052 || sc->rf_rev == RT3593_RF_3053 || sc->rf_rev == RT5592_RF_5592) setbit(&bands, IEEE80211_MODE_11A); ieee80211_init_channels(ic, NULL, &bands); ieee80211_ifattach(ic, sc->sc_bssid); ic->ic_scan_start = run_scan_start; ic->ic_scan_end = run_scan_end; ic->ic_set_channel = run_set_channel; ic->ic_node_alloc = run_node_alloc; ic->ic_newassoc = run_newassoc; ic->ic_updateslot = run_updateslot; ic->ic_update_mcast = run_update_mcast; ic->ic_wme.wme_update = run_wme_update; ic->ic_raw_xmit = run_raw_xmit; ic->ic_update_promisc = run_update_promisc; ic->ic_vap_create = run_vap_create; ic->ic_vap_delete = run_vap_delete; ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap), RUN_TX_RADIOTAP_PRESENT, &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap), RUN_RX_RADIOTAP_PRESENT); TASK_INIT(&sc->cmdq_task, 0, run_cmdq_cb, sc); TASK_INIT(&sc->ratectl_task, 0, run_ratectl_cb, sc); usb_callout_init_mtx(&sc->ratectl_ch, &sc->sc_mtx, 0); if (bootverbose) ieee80211_announce(ic); return (0); detach: run_detach(self); return (ENXIO); } static int run_detach(device_t self) { struct run_softc *sc = device_get_softc(self); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic; int i; RUN_LOCK(sc); sc->sc_detached = 1; RUN_UNLOCK(sc); /* stop all USB transfers */ usbd_transfer_unsetup(sc->sc_xfer, RUN_N_XFER); RUN_LOCK(sc); sc->ratectl_run = RUN_RATECTL_OFF; sc->cmdq_run = sc->cmdq_key_set = RUN_CMDQ_ABORT; /* free TX list, if any */ for (i = 0; i != RUN_EP_QUEUES; i++) run_unsetup_tx_list(sc, &sc->sc_epq[i]); RUN_UNLOCK(sc); if (ifp) { ic = ifp->if_l2com; /* drain tasks */ usb_callout_drain(&sc->ratectl_ch); ieee80211_draintask(ic, &sc->cmdq_task); ieee80211_draintask(ic, &sc->ratectl_task); ieee80211_ifdetach(ic); if_free(ifp); } mtx_destroy(&sc->sc_mtx); return (0); } static struct ieee80211vap * run_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit, enum ieee80211_opmode opmode, int flags, const uint8_t bssid[IEEE80211_ADDR_LEN], const uint8_t mac[IEEE80211_ADDR_LEN]) { struct ifnet *ifp = ic->ic_ifp; struct run_softc *sc = ifp->if_softc; struct run_vap *rvp; struct ieee80211vap *vap; int i; if (sc->rvp_cnt >= RUN_VAP_MAX) { if_printf(ifp, "number of VAPs maxed out\n"); return (NULL); } switch (opmode) { case IEEE80211_M_STA: /* enable s/w bmiss handling for sta mode */ flags |= IEEE80211_CLONE_NOBEACONS; /* fall though */ case IEEE80211_M_IBSS: case IEEE80211_M_MONITOR: case IEEE80211_M_HOSTAP: case IEEE80211_M_MBSS: /* other than WDS vaps, only one at a time */ if (!TAILQ_EMPTY(&ic->ic_vaps)) return (NULL); break; case IEEE80211_M_WDS: TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next){ if(vap->iv_opmode != IEEE80211_M_HOSTAP) continue; /* WDS vap's always share the local mac address. */ flags &= ~IEEE80211_CLONE_BSSID; break; } if (vap == NULL) { if_printf(ifp, "wds only supported in ap mode\n"); return (NULL); } break; default: if_printf(ifp, "unknown opmode %d\n", opmode); return (NULL); } rvp = (struct run_vap *) malloc(sizeof(struct run_vap), M_80211_VAP, M_NOWAIT | M_ZERO); if (rvp == NULL) return (NULL); vap = &rvp->vap; if (ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac) != 0) { /* out of memory */ free(rvp, M_80211_VAP); return (NULL); } vap->iv_key_update_begin = run_key_update_begin; vap->iv_key_update_end = run_key_update_end; vap->iv_update_beacon = run_update_beacon; vap->iv_max_aid = RT2870_WCID_MAX; /* * To delete the right key from h/w, we need wcid. * Luckily, there is unused space in ieee80211_key{}, wk_pad, * and matching wcid will be written into there. So, cast * some spells to remove 'const' from ieee80211_key{} */ vap->iv_key_delete = (void *)run_key_delete; vap->iv_key_set = (void *)run_key_set; /* override state transition machine */ rvp->newstate = vap->iv_newstate; vap->iv_newstate = run_newstate; ieee80211_ratectl_init(vap); ieee80211_ratectl_setinterval(vap, 1000 /* 1 sec */); /* complete setup */ ieee80211_vap_attach(vap, run_media_change, ieee80211_media_status); /* make sure id is always unique */ for (i = 0; i < RUN_VAP_MAX; i++) { if((sc->rvp_bmap & 1 << i) == 0){ sc->rvp_bmap |= 1 << i; rvp->rvp_id = i; break; } } if (sc->rvp_cnt++ == 0) ic->ic_opmode = opmode; if (opmode == IEEE80211_M_HOSTAP) sc->cmdq_run = RUN_CMDQ_GO; DPRINTF("rvp_id=%d bmap=%x rvp_cnt=%d\n", rvp->rvp_id, sc->rvp_bmap, sc->rvp_cnt); return (vap); } static void run_vap_delete(struct ieee80211vap *vap) { struct run_vap *rvp = RUN_VAP(vap); struct ifnet *ifp; struct ieee80211com *ic; struct run_softc *sc; uint8_t rvp_id; if (vap == NULL) return; ic = vap->iv_ic; ifp = ic->ic_ifp; sc = ifp->if_softc; RUN_LOCK(sc); m_freem(rvp->beacon_mbuf); rvp->beacon_mbuf = NULL; rvp_id = rvp->rvp_id; sc->ratectl_run &= ~(1 << rvp_id); sc->rvp_bmap &= ~(1 << rvp_id); run_set_region_4(sc, RT2860_SKEY(rvp_id, 0), 0, 128); run_set_region_4(sc, RT2860_BCN_BASE(rvp_id), 0, 512); --sc->rvp_cnt; DPRINTF("vap=%p rvp_id=%d bmap=%x rvp_cnt=%d\n", vap, rvp_id, sc->rvp_bmap, sc->rvp_cnt); RUN_UNLOCK(sc); ieee80211_ratectl_deinit(vap); ieee80211_vap_detach(vap); free(rvp, M_80211_VAP); } /* * There are numbers of functions need to be called in context thread. * Rather than creating taskqueue event for each of those functions, * here is all-for-one taskqueue callback function. This function * gurantees deferred functions are executed in the same order they * were enqueued. * '& RUN_CMDQ_MASQ' is to loop cmdq[]. */ static void run_cmdq_cb(void *arg, int pending) { struct run_softc *sc = arg; uint8_t i; /* call cmdq[].func locked */ RUN_LOCK(sc); for (i = sc->cmdq_exec; sc->cmdq[i].func && pending; i = sc->cmdq_exec, pending--) { DPRINTFN(6, "cmdq_exec=%d pending=%d\n", i, pending); if (sc->cmdq_run == RUN_CMDQ_GO) { /* * If arg0 is NULL, callback func needs more * than one arg. So, pass ptr to cmdq struct. */ if (sc->cmdq[i].arg0) sc->cmdq[i].func(sc->cmdq[i].arg0); else sc->cmdq[i].func(&sc->cmdq[i]); } sc->cmdq[i].arg0 = NULL; sc->cmdq[i].func = NULL; sc->cmdq_exec++; sc->cmdq_exec &= RUN_CMDQ_MASQ; } RUN_UNLOCK(sc); } static void run_setup_tx_list(struct run_softc *sc, struct run_endpoint_queue *pq) { struct run_tx_data *data; memset(pq, 0, sizeof(*pq)); STAILQ_INIT(&pq->tx_qh); STAILQ_INIT(&pq->tx_fh); for (data = &pq->tx_data[0]; data < &pq->tx_data[RUN_TX_RING_COUNT]; data++) { data->sc = sc; STAILQ_INSERT_TAIL(&pq->tx_fh, data, next); } pq->tx_nfree = RUN_TX_RING_COUNT; } static void run_unsetup_tx_list(struct run_softc *sc, struct run_endpoint_queue *pq) { struct run_tx_data *data; /* make sure any subsequent use of the queues will fail */ pq->tx_nfree = 0; STAILQ_INIT(&pq->tx_fh); STAILQ_INIT(&pq->tx_qh); /* free up all node references and mbufs */ for (data = &pq->tx_data[0]; data < &pq->tx_data[RUN_TX_RING_COUNT]; data++) { if (data->m != NULL) { m_freem(data->m); data->m = NULL; } if (data->ni != NULL) { ieee80211_free_node(data->ni); data->ni = NULL; } } } static int run_load_microcode(struct run_softc *sc) { usb_device_request_t req; const struct firmware *fw; const u_char *base; uint32_t tmp; int ntries, error; const uint64_t *temp; uint64_t bytes; RUN_UNLOCK(sc); fw = firmware_get("runfw"); RUN_LOCK(sc); if (fw == NULL) { device_printf(sc->sc_dev, "failed loadfirmware of file %s\n", "runfw"); return ENOENT; } if (fw->datasize != 8192) { device_printf(sc->sc_dev, "invalid firmware size (should be 8KB)\n"); error = EINVAL; goto fail; } /* * RT3071/RT3072 use a different firmware * run-rt2870 (8KB) contains both, * first half (4KB) is for rt2870, * last half is for rt3071. */ base = fw->data; if ((sc->mac_ver) != 0x2860 && (sc->mac_ver) != 0x2872 && (sc->mac_ver) != 0x3070) { base += 4096; } /* cheap sanity check */ temp = fw->data; bytes = *temp; if (bytes != be64toh(0xffffff0210280210ULL)) { device_printf(sc->sc_dev, "firmware checksum failed\n"); error = EINVAL; goto fail; } /* write microcode image */ if (sc->sc_flags & RUN_FLAG_FWLOAD_NEEDED) { run_write_region_1(sc, RT2870_FW_BASE, base, 4096); run_write(sc, RT2860_H2M_MAILBOX_CID, 0xffffffff); run_write(sc, RT2860_H2M_MAILBOX_STATUS, 0xffffffff); } req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = RT2870_RESET; USETW(req.wValue, 8); USETW(req.wIndex, 0); USETW(req.wLength, 0); if ((error = usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, NULL)) != 0) { device_printf(sc->sc_dev, "firmware reset failed\n"); goto fail; } run_delay(sc, 10); run_write(sc, RT2860_H2M_BBPAGENT, 0); run_write(sc, RT2860_H2M_MAILBOX, 0); run_write(sc, RT2860_H2M_INTSRC, 0); if ((error = run_mcu_cmd(sc, RT2860_MCU_CMD_RFRESET, 0)) != 0) goto fail; /* wait until microcontroller is ready */ for (ntries = 0; ntries < 1000; ntries++) { if ((error = run_read(sc, RT2860_SYS_CTRL, &tmp)) != 0) goto fail; if (tmp & RT2860_MCU_READY) break; run_delay(sc, 10); } if (ntries == 1000) { device_printf(sc->sc_dev, "timeout waiting for MCU to initialize\n"); error = ETIMEDOUT; goto fail; } device_printf(sc->sc_dev, "firmware %s ver. %u.%u loaded\n", (base == fw->data) ? "RT2870" : "RT3071", *(base + 4092), *(base + 4093)); fail: firmware_put(fw, FIRMWARE_UNLOAD); return (error); } static int run_reset(struct run_softc *sc) { usb_device_request_t req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = RT2870_RESET; USETW(req.wValue, 1); USETW(req.wIndex, 0); USETW(req.wLength, 0); return (usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, NULL)); } static usb_error_t run_do_request(struct run_softc *sc, struct usb_device_request *req, void *data) { usb_error_t err; int ntries = 10; RUN_LOCK_ASSERT(sc, MA_OWNED); while (ntries--) { err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx, req, data, 0, NULL, 250 /* ms */); if (err == 0) break; DPRINTFN(1, "Control request failed, %s (retrying)\n", usbd_errstr(err)); run_delay(sc, 10); } return (err); } static int run_read(struct run_softc *sc, uint16_t reg, uint32_t *val) { uint32_t tmp; int error; error = run_read_region_1(sc, reg, (uint8_t *)&tmp, sizeof tmp); if (error == 0) *val = le32toh(tmp); else *val = 0xffffffff; return (error); } static int run_read_region_1(struct run_softc *sc, uint16_t reg, uint8_t *buf, int len) { usb_device_request_t req; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = RT2870_READ_REGION_1; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, len); return (run_do_request(sc, &req, buf)); } static int run_write_2(struct run_softc *sc, uint16_t reg, uint16_t val) { usb_device_request_t req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = RT2870_WRITE_2; USETW(req.wValue, val); USETW(req.wIndex, reg); USETW(req.wLength, 0); return (run_do_request(sc, &req, NULL)); } static int run_write(struct run_softc *sc, uint16_t reg, uint32_t val) { int error; if ((error = run_write_2(sc, reg, val & 0xffff)) == 0) error = run_write_2(sc, reg + 2, val >> 16); return (error); } static int run_write_region_1(struct run_softc *sc, uint16_t reg, const uint8_t *buf, int len) { #if 1 int i, error = 0; /* * NB: the WRITE_REGION_1 command is not stable on RT2860. * We thus issue multiple WRITE_2 commands instead. */ KASSERT((len & 1) == 0, ("run_write_region_1: Data too long.\n")); for (i = 0; i < len && error == 0; i += 2) error = run_write_2(sc, reg + i, buf[i] | buf[i + 1] << 8); return (error); #else usb_device_request_t req; int error = 0; /* * NOTE: It appears the WRITE_REGION_1 command cannot be * passed a huge amount of data, which will crash the * firmware. Limit amount of data passed to 64-bytes at a * time. */ while (len > 0) { int delta = 64; if (delta > len) delta = len; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = RT2870_WRITE_REGION_1; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, delta); error = run_do_request(sc, &req, __DECONST(uint8_t *, buf)); if (error != 0) break; reg += delta; buf += delta; len -= delta; } return (error); #endif } static int run_set_region_4(struct run_softc *sc, uint16_t reg, uint32_t val, int len) { int i, error = 0; KASSERT((len & 3) == 0, ("run_set_region_4: Invalid data length.\n")); for (i = 0; i < len && error == 0; i += 4) error = run_write(sc, reg + i, val); return (error); } static int run_efuse_read(struct run_softc *sc, uint16_t addr, uint16_t *val, int count) { uint32_t tmp; uint16_t reg; int error, ntries; if ((error = run_read(sc, RT3070_EFUSE_CTRL, &tmp)) != 0) return (error); if (count == 2) addr *= 2; /*- * Read one 16-byte block into registers EFUSE_DATA[0-3]: * DATA0: F E D C * DATA1: B A 9 8 * DATA2: 7 6 5 4 * DATA3: 3 2 1 0 */ tmp &= ~(RT3070_EFSROM_MODE_MASK | RT3070_EFSROM_AIN_MASK); tmp |= (addr & ~0xf) << RT3070_EFSROM_AIN_SHIFT | RT3070_EFSROM_KICK; run_write(sc, RT3070_EFUSE_CTRL, tmp); for (ntries = 0; ntries < 100; ntries++) { if ((error = run_read(sc, RT3070_EFUSE_CTRL, &tmp)) != 0) return (error); if (!(tmp & RT3070_EFSROM_KICK)) break; run_delay(sc, 2); } if (ntries == 100) return (ETIMEDOUT); if ((tmp & RT3070_EFUSE_AOUT_MASK) == RT3070_EFUSE_AOUT_MASK) { *val = 0xffff; /* address not found */ return (0); } /* determine to which 32-bit register our 16-bit word belongs */ reg = RT3070_EFUSE_DATA3 - (addr & 0xc); if ((error = run_read(sc, reg, &tmp)) != 0) return (error); tmp >>= (8 * (addr & 0x3)); *val = (addr & 1) ? tmp >> 16 : tmp & 0xffff; return (0); } /* Read 16-bit from eFUSE ROM for RT3xxx. */ static int run_efuse_read_2(struct run_softc *sc, uint16_t addr, uint16_t *val) { return (run_efuse_read(sc, addr, val, 2)); } static int run_eeprom_read_2(struct run_softc *sc, uint16_t addr, uint16_t *val) { usb_device_request_t req; uint16_t tmp; int error; addr *= 2; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = RT2870_EEPROM_READ; USETW(req.wValue, 0); USETW(req.wIndex, addr); USETW(req.wLength, sizeof(tmp)); error = usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, &tmp); if (error == 0) *val = le16toh(tmp); else *val = 0xffff; return (error); } static __inline int run_srom_read(struct run_softc *sc, uint16_t addr, uint16_t *val) { /* either eFUSE ROM or EEPROM */ return sc->sc_srom_read(sc, addr, val); } static int run_rt2870_rf_write(struct run_softc *sc, uint32_t val) { uint32_t tmp; int error, ntries; for (ntries = 0; ntries < 10; ntries++) { if ((error = run_read(sc, RT2860_RF_CSR_CFG0, &tmp)) != 0) return (error); if (!(tmp & RT2860_RF_REG_CTRL)) break; } if (ntries == 10) return (ETIMEDOUT); return (run_write(sc, RT2860_RF_CSR_CFG0, val)); } static int run_rt3070_rf_read(struct run_softc *sc, uint8_t reg, uint8_t *val) { uint32_t tmp; int error, ntries; for (ntries = 0; ntries < 100; ntries++) { if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0) return (error); if (!(tmp & RT3070_RF_KICK)) break; } if (ntries == 100) return (ETIMEDOUT); tmp = RT3070_RF_KICK | reg << 8; if ((error = run_write(sc, RT3070_RF_CSR_CFG, tmp)) != 0) return (error); for (ntries = 0; ntries < 100; ntries++) { if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0) return (error); if (!(tmp & RT3070_RF_KICK)) break; } if (ntries == 100) return (ETIMEDOUT); *val = tmp & 0xff; return (0); } static int run_rt3070_rf_write(struct run_softc *sc, uint8_t reg, uint8_t val) { uint32_t tmp; int error, ntries; for (ntries = 0; ntries < 10; ntries++) { if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0) return (error); if (!(tmp & RT3070_RF_KICK)) break; } if (ntries == 10) return (ETIMEDOUT); tmp = RT3070_RF_WRITE | RT3070_RF_KICK | reg << 8 | val; return (run_write(sc, RT3070_RF_CSR_CFG, tmp)); } static int run_bbp_read(struct run_softc *sc, uint8_t reg, uint8_t *val) { uint32_t tmp; int ntries, error; for (ntries = 0; ntries < 10; ntries++) { if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0) return (error); if (!(tmp & RT2860_BBP_CSR_KICK)) break; } if (ntries == 10) return (ETIMEDOUT); tmp = RT2860_BBP_CSR_READ | RT2860_BBP_CSR_KICK | reg << 8; if ((error = run_write(sc, RT2860_BBP_CSR_CFG, tmp)) != 0) return (error); for (ntries = 0; ntries < 10; ntries++) { if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0) return (error); if (!(tmp & RT2860_BBP_CSR_KICK)) break; } if (ntries == 10) return (ETIMEDOUT); *val = tmp & 0xff; return (0); } static int run_bbp_write(struct run_softc *sc, uint8_t reg, uint8_t val) { uint32_t tmp; int ntries, error; for (ntries = 0; ntries < 10; ntries++) { if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0) return (error); if (!(tmp & RT2860_BBP_CSR_KICK)) break; } if (ntries == 10) return (ETIMEDOUT); tmp = RT2860_BBP_CSR_KICK | reg << 8 | val; return (run_write(sc, RT2860_BBP_CSR_CFG, tmp)); } /* * Send a command to the 8051 microcontroller unit. */ static int run_mcu_cmd(struct run_softc *sc, uint8_t cmd, uint16_t arg) { uint32_t tmp; int error, ntries; for (ntries = 0; ntries < 100; ntries++) { if ((error = run_read(sc, RT2860_H2M_MAILBOX, &tmp)) != 0) return error; if (!(tmp & RT2860_H2M_BUSY)) break; } if (ntries == 100) return ETIMEDOUT; tmp = RT2860_H2M_BUSY | RT2860_TOKEN_NO_INTR << 16 | arg; if ((error = run_write(sc, RT2860_H2M_MAILBOX, tmp)) == 0) error = run_write(sc, RT2860_HOST_CMD, cmd); return (error); } /* * Add `delta' (signed) to each 4-bit sub-word of a 32-bit word. * Used to adjust per-rate Tx power registers. */ static __inline uint32_t b4inc(uint32_t b32, int8_t delta) { int8_t i, b4; for (i = 0; i < 8; i++) { b4 = b32 & 0xf; b4 += delta; if (b4 < 0) b4 = 0; else if (b4 > 0xf) b4 = 0xf; b32 = b32 >> 4 | b4 << 28; } return (b32); } static const char * run_get_rf(uint16_t rev) { switch (rev) { case RT2860_RF_2820: return "RT2820"; case RT2860_RF_2850: return "RT2850"; case RT2860_RF_2720: return "RT2720"; case RT2860_RF_2750: return "RT2750"; case RT3070_RF_3020: return "RT3020"; case RT3070_RF_2020: return "RT2020"; case RT3070_RF_3021: return "RT3021"; case RT3070_RF_3022: return "RT3022"; case RT3070_RF_3052: return "RT3052"; case RT3593_RF_3053: return "RT3053"; case RT5592_RF_5592: return "RT5592"; case RT5390_RF_5370: return "RT5370"; case RT5390_RF_5372: return "RT5372"; } return ("unknown"); } static void run_rt3593_get_txpower(struct run_softc *sc) { uint16_t addr, val; int i; /* Read power settings for 2GHz channels. */ for (i = 0; i < 14; i += 2) { addr = (sc->ntxchains == 3) ? RT3593_EEPROM_PWR2GHZ_BASE1 : RT2860_EEPROM_PWR2GHZ_BASE1; run_srom_read(sc, addr + i / 2, &val); sc->txpow1[i + 0] = (int8_t)(val & 0xff); sc->txpow1[i + 1] = (int8_t)(val >> 8); addr = (sc->ntxchains == 3) ? RT3593_EEPROM_PWR2GHZ_BASE2 : RT2860_EEPROM_PWR2GHZ_BASE2; run_srom_read(sc, addr + i / 2, &val); sc->txpow2[i + 0] = (int8_t)(val & 0xff); sc->txpow2[i + 1] = (int8_t)(val >> 8); if (sc->ntxchains == 3) { run_srom_read(sc, RT3593_EEPROM_PWR2GHZ_BASE3 + i / 2, &val); sc->txpow3[i + 0] = (int8_t)(val & 0xff); sc->txpow3[i + 1] = (int8_t)(val >> 8); } } /* Fix broken Tx power entries. */ for (i = 0; i < 14; i++) { if (sc->txpow1[i] > 31) sc->txpow1[i] = 5; if (sc->txpow2[i] > 31) sc->txpow2[i] = 5; if (sc->ntxchains == 3) { if (sc->txpow3[i] > 31) sc->txpow3[i] = 5; } } /* Read power settings for 5GHz channels. */ for (i = 0; i < 40; i += 2) { run_srom_read(sc, RT3593_EEPROM_PWR5GHZ_BASE1 + i / 2, &val); sc->txpow1[i + 14] = (int8_t)(val & 0xff); sc->txpow1[i + 15] = (int8_t)(val >> 8); run_srom_read(sc, RT3593_EEPROM_PWR5GHZ_BASE2 + i / 2, &val); sc->txpow2[i + 14] = (int8_t)(val & 0xff); sc->txpow2[i + 15] = (int8_t)(val >> 8); if (sc->ntxchains == 3) { run_srom_read(sc, RT3593_EEPROM_PWR5GHZ_BASE3 + i / 2, &val); sc->txpow3[i + 14] = (int8_t)(val & 0xff); sc->txpow3[i + 15] = (int8_t)(val >> 8); } } } static void run_get_txpower(struct run_softc *sc) { uint16_t val; int i; /* Read power settings for 2GHz channels. */ for (i = 0; i < 14; i += 2) { run_srom_read(sc, RT2860_EEPROM_PWR2GHZ_BASE1 + i / 2, &val); sc->txpow1[i + 0] = (int8_t)(val & 0xff); sc->txpow1[i + 1] = (int8_t)(val >> 8); if (sc->mac_ver != 0x5390) { run_srom_read(sc, RT2860_EEPROM_PWR2GHZ_BASE2 + i / 2, &val); sc->txpow2[i + 0] = (int8_t)(val & 0xff); sc->txpow2[i + 1] = (int8_t)(val >> 8); } } /* Fix broken Tx power entries. */ for (i = 0; i < 14; i++) { if (sc->mac_ver >= 0x5390) { if (sc->txpow1[i] < 0 || sc->txpow1[i] > 27) sc->txpow1[i] = 5; } else { if (sc->txpow1[i] < 0 || sc->txpow1[i] > 31) sc->txpow1[i] = 5; } if (sc->mac_ver > 0x5390) { if (sc->txpow2[i] < 0 || sc->txpow2[i] > 27) sc->txpow2[i] = 5; } else if (sc->mac_ver < 0x5390) { if (sc->txpow2[i] < 0 || sc->txpow2[i] > 31) sc->txpow2[i] = 5; } DPRINTF("chan %d: power1=%d, power2=%d\n", rt2860_rf2850[i].chan, sc->txpow1[i], sc->txpow2[i]); } /* Read power settings for 5GHz channels. */ for (i = 0; i < 40; i += 2) { run_srom_read(sc, RT2860_EEPROM_PWR5GHZ_BASE1 + i / 2, &val); sc->txpow1[i + 14] = (int8_t)(val & 0xff); sc->txpow1[i + 15] = (int8_t)(val >> 8); run_srom_read(sc, RT2860_EEPROM_PWR5GHZ_BASE2 + i / 2, &val); sc->txpow2[i + 14] = (int8_t)(val & 0xff); sc->txpow2[i + 15] = (int8_t)(val >> 8); } /* Fix broken Tx power entries. */ for (i = 0; i < 40; i++ ) { if (sc->mac_ver != 0x5592) { if (sc->txpow1[14 + i] < -7 || sc->txpow1[14 + i] > 15) sc->txpow1[14 + i] = 5; if (sc->txpow2[14 + i] < -7 || sc->txpow2[14 + i] > 15) sc->txpow2[14 + i] = 5; } DPRINTF("chan %d: power1=%d, power2=%d\n", rt2860_rf2850[14 + i].chan, sc->txpow1[14 + i], sc->txpow2[14 + i]); } } static int run_read_eeprom(struct run_softc *sc) { int8_t delta_2ghz, delta_5ghz; uint32_t tmp; uint16_t val; int ridx, ant, i; /* check whether the ROM is eFUSE ROM or EEPROM */ sc->sc_srom_read = run_eeprom_read_2; if (sc->mac_ver >= 0x3070) { run_read(sc, RT3070_EFUSE_CTRL, &tmp); DPRINTF("EFUSE_CTRL=0x%08x\n", tmp); if ((tmp & RT3070_SEL_EFUSE) || sc->mac_ver == 0x3593) sc->sc_srom_read = run_efuse_read_2; } /* read ROM version */ run_srom_read(sc, RT2860_EEPROM_VERSION, &val); DPRINTF("EEPROM rev=%d, FAE=%d\n", val & 0xff, val >> 8); /* read MAC address */ run_srom_read(sc, RT2860_EEPROM_MAC01, &val); sc->sc_bssid[0] = val & 0xff; sc->sc_bssid[1] = val >> 8; run_srom_read(sc, RT2860_EEPROM_MAC23, &val); sc->sc_bssid[2] = val & 0xff; sc->sc_bssid[3] = val >> 8; run_srom_read(sc, RT2860_EEPROM_MAC45, &val); sc->sc_bssid[4] = val & 0xff; sc->sc_bssid[5] = val >> 8; if (sc->mac_ver < 0x3593) { /* read vender BBP settings */ for (i = 0; i < 10; i++) { run_srom_read(sc, RT2860_EEPROM_BBP_BASE + i, &val); sc->bbp[i].val = val & 0xff; sc->bbp[i].reg = val >> 8; DPRINTF("BBP%d=0x%02x\n", sc->bbp[i].reg, sc->bbp[i].val); } if (sc->mac_ver >= 0x3071) { /* read vendor RF settings */ for (i = 0; i < 10; i++) { run_srom_read(sc, RT3071_EEPROM_RF_BASE + i, &val); sc->rf[i].val = val & 0xff; sc->rf[i].reg = val >> 8; DPRINTF("RF%d=0x%02x\n", sc->rf[i].reg, sc->rf[i].val); } } } /* read RF frequency offset from EEPROM */ run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_FREQ_LEDS : RT3593_EEPROM_FREQ, &val); sc->freq = ((val & 0xff) != 0xff) ? val & 0xff : 0; DPRINTF("EEPROM freq offset %d\n", sc->freq & 0xff); run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_FREQ_LEDS : RT3593_EEPROM_FREQ_LEDS, &val); if (val >> 8 != 0xff) { /* read LEDs operating mode */ sc->leds = val >> 8; run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_LED1 : RT3593_EEPROM_LED1, &sc->led[0]); run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_LED2 : RT3593_EEPROM_LED2, &sc->led[1]); run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_LED3 : RT3593_EEPROM_LED3, &sc->led[2]); } else { /* broken EEPROM, use default settings */ sc->leds = 0x01; sc->led[0] = 0x5555; sc->led[1] = 0x2221; sc->led[2] = 0x5627; /* differs from RT2860 */ } DPRINTF("EEPROM LED mode=0x%02x, LEDs=0x%04x/0x%04x/0x%04x\n", sc->leds, sc->led[0], sc->led[1], sc->led[2]); /* read RF information */ if (sc->mac_ver == 0x5390 || sc->mac_ver ==0x5392) run_srom_read(sc, 0x00, &val); else run_srom_read(sc, RT2860_EEPROM_ANTENNA, &val); if (val == 0xffff) { device_printf(sc->sc_dev, "invalid EEPROM antenna info, using default\n"); DPRINTF("invalid EEPROM antenna info, using default\n"); if (sc->mac_ver == 0x3572) { /* default to RF3052 2T2R */ sc->rf_rev = RT3070_RF_3052; sc->ntxchains = 2; sc->nrxchains = 2; } else if (sc->mac_ver >= 0x3070) { /* default to RF3020 1T1R */ sc->rf_rev = RT3070_RF_3020; sc->ntxchains = 1; sc->nrxchains = 1; } else { /* default to RF2820 1T2R */ sc->rf_rev = RT2860_RF_2820; sc->ntxchains = 1; sc->nrxchains = 2; } } else { if (sc->mac_ver == 0x5390 || sc->mac_ver ==0x5392) { sc->rf_rev = val; run_srom_read(sc, RT2860_EEPROM_ANTENNA, &val); } else sc->rf_rev = (val >> 8) & 0xf; sc->ntxchains = (val >> 4) & 0xf; sc->nrxchains = val & 0xf; } DPRINTF("EEPROM RF rev=0x%04x chains=%dT%dR\n", sc->rf_rev, sc->ntxchains, sc->nrxchains); /* check if RF supports automatic Tx access gain control */ run_srom_read(sc, RT2860_EEPROM_CONFIG, &val); DPRINTF("EEPROM CFG 0x%04x\n", val); /* check if driver should patch the DAC issue */ if ((val >> 8) != 0xff) sc->patch_dac = (val >> 15) & 1; if ((val & 0xff) != 0xff) { sc->ext_5ghz_lna = (val >> 3) & 1; sc->ext_2ghz_lna = (val >> 2) & 1; /* check if RF supports automatic Tx access gain control */ sc->calib_2ghz = sc->calib_5ghz = (val >> 1) & 1; /* check if we have a hardware radio switch */ sc->rfswitch = val & 1; } /* Read Tx power settings. */ if (sc->mac_ver == 0x3593) run_rt3593_get_txpower(sc); else run_get_txpower(sc); /* read Tx power compensation for each Tx rate */ run_srom_read(sc, RT2860_EEPROM_DELTAPWR, &val); delta_2ghz = delta_5ghz = 0; if ((val & 0xff) != 0xff && (val & 0x80)) { delta_2ghz = val & 0xf; if (!(val & 0x40)) /* negative number */ delta_2ghz = -delta_2ghz; } val >>= 8; if ((val & 0xff) != 0xff && (val & 0x80)) { delta_5ghz = val & 0xf; if (!(val & 0x40)) /* negative number */ delta_5ghz = -delta_5ghz; } DPRINTF("power compensation=%d (2GHz), %d (5GHz)\n", delta_2ghz, delta_5ghz); for (ridx = 0; ridx < 5; ridx++) { uint32_t reg; run_srom_read(sc, RT2860_EEPROM_RPWR + ridx * 2, &val); reg = val; run_srom_read(sc, RT2860_EEPROM_RPWR + ridx * 2 + 1, &val); reg |= (uint32_t)val << 16; sc->txpow20mhz[ridx] = reg; sc->txpow40mhz_2ghz[ridx] = b4inc(reg, delta_2ghz); sc->txpow40mhz_5ghz[ridx] = b4inc(reg, delta_5ghz); DPRINTF("ridx %d: power 20MHz=0x%08x, 40MHz/2GHz=0x%08x, " "40MHz/5GHz=0x%08x\n", ridx, sc->txpow20mhz[ridx], sc->txpow40mhz_2ghz[ridx], sc->txpow40mhz_5ghz[ridx]); } /* Read RSSI offsets and LNA gains from EEPROM. */ run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_RSSI1_2GHZ : RT3593_EEPROM_RSSI1_2GHZ, &val); sc->rssi_2ghz[0] = val & 0xff; /* Ant A */ sc->rssi_2ghz[1] = val >> 8; /* Ant B */ run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_RSSI2_2GHZ : RT3593_EEPROM_RSSI2_2GHZ, &val); if (sc->mac_ver >= 0x3070) { if (sc->mac_ver == 0x3593) { sc->txmixgain_2ghz = 0; sc->rssi_2ghz[2] = val & 0xff; /* Ant C */ } else { /* * On RT3070 chips (limited to 2 Rx chains), this ROM * field contains the Tx mixer gain for the 2GHz band. */ if ((val & 0xff) != 0xff) sc->txmixgain_2ghz = val & 0x7; } DPRINTF("tx mixer gain=%u (2GHz)\n", sc->txmixgain_2ghz); } else sc->rssi_2ghz[2] = val & 0xff; /* Ant C */ if (sc->mac_ver == 0x3593) run_srom_read(sc, RT3593_EEPROM_LNA_5GHZ, &val); sc->lna[2] = val >> 8; /* channel group 2 */ run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_RSSI1_5GHZ : RT3593_EEPROM_RSSI1_5GHZ, &val); sc->rssi_5ghz[0] = val & 0xff; /* Ant A */ sc->rssi_5ghz[1] = val >> 8; /* Ant B */ run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_RSSI2_5GHZ : RT3593_EEPROM_RSSI2_5GHZ, &val); if (sc->mac_ver == 0x3572) { /* * On RT3572 chips (limited to 2 Rx chains), this ROM * field contains the Tx mixer gain for the 5GHz band. */ if ((val & 0xff) != 0xff) sc->txmixgain_5ghz = val & 0x7; DPRINTF("tx mixer gain=%u (5GHz)\n", sc->txmixgain_5ghz); } else sc->rssi_5ghz[2] = val & 0xff; /* Ant C */ if (sc->mac_ver == 0x3593) { sc->txmixgain_5ghz = 0; run_srom_read(sc, RT3593_EEPROM_LNA_5GHZ, &val); } sc->lna[3] = val >> 8; /* channel group 3 */ run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_LNA : RT3593_EEPROM_LNA, &val); sc->lna[0] = val & 0xff; /* channel group 0 */ sc->lna[1] = val >> 8; /* channel group 1 */ /* fix broken 5GHz LNA entries */ if (sc->lna[2] == 0 || sc->lna[2] == 0xff) { DPRINTF("invalid LNA for channel group %d\n", 2); sc->lna[2] = sc->lna[1]; } if (sc->lna[3] == 0 || sc->lna[3] == 0xff) { DPRINTF("invalid LNA for channel group %d\n", 3); sc->lna[3] = sc->lna[1]; } /* fix broken RSSI offset entries */ for (ant = 0; ant < 3; ant++) { if (sc->rssi_2ghz[ant] < -10 || sc->rssi_2ghz[ant] > 10) { DPRINTF("invalid RSSI%d offset: %d (2GHz)\n", ant + 1, sc->rssi_2ghz[ant]); sc->rssi_2ghz[ant] = 0; } if (sc->rssi_5ghz[ant] < -10 || sc->rssi_5ghz[ant] > 10) { DPRINTF("invalid RSSI%d offset: %d (5GHz)\n", ant + 1, sc->rssi_5ghz[ant]); sc->rssi_5ghz[ant] = 0; } } return (0); } static struct ieee80211_node * run_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN]) { return malloc(sizeof (struct run_node), M_DEVBUF, M_NOWAIT | M_ZERO); } static int run_media_change(struct ifnet *ifp) { struct ieee80211vap *vap = ifp->if_softc; struct ieee80211com *ic = vap->iv_ic; const struct ieee80211_txparam *tp; struct run_softc *sc = ic->ic_ifp->if_softc; uint8_t rate, ridx; int error; RUN_LOCK(sc); error = ieee80211_media_change(ifp); if (error != ENETRESET) { RUN_UNLOCK(sc); return (error); } tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)]; if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) { struct ieee80211_node *ni; struct run_node *rn; rate = ic->ic_sup_rates[ic->ic_curmode]. rs_rates[tp->ucastrate] & IEEE80211_RATE_VAL; for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++) if (rt2860_rates[ridx].rate == rate) break; ni = ieee80211_ref_node(vap->iv_bss); rn = (struct run_node *)ni; rn->fix_ridx = ridx; DPRINTF("rate=%d, fix_ridx=%d\n", rate, rn->fix_ridx); ieee80211_free_node(ni); } #if 0 if ((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING)){ run_init_locked(sc); } #endif RUN_UNLOCK(sc); return (0); } static int run_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg) { const struct ieee80211_txparam *tp; struct ieee80211com *ic = vap->iv_ic; struct run_softc *sc = ic->ic_ifp->if_softc; struct run_vap *rvp = RUN_VAP(vap); enum ieee80211_state ostate; uint32_t sta[3]; uint32_t tmp; uint8_t ratectl; uint8_t restart_ratectl = 0; uint8_t bid = 1 << rvp->rvp_id; ostate = vap->iv_state; DPRINTF("%s -> %s\n", ieee80211_state_name[ostate], ieee80211_state_name[nstate]); IEEE80211_UNLOCK(ic); RUN_LOCK(sc); ratectl = sc->ratectl_run; /* remember current state */ sc->ratectl_run = RUN_RATECTL_OFF; usb_callout_stop(&sc->ratectl_ch); if (ostate == IEEE80211_S_RUN) { /* turn link LED off */ run_set_leds(sc, RT2860_LED_RADIO); } switch (nstate) { case IEEE80211_S_INIT: restart_ratectl = 1; if (ostate != IEEE80211_S_RUN) break; ratectl &= ~bid; sc->runbmap &= ~bid; /* abort TSF synchronization if there is no vap running */ if (--sc->running == 0) { run_read(sc, RT2860_BCN_TIME_CFG, &tmp); run_write(sc, RT2860_BCN_TIME_CFG, tmp & ~(RT2860_BCN_TX_EN | RT2860_TSF_TIMER_EN | RT2860_TBTT_TIMER_EN)); } break; case IEEE80211_S_RUN: if (!(sc->runbmap & bid)) { if(sc->running++) restart_ratectl = 1; sc->runbmap |= bid; } m_freem(rvp->beacon_mbuf); rvp->beacon_mbuf = NULL; switch (vap->iv_opmode) { case IEEE80211_M_HOSTAP: case IEEE80211_M_MBSS: sc->ap_running |= bid; ic->ic_opmode = vap->iv_opmode; run_update_beacon_cb(vap); break; case IEEE80211_M_IBSS: sc->adhoc_running |= bid; if (!sc->ap_running) ic->ic_opmode = vap->iv_opmode; run_update_beacon_cb(vap); break; case IEEE80211_M_STA: sc->sta_running |= bid; if (!sc->ap_running && !sc->adhoc_running) ic->ic_opmode = vap->iv_opmode; /* read statistic counters (clear on read) */ run_read_region_1(sc, RT2860_TX_STA_CNT0, (uint8_t *)sta, sizeof sta); break; default: ic->ic_opmode = vap->iv_opmode; break; } if (vap->iv_opmode != IEEE80211_M_MONITOR) { struct ieee80211_node *ni; if (ic->ic_bsschan == IEEE80211_CHAN_ANYC) { RUN_UNLOCK(sc); IEEE80211_LOCK(ic); return (-1); } run_updateslot(ic->ic_ifp); run_enable_mrr(sc); run_set_txpreamble(sc); run_set_basicrates(sc); ni = ieee80211_ref_node(vap->iv_bss); IEEE80211_ADDR_COPY(sc->sc_bssid, ni->ni_bssid); run_set_bssid(sc, ni->ni_bssid); ieee80211_free_node(ni); run_enable_tsf_sync(sc); /* enable automatic rate adaptation */ tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)]; if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE) ratectl |= bid; } /* turn link LED on */ run_set_leds(sc, RT2860_LED_RADIO | (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan) ? RT2860_LED_LINK_2GHZ : RT2860_LED_LINK_5GHZ)); break; default: DPRINTFN(6, "undefined case\n"); break; } /* restart amrr for running VAPs */ if ((sc->ratectl_run = ratectl) && restart_ratectl) usb_callout_reset(&sc->ratectl_ch, hz, run_ratectl_to, sc); RUN_UNLOCK(sc); IEEE80211_LOCK(ic); return(rvp->newstate(vap, nstate, arg)); } /* ARGSUSED */ static void run_wme_update_cb(void *arg) { struct ieee80211com *ic = arg; struct run_softc *sc = ic->ic_ifp->if_softc; struct ieee80211_wme_state *wmesp = &ic->ic_wme; int aci, error = 0; RUN_LOCK_ASSERT(sc, MA_OWNED); /* update MAC TX configuration registers */ for (aci = 0; aci < WME_NUM_AC; aci++) { error = run_write(sc, RT2860_EDCA_AC_CFG(aci), wmesp->wme_params[aci].wmep_logcwmax << 16 | wmesp->wme_params[aci].wmep_logcwmin << 12 | wmesp->wme_params[aci].wmep_aifsn << 8 | wmesp->wme_params[aci].wmep_txopLimit); if (error) goto err; } /* update SCH/DMA registers too */ error = run_write(sc, RT2860_WMM_AIFSN_CFG, wmesp->wme_params[WME_AC_VO].wmep_aifsn << 12 | wmesp->wme_params[WME_AC_VI].wmep_aifsn << 8 | wmesp->wme_params[WME_AC_BK].wmep_aifsn << 4 | wmesp->wme_params[WME_AC_BE].wmep_aifsn); if (error) goto err; error = run_write(sc, RT2860_WMM_CWMIN_CFG, wmesp->wme_params[WME_AC_VO].wmep_logcwmin << 12 | wmesp->wme_params[WME_AC_VI].wmep_logcwmin << 8 | wmesp->wme_params[WME_AC_BK].wmep_logcwmin << 4 | wmesp->wme_params[WME_AC_BE].wmep_logcwmin); if (error) goto err; error = run_write(sc, RT2860_WMM_CWMAX_CFG, wmesp->wme_params[WME_AC_VO].wmep_logcwmax << 12 | wmesp->wme_params[WME_AC_VI].wmep_logcwmax << 8 | wmesp->wme_params[WME_AC_BK].wmep_logcwmax << 4 | wmesp->wme_params[WME_AC_BE].wmep_logcwmax); if (error) goto err; error = run_write(sc, RT2860_WMM_TXOP0_CFG, wmesp->wme_params[WME_AC_BK].wmep_txopLimit << 16 | wmesp->wme_params[WME_AC_BE].wmep_txopLimit); if (error) goto err; error = run_write(sc, RT2860_WMM_TXOP1_CFG, wmesp->wme_params[WME_AC_VO].wmep_txopLimit << 16 | wmesp->wme_params[WME_AC_VI].wmep_txopLimit); err: if (error) DPRINTF("WME update failed\n"); return; } static int run_wme_update(struct ieee80211com *ic) { struct run_softc *sc = ic->ic_ifp->if_softc; /* sometime called wothout lock */ if (mtx_owned(&ic->ic_comlock.mtx)) { uint32_t i = RUN_CMDQ_GET(&sc->cmdq_store); DPRINTF("cmdq_store=%d\n", i); sc->cmdq[i].func = run_wme_update_cb; sc->cmdq[i].arg0 = ic; ieee80211_runtask(ic, &sc->cmdq_task); return (0); } RUN_LOCK(sc); run_wme_update_cb(ic); RUN_UNLOCK(sc); /* return whatever, upper layer desn't care anyway */ return (0); } static void run_key_update_begin(struct ieee80211vap *vap) { /* * To avoid out-of-order events, both run_key_set() and * _delete() are deferred and handled by run_cmdq_cb(). * So, there is nothing we need to do here. */ } static void run_key_update_end(struct ieee80211vap *vap) { /* null */ } static void run_key_set_cb(void *arg) { struct run_cmdq *cmdq = arg; struct ieee80211vap *vap = cmdq->arg1; struct ieee80211_key *k = cmdq->k; struct ieee80211com *ic = vap->iv_ic; struct run_softc *sc = ic->ic_ifp->if_softc; struct ieee80211_node *ni; uint32_t attr; uint16_t base, associd; uint8_t mode, wcid, iv[8]; RUN_LOCK_ASSERT(sc, MA_OWNED); if (vap->iv_opmode == IEEE80211_M_HOSTAP) ni = ieee80211_find_vap_node(&ic->ic_sta, vap, cmdq->mac); else ni = vap->iv_bss; associd = (ni != NULL) ? ni->ni_associd : 0; /* map net80211 cipher to RT2860 security mode */ switch (k->wk_cipher->ic_cipher) { case IEEE80211_CIPHER_WEP: if(k->wk_keylen < 8) mode = RT2860_MODE_WEP40; else mode = RT2860_MODE_WEP104; break; case IEEE80211_CIPHER_TKIP: mode = RT2860_MODE_TKIP; break; case IEEE80211_CIPHER_AES_CCM: mode = RT2860_MODE_AES_CCMP; break; default: DPRINTF("undefined case\n"); return; } DPRINTFN(1, "associd=%x, keyix=%d, mode=%x, type=%s, tx=%s, rx=%s\n", associd, k->wk_keyix, mode, (k->wk_flags & IEEE80211_KEY_GROUP) ? "group" : "pairwise", (k->wk_flags & IEEE80211_KEY_XMIT) ? "on" : "off", (k->wk_flags & IEEE80211_KEY_RECV) ? "on" : "off"); if (k->wk_flags & IEEE80211_KEY_GROUP) { wcid = 0; /* NB: update WCID0 for group keys */ base = RT2860_SKEY(RUN_VAP(vap)->rvp_id, k->wk_keyix); } else { wcid = (vap->iv_opmode == IEEE80211_M_STA) ? 1 : RUN_AID2WCID(associd); base = RT2860_PKEY(wcid); } if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP) { if(run_write_region_1(sc, base, k->wk_key, 16)) return; if(run_write_region_1(sc, base + 16, &k->wk_key[16], 8)) /* wk_txmic */ return; if(run_write_region_1(sc, base + 24, &k->wk_key[24], 8)) /* wk_rxmic */ return; } else { /* roundup len to 16-bit: XXX fix write_region_1() instead */ if(run_write_region_1(sc, base, k->wk_key, (k->wk_keylen + 1) & ~1)) return; } if (!(k->wk_flags & IEEE80211_KEY_GROUP) || (k->wk_flags & (IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV))) { /* set initial packet number in IV+EIV */ if (k->wk_cipher == IEEE80211_CIPHER_WEP) { memset(iv, 0, sizeof iv); iv[3] = vap->iv_def_txkey << 6; } else { if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP) { iv[0] = k->wk_keytsc >> 8; iv[1] = (iv[0] | 0x20) & 0x7f; iv[2] = k->wk_keytsc; } else /* CCMP */ { iv[0] = k->wk_keytsc; iv[1] = k->wk_keytsc >> 8; iv[2] = 0; } iv[3] = k->wk_keyix << 6 | IEEE80211_WEP_EXTIV; iv[4] = k->wk_keytsc >> 16; iv[5] = k->wk_keytsc >> 24; iv[6] = k->wk_keytsc >> 32; iv[7] = k->wk_keytsc >> 40; } if (run_write_region_1(sc, RT2860_IVEIV(wcid), iv, 8)) return; } if (k->wk_flags & IEEE80211_KEY_GROUP) { /* install group key */ if (run_read(sc, RT2860_SKEY_MODE_0_7, &attr)) return; attr &= ~(0xf << (k->wk_keyix * 4)); attr |= mode << (k->wk_keyix * 4); if (run_write(sc, RT2860_SKEY_MODE_0_7, attr)) return; } else { /* install pairwise key */ if (run_read(sc, RT2860_WCID_ATTR(wcid), &attr)) return; attr = (attr & ~0xf) | (mode << 1) | RT2860_RX_PKEY_EN; if (run_write(sc, RT2860_WCID_ATTR(wcid), attr)) return; } /* TODO create a pass-thru key entry? */ /* need wcid to delete the right key later */ k->wk_pad = wcid; } /* * Don't have to be deferred, but in order to keep order of * execution, i.e. with run_key_delete(), defer this and let * run_cmdq_cb() maintain the order. * * return 0 on error */ static int run_key_set(struct ieee80211vap *vap, struct ieee80211_key *k, const uint8_t mac[IEEE80211_ADDR_LEN]) { struct ieee80211com *ic = vap->iv_ic; struct run_softc *sc = ic->ic_ifp->if_softc; uint32_t i; i = RUN_CMDQ_GET(&sc->cmdq_store); DPRINTF("cmdq_store=%d\n", i); sc->cmdq[i].func = run_key_set_cb; sc->cmdq[i].arg0 = NULL; sc->cmdq[i].arg1 = vap; sc->cmdq[i].k = k; IEEE80211_ADDR_COPY(sc->cmdq[i].mac, mac); ieee80211_runtask(ic, &sc->cmdq_task); /* * To make sure key will be set when hostapd * calls iv_key_set() before if_init(). */ if (vap->iv_opmode == IEEE80211_M_HOSTAP) { RUN_LOCK(sc); sc->cmdq_key_set = RUN_CMDQ_GO; RUN_UNLOCK(sc); } return (1); } /* * If wlan is destroyed without being brought down i.e. without * wlan down or wpa_cli terminate, this function is called after * vap is gone. Don't refer it. */ static void run_key_delete_cb(void *arg) { struct run_cmdq *cmdq = arg; struct run_softc *sc = cmdq->arg1; struct ieee80211_key *k = &cmdq->key; uint32_t attr; uint8_t wcid; RUN_LOCK_ASSERT(sc, MA_OWNED); if (k->wk_flags & IEEE80211_KEY_GROUP) { /* remove group key */ DPRINTF("removing group key\n"); run_read(sc, RT2860_SKEY_MODE_0_7, &attr); attr &= ~(0xf << (k->wk_keyix * 4)); run_write(sc, RT2860_SKEY_MODE_0_7, attr); } else { /* remove pairwise key */ DPRINTF("removing key for wcid %x\n", k->wk_pad); /* matching wcid was written to wk_pad in run_key_set() */ wcid = k->wk_pad; run_read(sc, RT2860_WCID_ATTR(wcid), &attr); attr &= ~0xf; run_write(sc, RT2860_WCID_ATTR(wcid), attr); run_set_region_4(sc, RT2860_WCID_ENTRY(wcid), 0, 8); } k->wk_pad = 0; } /* * return 0 on error */ static int run_key_delete(struct ieee80211vap *vap, struct ieee80211_key *k) { struct ieee80211com *ic = vap->iv_ic; struct run_softc *sc = ic->ic_ifp->if_softc; struct ieee80211_key *k0; uint32_t i; /* * When called back, key might be gone. So, make a copy * of some values need to delete keys before deferring. * But, because of LOR with node lock, cannot use lock here. * So, use atomic instead. */ i = RUN_CMDQ_GET(&sc->cmdq_store); DPRINTF("cmdq_store=%d\n", i); sc->cmdq[i].func = run_key_delete_cb; sc->cmdq[i].arg0 = NULL; sc->cmdq[i].arg1 = sc; k0 = &sc->cmdq[i].key; k0->wk_flags = k->wk_flags; k0->wk_keyix = k->wk_keyix; /* matching wcid was written to wk_pad in run_key_set() */ k0->wk_pad = k->wk_pad; ieee80211_runtask(ic, &sc->cmdq_task); return (1); /* return fake success */ } static void run_ratectl_to(void *arg) { struct run_softc *sc = arg; /* do it in a process context, so it can go sleep */ ieee80211_runtask(sc->sc_ifp->if_l2com, &sc->ratectl_task); /* next timeout will be rescheduled in the callback task */ } /* ARGSUSED */ static void run_ratectl_cb(void *arg, int pending) { struct run_softc *sc = arg; struct ieee80211com *ic = sc->sc_ifp->if_l2com; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); if (vap == NULL) return; if (sc->rvp_cnt > 1 || vap->iv_opmode != IEEE80211_M_STA) { /* * run_reset_livelock() doesn't do anything with AMRR, * but Ralink wants us to call it every 1 sec. So, we * piggyback here rather than creating another callout. * Livelock may occur only in HOSTAP or IBSS mode * (when h/w is sending beacons). */ RUN_LOCK(sc); run_reset_livelock(sc); /* just in case, there are some stats to drain */ run_drain_fifo(sc); RUN_UNLOCK(sc); } ieee80211_iterate_nodes(&ic->ic_sta, run_iter_func, sc); RUN_LOCK(sc); if(sc->ratectl_run != RUN_RATECTL_OFF) usb_callout_reset(&sc->ratectl_ch, hz, run_ratectl_to, sc); RUN_UNLOCK(sc); } static void run_drain_fifo(void *arg) { struct run_softc *sc = arg; struct ifnet *ifp = sc->sc_ifp; uint32_t stat; uint16_t (*wstat)[3]; uint8_t wcid, mcs, pid; int8_t retry; RUN_LOCK_ASSERT(sc, MA_OWNED); for (;;) { /* drain Tx status FIFO (maxsize = 16) */ run_read(sc, RT2860_TX_STAT_FIFO, &stat); DPRINTFN(4, "tx stat 0x%08x\n", stat); if (!(stat & RT2860_TXQ_VLD)) break; wcid = (stat >> RT2860_TXQ_WCID_SHIFT) & 0xff; /* if no ACK was requested, no feedback is available */ if (!(stat & RT2860_TXQ_ACKREQ) || wcid > RT2870_WCID_MAX || wcid == 0) continue; /* * Even though each stat is Tx-complete-status like format, * the device can poll stats. Because there is no guarantee * that the referring node is still around when read the stats. * So that, if we use ieee80211_ratectl_tx_update(), we will * have hard time not to refer already freed node. * * To eliminate such page faults, we poll stats in softc. * Then, update the rates later with ieee80211_ratectl_tx_update(). */ wstat = &(sc->wcid_stats[wcid]); (*wstat)[RUN_TXCNT]++; if (stat & RT2860_TXQ_OK) (*wstat)[RUN_SUCCESS]++; else if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); /* * Check if there were retries, ie if the Tx success rate is * different from the requested rate. Note that it works only * because we do not allow rate fallback from OFDM to CCK. */ mcs = (stat >> RT2860_TXQ_MCS_SHIFT) & 0x7f; pid = (stat >> RT2860_TXQ_PID_SHIFT) & 0xf; if ((retry = pid -1 - mcs) > 0) { (*wstat)[RUN_TXCNT] += retry; (*wstat)[RUN_RETRY] += retry; } } DPRINTFN(3, "count=%d\n", sc->fifo_cnt); sc->fifo_cnt = 0; } static void run_iter_func(void *arg, struct ieee80211_node *ni) { struct run_softc *sc = arg; struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = ni->ni_ic; struct ifnet *ifp = ic->ic_ifp; struct run_node *rn = (void *)ni; union run_stats sta[2]; uint16_t (*wstat)[3]; int txcnt, success, retrycnt, error; RUN_LOCK(sc); /* Check for special case */ if (sc->rvp_cnt <= 1 && vap->iv_opmode == IEEE80211_M_STA && ni != vap->iv_bss) goto fail; if (sc->rvp_cnt <= 1 && (vap->iv_opmode == IEEE80211_M_IBSS || vap->iv_opmode == IEEE80211_M_STA)) { /* read statistic counters (clear on read) and update AMRR state */ error = run_read_region_1(sc, RT2860_TX_STA_CNT0, (uint8_t *)sta, sizeof sta); if (error != 0) goto fail; /* count failed TX as errors */ if_inc_counter(ifp, IFCOUNTER_OERRORS, le16toh(sta[0].error.fail)); retrycnt = le16toh(sta[1].tx.retry); success = le16toh(sta[1].tx.success); txcnt = retrycnt + success + le16toh(sta[0].error.fail); DPRINTFN(3, "retrycnt=%d success=%d failcnt=%d\n", retrycnt, success, le16toh(sta[0].error.fail)); } else { wstat = &(sc->wcid_stats[RUN_AID2WCID(ni->ni_associd)]); if (wstat == &(sc->wcid_stats[0]) || wstat > &(sc->wcid_stats[RT2870_WCID_MAX])) goto fail; txcnt = (*wstat)[RUN_TXCNT]; success = (*wstat)[RUN_SUCCESS]; retrycnt = (*wstat)[RUN_RETRY]; DPRINTFN(3, "retrycnt=%d txcnt=%d success=%d\n", retrycnt, txcnt, success); memset(wstat, 0, sizeof(*wstat)); } ieee80211_ratectl_tx_update(vap, ni, &txcnt, &success, &retrycnt); rn->amrr_ridx = ieee80211_ratectl_rate(ni, NULL, 0); fail: RUN_UNLOCK(sc); DPRINTFN(3, "ridx=%d\n", rn->amrr_ridx); } static void run_newassoc_cb(void *arg) { struct run_cmdq *cmdq = arg; struct ieee80211_node *ni = cmdq->arg1; struct run_softc *sc = ni->ni_vap->iv_ic->ic_ifp->if_softc; uint8_t wcid = cmdq->wcid; RUN_LOCK_ASSERT(sc, MA_OWNED); run_write_region_1(sc, RT2860_WCID_ENTRY(wcid), ni->ni_macaddr, IEEE80211_ADDR_LEN); memset(&(sc->wcid_stats[wcid]), 0, sizeof(sc->wcid_stats[wcid])); } static void run_newassoc(struct ieee80211_node *ni, int isnew) { struct run_node *rn = (void *)ni; struct ieee80211_rateset *rs = &ni->ni_rates; struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = vap->iv_ic; struct run_softc *sc = ic->ic_ifp->if_softc; uint8_t rate; uint8_t ridx; uint8_t wcid; int i, j; wcid = (vap->iv_opmode == IEEE80211_M_STA) ? 1 : RUN_AID2WCID(ni->ni_associd); if (wcid > RT2870_WCID_MAX) { device_printf(sc->sc_dev, "wcid=%d out of range\n", wcid); return; } /* only interested in true associations */ if (isnew && ni->ni_associd != 0) { /* * This function could is called though timeout function. * Need to defer. */ uint32_t cnt = RUN_CMDQ_GET(&sc->cmdq_store); DPRINTF("cmdq_store=%d\n", cnt); sc->cmdq[cnt].func = run_newassoc_cb; sc->cmdq[cnt].arg0 = NULL; sc->cmdq[cnt].arg1 = ni; sc->cmdq[cnt].wcid = wcid; ieee80211_runtask(ic, &sc->cmdq_task); } DPRINTF("new assoc isnew=%d associd=%x addr=%s\n", isnew, ni->ni_associd, ether_sprintf(ni->ni_macaddr)); for (i = 0; i < rs->rs_nrates; i++) { rate = rs->rs_rates[i] & IEEE80211_RATE_VAL; /* convert 802.11 rate to hardware rate index */ for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++) if (rt2860_rates[ridx].rate == rate) break; rn->ridx[i] = ridx; /* determine rate of control response frames */ for (j = i; j >= 0; j--) { if ((rs->rs_rates[j] & IEEE80211_RATE_BASIC) && rt2860_rates[rn->ridx[i]].phy == rt2860_rates[rn->ridx[j]].phy) break; } if (j >= 0) { rn->ctl_ridx[i] = rn->ridx[j]; } else { /* no basic rate found, use mandatory one */ rn->ctl_ridx[i] = rt2860_rates[ridx].ctl_ridx; } DPRINTF("rate=0x%02x ridx=%d ctl_ridx=%d\n", rs->rs_rates[i], rn->ridx[i], rn->ctl_ridx[i]); } rate = vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)].mgmtrate; for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++) if (rt2860_rates[ridx].rate == rate) break; rn->mgt_ridx = ridx; DPRINTF("rate=%d, mgmt_ridx=%d\n", rate, rn->mgt_ridx); RUN_LOCK(sc); if(sc->ratectl_run != RUN_RATECTL_OFF) usb_callout_reset(&sc->ratectl_ch, hz, run_ratectl_to, sc); RUN_UNLOCK(sc); } /* * Return the Rx chain with the highest RSSI for a given frame. */ static __inline uint8_t run_maxrssi_chain(struct run_softc *sc, const struct rt2860_rxwi *rxwi) { uint8_t rxchain = 0; if (sc->nrxchains > 1) { if (rxwi->rssi[1] > rxwi->rssi[rxchain]) rxchain = 1; if (sc->nrxchains > 2) if (rxwi->rssi[2] > rxwi->rssi[rxchain]) rxchain = 2; } return (rxchain); } static void run_rx_frame(struct run_softc *sc, struct mbuf *m, uint32_t dmalen) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211_frame *wh; struct ieee80211_node *ni; struct rt2870_rxd *rxd; struct rt2860_rxwi *rxwi; uint32_t flags; uint16_t len, rxwisize; uint8_t ant, rssi; int8_t nf; rxwi = mtod(m, struct rt2860_rxwi *); len = le16toh(rxwi->len) & 0xfff; rxwisize = sizeof(struct rt2860_rxwi); if (sc->mac_ver == 0x5592) rxwisize += sizeof(uint64_t); else if (sc->mac_ver == 0x3593) rxwisize += sizeof(uint32_t); if (__predict_false(len > dmalen)) { m_freem(m); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); DPRINTF("bad RXWI length %u > %u\n", len, dmalen); return; } /* Rx descriptor is located at the end */ rxd = (struct rt2870_rxd *)(mtod(m, caddr_t) + dmalen); flags = le32toh(rxd->flags); if (__predict_false(flags & (RT2860_RX_CRCERR | RT2860_RX_ICVERR))) { m_freem(m); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); DPRINTF("%s error.\n", (flags & RT2860_RX_CRCERR)?"CRC":"ICV"); return; } m->m_data += rxwisize; m->m_pkthdr.len = m->m_len -= rxwisize; wh = mtod(m, struct ieee80211_frame *); if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) { wh->i_fc[1] &= ~IEEE80211_FC1_PROTECTED; m->m_flags |= M_WEP; } if (flags & RT2860_RX_L2PAD) { DPRINTFN(8, "received RT2860_RX_L2PAD frame\n"); len += 2; } ni = ieee80211_find_rxnode(ic, mtod(m, struct ieee80211_frame_min *)); if (__predict_false(flags & RT2860_RX_MICERR)) { /* report MIC failures to net80211 for TKIP */ if (ni != NULL) ieee80211_notify_michael_failure(ni->ni_vap, wh, rxwi->keyidx); m_freem(m); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); DPRINTF("MIC error. Someone is lying.\n"); return; } ant = run_maxrssi_chain(sc, rxwi); rssi = rxwi->rssi[ant]; nf = run_rssi2dbm(sc, rssi, ant); m->m_pkthdr.rcvif = ifp; m->m_pkthdr.len = m->m_len = len; if (ni != NULL) { (void)ieee80211_input(ni, m, rssi, nf); ieee80211_free_node(ni); } else { (void)ieee80211_input_all(ic, m, rssi, nf); } if (__predict_false(ieee80211_radiotap_active(ic))) { struct run_rx_radiotap_header *tap = &sc->sc_rxtap; uint16_t phy; tap->wr_flags = 0; tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq); tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags); tap->wr_antsignal = rssi; tap->wr_antenna = ant; tap->wr_dbm_antsignal = run_rssi2dbm(sc, rssi, ant); tap->wr_rate = 2; /* in case it can't be found below */ phy = le16toh(rxwi->phy); switch (phy & RT2860_PHY_MODE) { case RT2860_PHY_CCK: switch ((phy & RT2860_PHY_MCS) & ~RT2860_PHY_SHPRE) { case 0: tap->wr_rate = 2; break; case 1: tap->wr_rate = 4; break; case 2: tap->wr_rate = 11; break; case 3: tap->wr_rate = 22; break; } if (phy & RT2860_PHY_SHPRE) tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE; break; case RT2860_PHY_OFDM: switch (phy & RT2860_PHY_MCS) { case 0: tap->wr_rate = 12; break; case 1: tap->wr_rate = 18; break; case 2: tap->wr_rate = 24; break; case 3: tap->wr_rate = 36; break; case 4: tap->wr_rate = 48; break; case 5: tap->wr_rate = 72; break; case 6: tap->wr_rate = 96; break; case 7: tap->wr_rate = 108; break; } break; } } } static void run_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error) { struct run_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct mbuf *m = NULL; struct mbuf *m0; uint32_t dmalen; uint16_t rxwisize; int xferlen; rxwisize = sizeof(struct rt2860_rxwi); if (sc->mac_ver == 0x5592) rxwisize += sizeof(uint64_t); else if (sc->mac_ver == 0x3593) rxwisize += sizeof(uint32_t); usbd_xfer_status(xfer, &xferlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(15, "rx done, actlen=%d\n", xferlen); if (xferlen < (int)(sizeof(uint32_t) + rxwisize + sizeof(struct rt2870_rxd))) { DPRINTF("xfer too short %d\n", xferlen); goto tr_setup; } m = sc->rx_m; sc->rx_m = NULL; /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: if (sc->rx_m == NULL) { sc->rx_m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE /* xfer can be bigger than MCLBYTES */); } if (sc->rx_m == NULL) { DPRINTF("could not allocate mbuf - idle with stall\n"); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); usbd_xfer_set_stall(xfer); usbd_xfer_set_frames(xfer, 0); } else { /* * Directly loading a mbuf cluster into DMA to * save some data copying. This works because * there is only one cluster. */ usbd_xfer_set_frame_data(xfer, 0, mtod(sc->rx_m, caddr_t), RUN_MAX_RXSZ); usbd_xfer_set_frames(xfer, 1); } usbd_transfer_submit(xfer); break; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); if (error == USB_ERR_TIMEOUT) device_printf(sc->sc_dev, "device timeout\n"); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } if (sc->rx_m != NULL) { m_freem(sc->rx_m); sc->rx_m = NULL; } break; } if (m == NULL) return; /* inputting all the frames must be last */ RUN_UNLOCK(sc); m->m_pkthdr.len = m->m_len = xferlen; /* HW can aggregate multiple 802.11 frames in a single USB xfer */ for(;;) { dmalen = le32toh(*mtod(m, uint32_t *)) & 0xffff; if ((dmalen >= (uint32_t)-8) || (dmalen == 0) || ((dmalen & 3) != 0)) { DPRINTF("bad DMA length %u\n", dmalen); break; } if ((dmalen + 8) > (uint32_t)xferlen) { DPRINTF("bad DMA length %u > %d\n", dmalen + 8, xferlen); break; } /* If it is the last one or a single frame, we won't copy. */ if ((xferlen -= dmalen + 8) <= 8) { /* trim 32-bit DMA-len header */ m->m_data += 4; m->m_pkthdr.len = m->m_len -= 4; run_rx_frame(sc, m, dmalen); m = NULL; /* don't free source buffer */ break; } /* copy aggregated frames to another mbuf */ m0 = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); if (__predict_false(m0 == NULL)) { DPRINTF("could not allocate mbuf\n"); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); break; } m_copydata(m, 4 /* skip 32-bit DMA-len header */, dmalen + sizeof(struct rt2870_rxd), mtod(m0, caddr_t)); m0->m_pkthdr.len = m0->m_len = dmalen + sizeof(struct rt2870_rxd); run_rx_frame(sc, m0, dmalen); /* update data ptr */ m->m_data += dmalen + 8; m->m_pkthdr.len = m->m_len -= dmalen + 8; } /* make sure we free the source buffer, if any */ m_freem(m); RUN_LOCK(sc); } static void run_tx_free(struct run_endpoint_queue *pq, struct run_tx_data *data, int txerr) { if (data->m != NULL) { if (data->m->m_flags & M_TXCB) ieee80211_process_callback(data->ni, data->m, txerr ? ETIMEDOUT : 0); m_freem(data->m); data->m = NULL; if (data->ni == NULL) { DPRINTF("no node\n"); } else { ieee80211_free_node(data->ni); data->ni = NULL; } } STAILQ_INSERT_TAIL(&pq->tx_fh, data, next); pq->tx_nfree++; } static void run_bulk_tx_callbackN(struct usb_xfer *xfer, usb_error_t error, u_int index) { struct run_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct run_tx_data *data; struct ieee80211vap *vap = NULL; struct usb_page_cache *pc; struct run_endpoint_queue *pq = &sc->sc_epq[index]; struct mbuf *m; usb_frlength_t size; int actlen; int sumlen; usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(11, "transfer complete: %d " "bytes @ index %d\n", actlen, index); data = usbd_xfer_get_priv(xfer); run_tx_free(pq, data, 0); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; usbd_xfer_set_priv(xfer, NULL); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: data = STAILQ_FIRST(&pq->tx_qh); if (data == NULL) break; STAILQ_REMOVE_HEAD(&pq->tx_qh, next); m = data->m; size = (sc->mac_ver == 0x5592) ? sizeof(data->desc) + sizeof(uint32_t) : sizeof(data->desc); if ((m->m_pkthdr.len + size + 3 + 8) > RUN_MAX_TXSZ) { DPRINTF("data overflow, %u bytes\n", m->m_pkthdr.len); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); run_tx_free(pq, data, 1); goto tr_setup; } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, &data->desc, size); usbd_m_copy_in(pc, size, m, 0, m->m_pkthdr.len); size += m->m_pkthdr.len; /* * Align end on a 4-byte boundary, pad 8 bytes (CRC + * 4-byte padding), and be sure to zero those trailing * bytes: */ usbd_frame_zero(pc, size, ((-size) & 3) + 8); size += ((-size) & 3) + 8; vap = data->ni->ni_vap; if (ieee80211_radiotap_active_vap(vap)) { struct run_tx_radiotap_header *tap = &sc->sc_txtap; struct rt2860_txwi *txwi = (struct rt2860_txwi *)(&data->desc + sizeof(struct rt2870_txd)); tap->wt_flags = 0; tap->wt_rate = rt2860_rates[data->ridx].rate; tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq); tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags); tap->wt_hwqueue = index; if (le16toh(txwi->phy) & RT2860_PHY_SHPRE) tap->wt_flags |= IEEE80211_RADIOTAP_F_SHORTPRE; ieee80211_radiotap_tx(vap, m); } DPRINTFN(11, "sending frame len=%u/%u @ index %d\n", m->m_pkthdr.len, size, index); usbd_xfer_set_frame_len(xfer, 0, size); usbd_xfer_set_priv(xfer, data); usbd_transfer_submit(xfer); RUN_UNLOCK(sc); run_start(ifp); RUN_LOCK(sc); break; default: DPRINTF("USB transfer error, %s\n", usbd_errstr(error)); data = usbd_xfer_get_priv(xfer); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); if (data != NULL) { if(data->ni != NULL) vap = data->ni->ni_vap; run_tx_free(pq, data, error); usbd_xfer_set_priv(xfer, NULL); } if (vap == NULL) vap = TAILQ_FIRST(&ic->ic_vaps); if (error != USB_ERR_CANCELLED) { if (error == USB_ERR_TIMEOUT) { device_printf(sc->sc_dev, "device timeout\n"); uint32_t i = RUN_CMDQ_GET(&sc->cmdq_store); DPRINTF("cmdq_store=%d\n", i); sc->cmdq[i].func = run_usb_timeout_cb; sc->cmdq[i].arg0 = vap; ieee80211_runtask(ic, &sc->cmdq_task); } /* * Try to clear stall first, also if other * errors occur, hence clearing stall * introduces a 50 ms delay: */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void run_bulk_tx_callback0(struct usb_xfer *xfer, usb_error_t error) { run_bulk_tx_callbackN(xfer, error, 0); } static void run_bulk_tx_callback1(struct usb_xfer *xfer, usb_error_t error) { run_bulk_tx_callbackN(xfer, error, 1); } static void run_bulk_tx_callback2(struct usb_xfer *xfer, usb_error_t error) { run_bulk_tx_callbackN(xfer, error, 2); } static void run_bulk_tx_callback3(struct usb_xfer *xfer, usb_error_t error) { run_bulk_tx_callbackN(xfer, error, 3); } static void run_bulk_tx_callback4(struct usb_xfer *xfer, usb_error_t error) { run_bulk_tx_callbackN(xfer, error, 4); } static void run_bulk_tx_callback5(struct usb_xfer *xfer, usb_error_t error) { run_bulk_tx_callbackN(xfer, error, 5); } static void run_set_tx_desc(struct run_softc *sc, struct run_tx_data *data) { struct mbuf *m = data->m; struct ieee80211com *ic = sc->sc_ifp->if_l2com; struct ieee80211vap *vap = data->ni->ni_vap; struct ieee80211_frame *wh; struct rt2870_txd *txd; struct rt2860_txwi *txwi; uint16_t xferlen, txwisize; uint16_t mcs; uint8_t ridx = data->ridx; uint8_t pad; /* get MCS code from rate index */ mcs = rt2860_rates[ridx].mcs; txwisize = (sc->mac_ver == 0x5592) ? sizeof(*txwi) + sizeof(uint32_t) : sizeof(*txwi); xferlen = txwisize + m->m_pkthdr.len; /* roundup to 32-bit alignment */ xferlen = (xferlen + 3) & ~3; txd = (struct rt2870_txd *)&data->desc; txd->len = htole16(xferlen); wh = mtod(m, struct ieee80211_frame *); /* * Ether both are true or both are false, the header * are nicely aligned to 32-bit. So, no L2 padding. */ if(IEEE80211_HAS_ADDR4(wh) == IEEE80211_QOS_HAS_SEQ(wh)) pad = 0; else pad = 2; /* setup TX Wireless Information */ txwi = (struct rt2860_txwi *)(txd + 1); txwi->len = htole16(m->m_pkthdr.len - pad); if (rt2860_rates[ridx].phy == IEEE80211_T_DS) { mcs |= RT2860_PHY_CCK; if (ridx != RT2860_RIDX_CCK1 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE)) mcs |= RT2860_PHY_SHPRE; } else mcs |= RT2860_PHY_OFDM; txwi->phy = htole16(mcs); /* check if RTS/CTS or CTS-to-self protection is required */ if (!IEEE80211_IS_MULTICAST(wh->i_addr1) && (m->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold || ((ic->ic_flags & IEEE80211_F_USEPROT) && rt2860_rates[ridx].phy == IEEE80211_T_OFDM))) txwi->txop |= RT2860_TX_TXOP_HT; else txwi->txop |= RT2860_TX_TXOP_BACKOFF; if (vap->iv_opmode != IEEE80211_M_STA && !IEEE80211_QOS_HAS_SEQ(wh)) txwi->xflags |= RT2860_TX_NSEQ; } /* This function must be called locked */ static int run_tx(struct run_softc *sc, struct mbuf *m, struct ieee80211_node *ni) { struct ieee80211com *ic = sc->sc_ifp->if_l2com; struct ieee80211vap *vap = ni->ni_vap; struct ieee80211_frame *wh; struct ieee80211_channel *chan; const struct ieee80211_txparam *tp; struct run_node *rn = (void *)ni; struct run_tx_data *data; struct rt2870_txd *txd; struct rt2860_txwi *txwi; uint16_t qos; uint16_t dur; uint16_t qid; uint8_t type; uint8_t tid; uint8_t ridx; uint8_t ctl_ridx; uint8_t qflags; uint8_t xflags = 0; int hasqos; RUN_LOCK_ASSERT(sc, MA_OWNED); wh = mtod(m, struct ieee80211_frame *); type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK; /* * There are 7 bulk endpoints: 1 for RX * and 6 for TX (4 EDCAs + HCCA + Prio). * Update 03-14-2009: some devices like the Planex GW-US300MiniS * seem to have only 4 TX bulk endpoints (Fukaumi Naoki). */ if ((hasqos = IEEE80211_QOS_HAS_SEQ(wh))) { uint8_t *frm; if(IEEE80211_HAS_ADDR4(wh)) frm = ((struct ieee80211_qosframe_addr4 *)wh)->i_qos; else frm =((struct ieee80211_qosframe *)wh)->i_qos; qos = le16toh(*(const uint16_t *)frm); tid = qos & IEEE80211_QOS_TID; qid = TID_TO_WME_AC(tid); } else { qos = 0; tid = 0; qid = WME_AC_BE; } qflags = (qid < 4) ? RT2860_TX_QSEL_EDCA : RT2860_TX_QSEL_HCCA; DPRINTFN(8, "qos %d\tqid %d\ttid %d\tqflags %x\n", qos, qid, tid, qflags); chan = (ni->ni_chan != IEEE80211_CHAN_ANYC)?ni->ni_chan:ic->ic_curchan; tp = &vap->iv_txparms[ieee80211_chan2mode(chan)]; /* pickup a rate index */ if (IEEE80211_IS_MULTICAST(wh->i_addr1) || type != IEEE80211_FC0_TYPE_DATA || m->m_flags & M_EAPOL) { ridx = (ic->ic_curmode == IEEE80211_MODE_11A) ? RT2860_RIDX_OFDM6 : RT2860_RIDX_CCK1; ctl_ridx = rt2860_rates[ridx].ctl_ridx; } else { if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) ridx = rn->fix_ridx; else ridx = rn->amrr_ridx; ctl_ridx = rt2860_rates[ridx].ctl_ridx; } if (!IEEE80211_IS_MULTICAST(wh->i_addr1) && (!hasqos || (qos & IEEE80211_QOS_ACKPOLICY) != IEEE80211_QOS_ACKPOLICY_NOACK)) { xflags |= RT2860_TX_ACK; if (ic->ic_flags & IEEE80211_F_SHPREAMBLE) dur = rt2860_rates[ctl_ridx].sp_ack_dur; else dur = rt2860_rates[ctl_ridx].lp_ack_dur; USETW(wh->i_dur, dur); } /* reserve slots for mgmt packets, just in case */ if (sc->sc_epq[qid].tx_nfree < 3) { DPRINTFN(10, "tx ring %d is full\n", qid); return (-1); } data = STAILQ_FIRST(&sc->sc_epq[qid].tx_fh); STAILQ_REMOVE_HEAD(&sc->sc_epq[qid].tx_fh, next); sc->sc_epq[qid].tx_nfree--; txd = (struct rt2870_txd *)&data->desc; txd->flags = qflags; txwi = (struct rt2860_txwi *)(txd + 1); txwi->xflags = xflags; if (IEEE80211_IS_MULTICAST(wh->i_addr1)) txwi->wcid = 0; else txwi->wcid = (vap->iv_opmode == IEEE80211_M_STA) ? 1 : RUN_AID2WCID(ni->ni_associd); /* clear leftover garbage bits */ txwi->flags = 0; txwi->txop = 0; data->m = m; data->ni = ni; data->ridx = ridx; run_set_tx_desc(sc, data); /* * The chip keeps track of 2 kind of Tx stats, * * TX_STAT_FIFO, for per WCID stats, and * * TX_STA_CNT0 for all-TX-in-one stats. * * To use FIFO stats, we need to store MCS into the driver-private * PacketID field. So that, we can tell whose stats when we read them. * We add 1 to the MCS because setting the PacketID field to 0 means * that we don't want feedback in TX_STAT_FIFO. * And, that's what we want for STA mode, since TX_STA_CNT0 does the job. * * FIFO stats doesn't count Tx with WCID 0xff, so we do this in run_tx(). */ if (sc->rvp_cnt > 1 || vap->iv_opmode == IEEE80211_M_HOSTAP || vap->iv_opmode == IEEE80211_M_MBSS) { uint16_t pid = (rt2860_rates[ridx].mcs + 1) & 0xf; txwi->len |= htole16(pid << RT2860_TX_PID_SHIFT); /* * Unlike PCI based devices, we don't get any interrupt from * USB devices, so we simulate FIFO-is-full interrupt here. * Ralink recomends to drain FIFO stats every 100 ms, but 16 slots * quickly get fulled. To prevent overflow, increment a counter on * every FIFO stat request, so we know how many slots are left. * We do this only in HOSTAP or multiple vap mode since FIFO stats * are used only in those modes. * We just drain stats. AMRR gets updated every 1 sec by * run_ratectl_cb() via callout. * Call it early. Otherwise overflow. */ if (sc->fifo_cnt++ == 10) { /* * With multiple vaps or if_bridge, if_start() is called * with a non-sleepable lock, tcpinp. So, need to defer. */ uint32_t i = RUN_CMDQ_GET(&sc->cmdq_store); DPRINTFN(6, "cmdq_store=%d\n", i); sc->cmdq[i].func = run_drain_fifo; sc->cmdq[i].arg0 = sc; ieee80211_runtask(ic, &sc->cmdq_task); } } STAILQ_INSERT_TAIL(&sc->sc_epq[qid].tx_qh, data, next); usbd_transfer_start(sc->sc_xfer[qid]); DPRINTFN(8, "sending data frame len=%d rate=%d qid=%d\n", m->m_pkthdr.len + (int)(sizeof(struct rt2870_txd) + sizeof(struct rt2860_txwi)), rt2860_rates[ridx].rate, qid); return (0); } static int run_tx_mgt(struct run_softc *sc, struct mbuf *m, struct ieee80211_node *ni) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct run_node *rn = (void *)ni; struct run_tx_data *data; struct ieee80211_frame *wh; struct rt2870_txd *txd; struct rt2860_txwi *txwi; uint16_t dur; uint8_t ridx = rn->mgt_ridx; uint8_t type; uint8_t xflags = 0; uint8_t wflags = 0; RUN_LOCK_ASSERT(sc, MA_OWNED); wh = mtod(m, struct ieee80211_frame *); type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK; /* tell hardware to add timestamp for probe responses */ if ((wh->i_fc[0] & (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) == (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP)) wflags |= RT2860_TX_TS; else if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) { xflags |= RT2860_TX_ACK; dur = ieee80211_ack_duration(ic->ic_rt, rt2860_rates[ridx].rate, ic->ic_flags & IEEE80211_F_SHPREAMBLE); USETW(wh->i_dur, dur); } if (sc->sc_epq[0].tx_nfree == 0) { /* let caller free mbuf */ ifp->if_drv_flags |= IFF_DRV_OACTIVE; return (EIO); } data = STAILQ_FIRST(&sc->sc_epq[0].tx_fh); STAILQ_REMOVE_HEAD(&sc->sc_epq[0].tx_fh, next); sc->sc_epq[0].tx_nfree--; txd = (struct rt2870_txd *)&data->desc; txd->flags = RT2860_TX_QSEL_EDCA; txwi = (struct rt2860_txwi *)(txd + 1); txwi->wcid = 0xff; txwi->flags = wflags; txwi->xflags = xflags; txwi->txop = 0; /* clear leftover garbage bits */ data->m = m; data->ni = ni; data->ridx = ridx; run_set_tx_desc(sc, data); DPRINTFN(10, "sending mgt frame len=%d rate=%d\n", m->m_pkthdr.len + (int)(sizeof(struct rt2870_txd) + sizeof(struct rt2860_txwi)), rt2860_rates[ridx].rate); STAILQ_INSERT_TAIL(&sc->sc_epq[0].tx_qh, data, next); usbd_transfer_start(sc->sc_xfer[0]); return (0); } static int run_sendprot(struct run_softc *sc, const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate) { struct ieee80211com *ic = ni->ni_ic; struct ieee80211_frame *wh; struct run_tx_data *data; struct rt2870_txd *txd; struct rt2860_txwi *txwi; struct mbuf *mprot; int ridx; int protrate; int ackrate; int pktlen; int isshort; uint16_t dur; uint8_t type; uint8_t wflags = 0; uint8_t xflags = 0; RUN_LOCK_ASSERT(sc, MA_OWNED); KASSERT(prot == IEEE80211_PROT_RTSCTS || prot == IEEE80211_PROT_CTSONLY, ("protection %d", prot)); wh = mtod(m, struct ieee80211_frame *); pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN; type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK; protrate = ieee80211_ctl_rate(ic->ic_rt, rate); ackrate = ieee80211_ack_rate(ic->ic_rt, rate); isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0; dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort) + ieee80211_ack_duration(ic->ic_rt, rate, isshort); wflags = RT2860_TX_FRAG; /* check that there are free slots before allocating the mbuf */ if (sc->sc_epq[0].tx_nfree == 0) { /* let caller free mbuf */ sc->sc_ifp->if_drv_flags |= IFF_DRV_OACTIVE; return (ENOBUFS); } if (prot == IEEE80211_PROT_RTSCTS) { /* NB: CTS is the same size as an ACK */ dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort); xflags |= RT2860_TX_ACK; mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur); } else { mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur); } if (mprot == NULL) { if_inc_counter(sc->sc_ifp, IFCOUNTER_OERRORS, 1); DPRINTF("could not allocate mbuf\n"); return (ENOBUFS); } data = STAILQ_FIRST(&sc->sc_epq[0].tx_fh); STAILQ_REMOVE_HEAD(&sc->sc_epq[0].tx_fh, next); sc->sc_epq[0].tx_nfree--; txd = (struct rt2870_txd *)&data->desc; txd->flags = RT2860_TX_QSEL_EDCA; txwi = (struct rt2860_txwi *)(txd + 1); txwi->wcid = 0xff; txwi->flags = wflags; txwi->xflags = xflags; txwi->txop = 0; /* clear leftover garbage bits */ data->m = mprot; data->ni = ieee80211_ref_node(ni); for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++) if (rt2860_rates[ridx].rate == protrate) break; data->ridx = ridx; run_set_tx_desc(sc, data); DPRINTFN(1, "sending prot len=%u rate=%u\n", m->m_pkthdr.len, rate); STAILQ_INSERT_TAIL(&sc->sc_epq[0].tx_qh, data, next); usbd_transfer_start(sc->sc_xfer[0]); return (0); } static int run_tx_param(struct run_softc *sc, struct mbuf *m, struct ieee80211_node *ni, const struct ieee80211_bpf_params *params) { struct ieee80211com *ic = ni->ni_ic; struct ieee80211_frame *wh; struct run_tx_data *data; struct rt2870_txd *txd; struct rt2860_txwi *txwi; uint8_t type; uint8_t ridx; uint8_t rate; uint8_t opflags = 0; uint8_t xflags = 0; int error; RUN_LOCK_ASSERT(sc, MA_OWNED); KASSERT(params != NULL, ("no raw xmit params")); wh = mtod(m, struct ieee80211_frame *); type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK; rate = params->ibp_rate0; if (!ieee80211_isratevalid(ic->ic_rt, rate)) { /* let caller free mbuf */ return (EINVAL); } if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0) xflags |= RT2860_TX_ACK; if (params->ibp_flags & (IEEE80211_BPF_RTS|IEEE80211_BPF_CTS)) { error = run_sendprot(sc, m, ni, params->ibp_flags & IEEE80211_BPF_RTS ? IEEE80211_PROT_RTSCTS : IEEE80211_PROT_CTSONLY, rate); if (error) { /* let caller free mbuf */ return error; } opflags |= /*XXX RT2573_TX_LONG_RETRY |*/ RT2860_TX_TXOP_SIFS; } if (sc->sc_epq[0].tx_nfree == 0) { /* let caller free mbuf */ sc->sc_ifp->if_drv_flags |= IFF_DRV_OACTIVE; DPRINTF("sending raw frame, but tx ring is full\n"); return (EIO); } data = STAILQ_FIRST(&sc->sc_epq[0].tx_fh); STAILQ_REMOVE_HEAD(&sc->sc_epq[0].tx_fh, next); sc->sc_epq[0].tx_nfree--; txd = (struct rt2870_txd *)&data->desc; txd->flags = RT2860_TX_QSEL_EDCA; txwi = (struct rt2860_txwi *)(txd + 1); txwi->wcid = 0xff; txwi->xflags = xflags; txwi->txop = opflags; txwi->flags = 0; /* clear leftover garbage bits */ data->m = m; data->ni = ni; for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++) if (rt2860_rates[ridx].rate == rate) break; data->ridx = ridx; run_set_tx_desc(sc, data); DPRINTFN(10, "sending raw frame len=%u rate=%u\n", m->m_pkthdr.len, rate); STAILQ_INSERT_TAIL(&sc->sc_epq[0].tx_qh, data, next); usbd_transfer_start(sc->sc_xfer[0]); return (0); } static int run_raw_xmit(struct ieee80211_node *ni, struct mbuf *m, const struct ieee80211_bpf_params *params) { struct ifnet *ifp = ni->ni_ic->ic_ifp; struct run_softc *sc = ifp->if_softc; int error = 0; RUN_LOCK(sc); /* prevent management frames from being sent if we're not ready */ if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) { error = ENETDOWN; goto done; } if (params == NULL) { /* tx mgt packet */ if ((error = run_tx_mgt(sc, m, ni)) != 0) { if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); DPRINTF("mgt tx failed\n"); goto done; } } else { /* tx raw packet with param */ if ((error = run_tx_param(sc, m, ni, params)) != 0) { if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); DPRINTF("tx with param failed\n"); goto done; } } if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); done: RUN_UNLOCK(sc); if (error != 0) { if(m != NULL) m_freem(m); ieee80211_free_node(ni); } return (error); } static void run_start(struct ifnet *ifp) { struct run_softc *sc = ifp->if_softc; struct ieee80211_node *ni; struct mbuf *m; RUN_LOCK(sc); if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) { RUN_UNLOCK(sc); return; } for (;;) { /* send data frames */ IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; ni = (struct ieee80211_node *)m->m_pkthdr.rcvif; if (run_tx(sc, m, ni) != 0) { IFQ_DRV_PREPEND(&ifp->if_snd, m); ifp->if_drv_flags |= IFF_DRV_OACTIVE; break; } } RUN_UNLOCK(sc); } static int run_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) { struct run_softc *sc = ifp->if_softc; struct ieee80211com *ic = sc->sc_ifp->if_l2com; struct ifreq *ifr = (struct ifreq *) data; int startall = 0; int error; RUN_LOCK(sc); error = sc->sc_detached ? ENXIO : 0; RUN_UNLOCK(sc); if (error) return (error); switch (cmd) { case SIOCSIFFLAGS: RUN_LOCK(sc); if (ifp->if_flags & IFF_UP) { if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)){ startall = 1; run_init_locked(sc); } else run_update_promisc_locked(ifp); } else { if (ifp->if_drv_flags & IFF_DRV_RUNNING && (ic->ic_nrunning == 0 || sc->rvp_cnt <= 1)) { run_stop(sc); } } RUN_UNLOCK(sc); if (startall) ieee80211_start_all(ic); break; case SIOCGIFMEDIA: error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd); break; case SIOCGIFADDR: error = ether_ioctl(ifp, cmd, data); break; default: error = EINVAL; break; } return (error); } static void run_iq_calib(struct run_softc *sc, u_int chan) { uint16_t val; /* Tx0 IQ gain. */ run_bbp_write(sc, 158, 0x2c); if (chan <= 14) run_efuse_read(sc, RT5390_EEPROM_IQ_GAIN_CAL_TX0_2GHZ, &val, 1); else if (chan <= 64) { run_efuse_read(sc, RT5390_EEPROM_IQ_GAIN_CAL_TX0_CH36_TO_CH64_5GHZ, &val, 1); } else if (chan <= 138) { run_efuse_read(sc, RT5390_EEPROM_IQ_GAIN_CAL_TX0_CH100_TO_CH138_5GHZ, &val, 1); } else if (chan <= 165) { run_efuse_read(sc, RT5390_EEPROM_IQ_GAIN_CAL_TX0_CH140_TO_CH165_5GHZ, &val, 1); } else val = 0; run_bbp_write(sc, 159, val); /* Tx0 IQ phase. */ run_bbp_write(sc, 158, 0x2d); if (chan <= 14) { run_efuse_read(sc, RT5390_EEPROM_IQ_PHASE_CAL_TX0_2GHZ, &val, 1); } else if (chan <= 64) { run_efuse_read(sc, RT5390_EEPROM_IQ_PHASE_CAL_TX0_CH36_TO_CH64_5GHZ, &val, 1); } else if (chan <= 138) { run_efuse_read(sc, RT5390_EEPROM_IQ_PHASE_CAL_TX0_CH100_TO_CH138_5GHZ, &val, 1); } else if (chan <= 165) { run_efuse_read(sc, RT5390_EEPROM_IQ_PHASE_CAL_TX0_CH140_TO_CH165_5GHZ, &val, 1); } else val = 0; run_bbp_write(sc, 159, val); /* Tx1 IQ gain. */ run_bbp_write(sc, 158, 0x4a); if (chan <= 14) { run_efuse_read(sc, RT5390_EEPROM_IQ_GAIN_CAL_TX1_2GHZ, &val, 1); } else if (chan <= 64) { run_efuse_read(sc, RT5390_EEPROM_IQ_GAIN_CAL_TX1_CH36_TO_CH64_5GHZ, &val, 1); } else if (chan <= 138) { run_efuse_read(sc, RT5390_EEPROM_IQ_GAIN_CAL_TX1_CH100_TO_CH138_5GHZ, &val, 1); } else if (chan <= 165) { run_efuse_read(sc, RT5390_EEPROM_IQ_GAIN_CAL_TX1_CH140_TO_CH165_5GHZ, &val, 1); } else val = 0; run_bbp_write(sc, 159, val); /* Tx1 IQ phase. */ run_bbp_write(sc, 158, 0x4b); if (chan <= 14) { run_efuse_read(sc, RT5390_EEPROM_IQ_PHASE_CAL_TX1_2GHZ, &val, 1); } else if (chan <= 64) { run_efuse_read(sc, RT5390_EEPROM_IQ_PHASE_CAL_TX1_CH36_TO_CH64_5GHZ, &val, 1); } else if (chan <= 138) { run_efuse_read(sc, RT5390_EEPROM_IQ_PHASE_CAL_TX1_CH100_TO_CH138_5GHZ, &val, 1); } else if (chan <= 165) { run_efuse_read(sc, RT5390_EEPROM_IQ_PHASE_CAL_TX1_CH140_TO_CH165_5GHZ, &val, 1); } else val = 0; run_bbp_write(sc, 159, val); /* RF IQ compensation control. */ run_bbp_write(sc, 158, 0x04); run_efuse_read(sc, RT5390_EEPROM_RF_IQ_COMPENSATION_CTL, &val, 1); run_bbp_write(sc, 159, val); /* RF IQ imbalance compensation control. */ run_bbp_write(sc, 158, 0x03); run_efuse_read(sc, RT5390_EEPROM_RF_IQ_IMBALANCE_COMPENSATION_CTL, &val, 1); run_bbp_write(sc, 159, val); } static void run_set_agc(struct run_softc *sc, uint8_t agc) { uint8_t bbp; if (sc->mac_ver == 0x3572) { run_bbp_read(sc, 27, &bbp); bbp &= ~(0x3 << 5); run_bbp_write(sc, 27, bbp | 0 << 5); /* select Rx0 */ run_bbp_write(sc, 66, agc); run_bbp_write(sc, 27, bbp | 1 << 5); /* select Rx1 */ run_bbp_write(sc, 66, agc); } else run_bbp_write(sc, 66, agc); } static void run_select_chan_group(struct run_softc *sc, int group) { uint32_t tmp; uint8_t agc; run_bbp_write(sc, 62, 0x37 - sc->lna[group]); run_bbp_write(sc, 63, 0x37 - sc->lna[group]); run_bbp_write(sc, 64, 0x37 - sc->lna[group]); if (sc->mac_ver < 0x3572) run_bbp_write(sc, 86, 0x00); if (sc->mac_ver == 0x3593) { run_bbp_write(sc, 77, 0x98); run_bbp_write(sc, 83, (group == 0) ? 0x8a : 0x9a); } if (group == 0) { if (sc->ext_2ghz_lna) { if (sc->mac_ver >= 0x5390) run_bbp_write(sc, 75, 0x52); else { run_bbp_write(sc, 82, 0x62); run_bbp_write(sc, 75, 0x46); } } else { if (sc->mac_ver == 0x5592) { run_bbp_write(sc, 79, 0x1c); run_bbp_write(sc, 80, 0x0e); run_bbp_write(sc, 81, 0x3a); run_bbp_write(sc, 82, 0x62); run_bbp_write(sc, 195, 0x80); run_bbp_write(sc, 196, 0xe0); run_bbp_write(sc, 195, 0x81); run_bbp_write(sc, 196, 0x1f); run_bbp_write(sc, 195, 0x82); run_bbp_write(sc, 196, 0x38); run_bbp_write(sc, 195, 0x83); run_bbp_write(sc, 196, 0x32); run_bbp_write(sc, 195, 0x85); run_bbp_write(sc, 196, 0x28); run_bbp_write(sc, 195, 0x86); run_bbp_write(sc, 196, 0x19); } else if (sc->mac_ver >= 0x5390) run_bbp_write(sc, 75, 0x50); else { run_bbp_write(sc, 82, (sc->mac_ver == 0x3593) ? 0x62 : 0x84); run_bbp_write(sc, 75, 0x50); } } } else { if (sc->mac_ver == 0x5592) { run_bbp_write(sc, 79, 0x18); run_bbp_write(sc, 80, 0x08); run_bbp_write(sc, 81, 0x38); run_bbp_write(sc, 82, 0x92); run_bbp_write(sc, 195, 0x80); run_bbp_write(sc, 196, 0xf0); run_bbp_write(sc, 195, 0x81); run_bbp_write(sc, 196, 0x1e); run_bbp_write(sc, 195, 0x82); run_bbp_write(sc, 196, 0x28); run_bbp_write(sc, 195, 0x83); run_bbp_write(sc, 196, 0x20); run_bbp_write(sc, 195, 0x85); run_bbp_write(sc, 196, 0x7f); run_bbp_write(sc, 195, 0x86); run_bbp_write(sc, 196, 0x7f); } else if (sc->mac_ver == 0x3572) run_bbp_write(sc, 82, 0x94); else run_bbp_write(sc, 82, (sc->mac_ver == 0x3593) ? 0x82 : 0xf2); if (sc->ext_5ghz_lna) run_bbp_write(sc, 75, 0x46); else run_bbp_write(sc, 75, 0x50); } run_read(sc, RT2860_TX_BAND_CFG, &tmp); tmp &= ~(RT2860_5G_BAND_SEL_N | RT2860_5G_BAND_SEL_P); tmp |= (group == 0) ? RT2860_5G_BAND_SEL_N : RT2860_5G_BAND_SEL_P; run_write(sc, RT2860_TX_BAND_CFG, tmp); /* enable appropriate Power Amplifiers and Low Noise Amplifiers */ tmp = RT2860_RFTR_EN | RT2860_TRSW_EN | RT2860_LNA_PE0_EN; if (sc->mac_ver == 0x3593) tmp |= 1 << 29 | 1 << 28; if (sc->nrxchains > 1) tmp |= RT2860_LNA_PE1_EN; if (group == 0) { /* 2GHz */ tmp |= RT2860_PA_PE_G0_EN; if (sc->ntxchains > 1) tmp |= RT2860_PA_PE_G1_EN; if (sc->mac_ver == 0x3593) { if (sc->ntxchains > 2) tmp |= 1 << 25; } } else { /* 5GHz */ tmp |= RT2860_PA_PE_A0_EN; if (sc->ntxchains > 1) tmp |= RT2860_PA_PE_A1_EN; } if (sc->mac_ver == 0x3572) { run_rt3070_rf_write(sc, 8, 0x00); run_write(sc, RT2860_TX_PIN_CFG, tmp); run_rt3070_rf_write(sc, 8, 0x80); } else run_write(sc, RT2860_TX_PIN_CFG, tmp); if (sc->mac_ver == 0x5592) { run_bbp_write(sc, 195, 0x8d); run_bbp_write(sc, 196, 0x1a); } if (sc->mac_ver == 0x3593) { run_read(sc, RT2860_GPIO_CTRL, &tmp); tmp &= ~0x01010000; if (group == 0) tmp |= 0x00010000; tmp = (tmp & ~0x00009090) | 0x00000090; run_write(sc, RT2860_GPIO_CTRL, tmp); } /* set initial AGC value */ if (group == 0) { /* 2GHz band */ if (sc->mac_ver >= 0x3070) agc = 0x1c + sc->lna[0] * 2; else agc = 0x2e + sc->lna[0]; } else { /* 5GHz band */ if (sc->mac_ver == 0x5592) agc = 0x24 + sc->lna[group] * 2; else if (sc->mac_ver == 0x3572 || sc->mac_ver == 0x3593) agc = 0x22 + (sc->lna[group] * 5) / 3; else agc = 0x32 + (sc->lna[group] * 5) / 3; } run_set_agc(sc, agc); } static void run_rt2870_set_chan(struct run_softc *sc, u_int chan) { const struct rfprog *rfprog = rt2860_rf2850; uint32_t r2, r3, r4; int8_t txpow1, txpow2; int i; /* find the settings for this channel (we know it exists) */ for (i = 0; rfprog[i].chan != chan; i++); r2 = rfprog[i].r2; if (sc->ntxchains == 1) r2 |= 1 << 14; /* 1T: disable Tx chain 2 */ if (sc->nrxchains == 1) r2 |= 1 << 17 | 1 << 6; /* 1R: disable Rx chains 2 & 3 */ else if (sc->nrxchains == 2) r2 |= 1 << 6; /* 2R: disable Rx chain 3 */ /* use Tx power values from EEPROM */ txpow1 = sc->txpow1[i]; txpow2 = sc->txpow2[i]; /* Initialize RF R3 and R4. */ r3 = rfprog[i].r3 & 0xffffc1ff; r4 = (rfprog[i].r4 & ~(0x001f87c0)) | (sc->freq << 15); if (chan > 14) { if (txpow1 >= 0) { txpow1 = (txpow1 > 0xf) ? (0xf) : (txpow1); r3 |= (txpow1 << 10) | (1 << 9); } else { txpow1 += 7; /* txpow1 is not possible larger than 15. */ r3 |= (txpow1 << 10); } if (txpow2 >= 0) { txpow2 = (txpow2 > 0xf) ? (0xf) : (txpow2); r4 |= (txpow2 << 7) | (1 << 6); } else { txpow2 += 7; r4 |= (txpow2 << 7); } } else { /* Set Tx0 power. */ r3 |= (txpow1 << 9); /* Set frequency offset and Tx1 power. */ r4 |= (txpow2 << 6); } run_rt2870_rf_write(sc, rfprog[i].r1); run_rt2870_rf_write(sc, r2); run_rt2870_rf_write(sc, r3 & ~(1 << 2)); run_rt2870_rf_write(sc, r4); run_delay(sc, 10); run_rt2870_rf_write(sc, rfprog[i].r1); run_rt2870_rf_write(sc, r2); run_rt2870_rf_write(sc, r3 | (1 << 2)); run_rt2870_rf_write(sc, r4); run_delay(sc, 10); run_rt2870_rf_write(sc, rfprog[i].r1); run_rt2870_rf_write(sc, r2); run_rt2870_rf_write(sc, r3 & ~(1 << 2)); run_rt2870_rf_write(sc, r4); } static void run_rt3070_set_chan(struct run_softc *sc, u_int chan) { int8_t txpow1, txpow2; uint8_t rf; int i; /* find the settings for this channel (we know it exists) */ for (i = 0; rt2860_rf2850[i].chan != chan; i++); /* use Tx power values from EEPROM */ txpow1 = sc->txpow1[i]; txpow2 = sc->txpow2[i]; run_rt3070_rf_write(sc, 2, rt3070_freqs[i].n); /* RT3370/RT3390: RF R3 [7:4] is not reserved bits. */ run_rt3070_rf_read(sc, 3, &rf); rf = (rf & ~0x0f) | rt3070_freqs[i].k; run_rt3070_rf_write(sc, 3, rf); run_rt3070_rf_read(sc, 6, &rf); rf = (rf & ~0x03) | rt3070_freqs[i].r; run_rt3070_rf_write(sc, 6, rf); /* set Tx0 power */ run_rt3070_rf_read(sc, 12, &rf); rf = (rf & ~0x1f) | txpow1; run_rt3070_rf_write(sc, 12, rf); /* set Tx1 power */ run_rt3070_rf_read(sc, 13, &rf); rf = (rf & ~0x1f) | txpow2; run_rt3070_rf_write(sc, 13, rf); run_rt3070_rf_read(sc, 1, &rf); rf &= ~0xfc; if (sc->ntxchains == 1) rf |= 1 << 7 | 1 << 5; /* 1T: disable Tx chains 2 & 3 */ else if (sc->ntxchains == 2) rf |= 1 << 7; /* 2T: disable Tx chain 3 */ if (sc->nrxchains == 1) rf |= 1 << 6 | 1 << 4; /* 1R: disable Rx chains 2 & 3 */ else if (sc->nrxchains == 2) rf |= 1 << 6; /* 2R: disable Rx chain 3 */ run_rt3070_rf_write(sc, 1, rf); /* set RF offset */ run_rt3070_rf_read(sc, 23, &rf); rf = (rf & ~0x7f) | sc->freq; run_rt3070_rf_write(sc, 23, rf); /* program RF filter */ run_rt3070_rf_read(sc, 24, &rf); /* Tx */ rf = (rf & ~0x3f) | sc->rf24_20mhz; run_rt3070_rf_write(sc, 24, rf); run_rt3070_rf_read(sc, 31, &rf); /* Rx */ rf = (rf & ~0x3f) | sc->rf24_20mhz; run_rt3070_rf_write(sc, 31, rf); /* enable RF tuning */ run_rt3070_rf_read(sc, 7, &rf); run_rt3070_rf_write(sc, 7, rf | 0x01); } static void run_rt3572_set_chan(struct run_softc *sc, u_int chan) { int8_t txpow1, txpow2; uint32_t tmp; uint8_t rf; int i; /* find the settings for this channel (we know it exists) */ for (i = 0; rt2860_rf2850[i].chan != chan; i++); /* use Tx power values from EEPROM */ txpow1 = sc->txpow1[i]; txpow2 = sc->txpow2[i]; if (chan <= 14) { run_bbp_write(sc, 25, sc->bbp25); run_bbp_write(sc, 26, sc->bbp26); } else { /* enable IQ phase correction */ run_bbp_write(sc, 25, 0x09); run_bbp_write(sc, 26, 0xff); } run_rt3070_rf_write(sc, 2, rt3070_freqs[i].n); run_rt3070_rf_write(sc, 3, rt3070_freqs[i].k); run_rt3070_rf_read(sc, 6, &rf); rf = (rf & ~0x0f) | rt3070_freqs[i].r; rf |= (chan <= 14) ? 0x08 : 0x04; run_rt3070_rf_write(sc, 6, rf); /* set PLL mode */ run_rt3070_rf_read(sc, 5, &rf); rf &= ~(0x08 | 0x04); rf |= (chan <= 14) ? 0x04 : 0x08; run_rt3070_rf_write(sc, 5, rf); /* set Tx power for chain 0 */ if (chan <= 14) rf = 0x60 | txpow1; else rf = 0xe0 | (txpow1 & 0xc) << 1 | (txpow1 & 0x3); run_rt3070_rf_write(sc, 12, rf); /* set Tx power for chain 1 */ if (chan <= 14) rf = 0x60 | txpow2; else rf = 0xe0 | (txpow2 & 0xc) << 1 | (txpow2 & 0x3); run_rt3070_rf_write(sc, 13, rf); /* set Tx/Rx streams */ run_rt3070_rf_read(sc, 1, &rf); rf &= ~0xfc; if (sc->ntxchains == 1) rf |= 1 << 7 | 1 << 5; /* 1T: disable Tx chains 2 & 3 */ else if (sc->ntxchains == 2) rf |= 1 << 7; /* 2T: disable Tx chain 3 */ if (sc->nrxchains == 1) rf |= 1 << 6 | 1 << 4; /* 1R: disable Rx chains 2 & 3 */ else if (sc->nrxchains == 2) rf |= 1 << 6; /* 2R: disable Rx chain 3 */ run_rt3070_rf_write(sc, 1, rf); /* set RF offset */ run_rt3070_rf_read(sc, 23, &rf); rf = (rf & ~0x7f) | sc->freq; run_rt3070_rf_write(sc, 23, rf); /* program RF filter */ rf = sc->rf24_20mhz; run_rt3070_rf_write(sc, 24, rf); /* Tx */ run_rt3070_rf_write(sc, 31, rf); /* Rx */ /* enable RF tuning */ run_rt3070_rf_read(sc, 7, &rf); rf = (chan <= 14) ? 0xd8 : ((rf & ~0xc8) | 0x14); run_rt3070_rf_write(sc, 7, rf); /* TSSI */ rf = (chan <= 14) ? 0xc3 : 0xc0; run_rt3070_rf_write(sc, 9, rf); /* set loop filter 1 */ run_rt3070_rf_write(sc, 10, 0xf1); /* set loop filter 2 */ run_rt3070_rf_write(sc, 11, (chan <= 14) ? 0xb9 : 0x00); /* set tx_mx2_ic */ run_rt3070_rf_write(sc, 15, (chan <= 14) ? 0x53 : 0x43); /* set tx_mx1_ic */ if (chan <= 14) rf = 0x48 | sc->txmixgain_2ghz; else rf = 0x78 | sc->txmixgain_5ghz; run_rt3070_rf_write(sc, 16, rf); /* set tx_lo1 */ run_rt3070_rf_write(sc, 17, 0x23); /* set tx_lo2 */ if (chan <= 14) rf = 0x93; else if (chan <= 64) rf = 0xb7; else if (chan <= 128) rf = 0x74; else rf = 0x72; run_rt3070_rf_write(sc, 19, rf); /* set rx_lo1 */ if (chan <= 14) rf = 0xb3; else if (chan <= 64) rf = 0xf6; else if (chan <= 128) rf = 0xf4; else rf = 0xf3; run_rt3070_rf_write(sc, 20, rf); /* set pfd_delay */ if (chan <= 14) rf = 0x15; else if (chan <= 64) rf = 0x3d; else rf = 0x01; run_rt3070_rf_write(sc, 25, rf); /* set rx_lo2 */ run_rt3070_rf_write(sc, 26, (chan <= 14) ? 0x85 : 0x87); /* set ldo_rf_vc */ run_rt3070_rf_write(sc, 27, (chan <= 14) ? 0x00 : 0x01); /* set drv_cc */ run_rt3070_rf_write(sc, 29, (chan <= 14) ? 0x9b : 0x9f); run_read(sc, RT2860_GPIO_CTRL, &tmp); tmp &= ~0x8080; if (chan <= 14) tmp |= 0x80; run_write(sc, RT2860_GPIO_CTRL, tmp); /* enable RF tuning */ run_rt3070_rf_read(sc, 7, &rf); run_rt3070_rf_write(sc, 7, rf | 0x01); run_delay(sc, 2); } static void run_rt3593_set_chan(struct run_softc *sc, u_int chan) { int8_t txpow1, txpow2, txpow3; uint8_t h20mhz, rf; int i; /* find the settings for this channel (we know it exists) */ for (i = 0; rt2860_rf2850[i].chan != chan; i++); /* use Tx power values from EEPROM */ txpow1 = sc->txpow1[i]; txpow2 = sc->txpow2[i]; txpow3 = (sc->ntxchains == 3) ? sc->txpow3[i] : 0; if (chan <= 14) { run_bbp_write(sc, 25, sc->bbp25); run_bbp_write(sc, 26, sc->bbp26); } else { /* Enable IQ phase correction. */ run_bbp_write(sc, 25, 0x09); run_bbp_write(sc, 26, 0xff); } run_rt3070_rf_write(sc, 8, rt3070_freqs[i].n); run_rt3070_rf_write(sc, 9, rt3070_freqs[i].k & 0x0f); run_rt3070_rf_read(sc, 11, &rf); rf = (rf & ~0x03) | (rt3070_freqs[i].r & 0x03); run_rt3070_rf_write(sc, 11, rf); /* Set pll_idoh. */ run_rt3070_rf_read(sc, 11, &rf); rf &= ~0x4c; rf |= (chan <= 14) ? 0x44 : 0x48; run_rt3070_rf_write(sc, 11, rf); if (chan <= 14) rf = txpow1 & 0x1f; else rf = 0x40 | ((txpow1 & 0x18) << 1) | (txpow1 & 0x07); run_rt3070_rf_write(sc, 53, rf); if (chan <= 14) rf = txpow2 & 0x1f; else rf = 0x40 | ((txpow2 & 0x18) << 1) | (txpow2 & 0x07); run_rt3070_rf_write(sc, 55, rf); if (chan <= 14) rf = txpow3 & 0x1f; else rf = 0x40 | ((txpow3 & 0x18) << 1) | (txpow3 & 0x07); run_rt3070_rf_write(sc, 54, rf); rf = RT3070_RF_BLOCK | RT3070_PLL_PD; if (sc->ntxchains == 3) rf |= RT3070_TX0_PD | RT3070_TX1_PD | RT3070_TX2_PD; else rf |= RT3070_TX0_PD | RT3070_TX1_PD; rf |= RT3070_RX0_PD | RT3070_RX1_PD | RT3070_RX2_PD; run_rt3070_rf_write(sc, 1, rf); run_adjust_freq_offset(sc); run_rt3070_rf_write(sc, 31, (chan <= 14) ? 0xa0 : 0x80); h20mhz = (sc->rf24_20mhz & 0x20) >> 5; run_rt3070_rf_read(sc, 30, &rf); rf = (rf & ~0x06) | (h20mhz << 1) | (h20mhz << 2); run_rt3070_rf_write(sc, 30, rf); run_rt3070_rf_read(sc, 36, &rf); if (chan <= 14) rf |= 0x80; else rf &= ~0x80; run_rt3070_rf_write(sc, 36, rf); /* Set vcolo_bs. */ run_rt3070_rf_write(sc, 34, (chan <= 14) ? 0x3c : 0x20); /* Set pfd_delay. */ run_rt3070_rf_write(sc, 12, (chan <= 14) ? 0x1a : 0x12); /* Set vco bias current control. */ run_rt3070_rf_read(sc, 6, &rf); rf &= ~0xc0; if (chan <= 14) rf |= 0x40; else if (chan <= 128) rf |= 0x80; else rf |= 0x40; run_rt3070_rf_write(sc, 6, rf); run_rt3070_rf_read(sc, 30, &rf); rf = (rf & ~0x18) | 0x10; run_rt3070_rf_write(sc, 30, rf); run_rt3070_rf_write(sc, 10, (chan <= 14) ? 0xd3 : 0xd8); run_rt3070_rf_write(sc, 13, (chan <= 14) ? 0x12 : 0x23); run_rt3070_rf_read(sc, 51, &rf); rf = (rf & ~0x03) | 0x01; run_rt3070_rf_write(sc, 51, rf); /* Set tx_mx1_cc. */ run_rt3070_rf_read(sc, 51, &rf); rf &= ~0x1c; rf |= (chan <= 14) ? 0x14 : 0x10; run_rt3070_rf_write(sc, 51, rf); /* Set tx_mx1_ic. */ run_rt3070_rf_read(sc, 51, &rf); rf &= ~0xe0; rf |= (chan <= 14) ? 0x60 : 0x40; run_rt3070_rf_write(sc, 51, rf); /* Set tx_lo1_ic. */ run_rt3070_rf_read(sc, 49, &rf); rf &= ~0x1c; rf |= (chan <= 14) ? 0x0c : 0x08; run_rt3070_rf_write(sc, 49, rf); /* Set tx_lo1_en. */ run_rt3070_rf_read(sc, 50, &rf); run_rt3070_rf_write(sc, 50, rf & ~0x20); /* Set drv_cc. */ run_rt3070_rf_read(sc, 57, &rf); rf &= ~0xfc; rf |= (chan <= 14) ? 0x6c : 0x3c; run_rt3070_rf_write(sc, 57, rf); /* Set rx_mix1_ic, rxa_lnactr, lna_vc, lna_inbias_en and lna_en. */ run_rt3070_rf_write(sc, 44, (chan <= 14) ? 0x93 : 0x9b); /* Set drv_gnd_a, tx_vga_cc_a and tx_mx2_gain. */ run_rt3070_rf_write(sc, 52, (chan <= 14) ? 0x45 : 0x05); /* Enable VCO calibration. */ run_rt3070_rf_read(sc, 3, &rf); rf &= ~RT5390_VCOCAL; rf |= (chan <= 14) ? RT5390_VCOCAL : 0xbe; run_rt3070_rf_write(sc, 3, rf); if (chan <= 14) rf = 0x23; else if (chan <= 64) rf = 0x36; else if (chan <= 128) rf = 0x32; else rf = 0x30; run_rt3070_rf_write(sc, 39, rf); if (chan <= 14) rf = 0xbb; else if (chan <= 64) rf = 0xeb; else if (chan <= 128) rf = 0xb3; else rf = 0x9b; run_rt3070_rf_write(sc, 45, rf); /* Set FEQ/AEQ control. */ run_bbp_write(sc, 105, 0x34); } static void run_rt5390_set_chan(struct run_softc *sc, u_int chan) { int8_t txpow1, txpow2; uint8_t rf; int i; /* find the settings for this channel (we know it exists) */ for (i = 0; rt2860_rf2850[i].chan != chan; i++); /* use Tx power values from EEPROM */ txpow1 = sc->txpow1[i]; txpow2 = sc->txpow2[i]; run_rt3070_rf_write(sc, 8, rt3070_freqs[i].n); run_rt3070_rf_write(sc, 9, rt3070_freqs[i].k & 0x0f); run_rt3070_rf_read(sc, 11, &rf); rf = (rf & ~0x03) | (rt3070_freqs[i].r & 0x03); run_rt3070_rf_write(sc, 11, rf); run_rt3070_rf_read(sc, 49, &rf); rf = (rf & ~0x3f) | (txpow1 & 0x3f); /* The valid range of the RF R49 is 0x00 to 0x27. */ if ((rf & 0x3f) > 0x27) rf = (rf & ~0x3f) | 0x27; run_rt3070_rf_write(sc, 49, rf); if (sc->mac_ver == 0x5392) { run_rt3070_rf_read(sc, 50, &rf); rf = (rf & ~0x3f) | (txpow2 & 0x3f); /* The valid range of the RF R50 is 0x00 to 0x27. */ if ((rf & 0x3f) > 0x27) rf = (rf & ~0x3f) | 0x27; run_rt3070_rf_write(sc, 50, rf); } run_rt3070_rf_read(sc, 1, &rf); rf |= RT3070_RF_BLOCK | RT3070_PLL_PD | RT3070_RX0_PD | RT3070_TX0_PD; if (sc->mac_ver == 0x5392) rf |= RT3070_RX1_PD | RT3070_TX1_PD; run_rt3070_rf_write(sc, 1, rf); if (sc->mac_ver != 0x5392) { run_rt3070_rf_read(sc, 2, &rf); rf |= 0x80; run_rt3070_rf_write(sc, 2, rf); run_delay(sc, 10); rf &= 0x7f; run_rt3070_rf_write(sc, 2, rf); } run_adjust_freq_offset(sc); if (sc->mac_ver == 0x5392) { /* Fix for RT5392C. */ if (sc->mac_rev >= 0x0223) { if (chan <= 4) rf = 0x0f; else if (chan >= 5 && chan <= 7) rf = 0x0e; else rf = 0x0d; run_rt3070_rf_write(sc, 23, rf); if (chan <= 4) rf = 0x0c; else if (chan == 5) rf = 0x0b; else if (chan >= 6 && chan <= 7) rf = 0x0a; else if (chan >= 8 && chan <= 10) rf = 0x09; else rf = 0x08; run_rt3070_rf_write(sc, 59, rf); } else { if (chan <= 11) rf = 0x0f; else rf = 0x0b; run_rt3070_rf_write(sc, 59, rf); } } else { /* Fix for RT5390F. */ if (sc->mac_rev >= 0x0502) { if (chan <= 11) rf = 0x43; else rf = 0x23; run_rt3070_rf_write(sc, 55, rf); if (chan <= 11) rf = 0x0f; else if (chan == 12) rf = 0x0d; else rf = 0x0b; run_rt3070_rf_write(sc, 59, rf); } else { run_rt3070_rf_write(sc, 55, 0x44); run_rt3070_rf_write(sc, 59, 0x8f); } } /* Enable VCO calibration. */ run_rt3070_rf_read(sc, 3, &rf); rf |= RT5390_VCOCAL; run_rt3070_rf_write(sc, 3, rf); } static void run_rt5592_set_chan(struct run_softc *sc, u_int chan) { const struct rt5592_freqs *freqs; uint32_t tmp; uint8_t reg, rf, txpow_bound; int8_t txpow1, txpow2; int i; run_read(sc, RT5592_DEBUG_INDEX, &tmp); freqs = (tmp & RT5592_SEL_XTAL) ? rt5592_freqs_40mhz : rt5592_freqs_20mhz; /* find the settings for this channel (we know it exists) */ for (i = 0; rt2860_rf2850[i].chan != chan; i++, freqs++); /* use Tx power values from EEPROM */ txpow1 = sc->txpow1[i]; txpow2 = sc->txpow2[i]; run_read(sc, RT3070_LDO_CFG0, &tmp); tmp &= ~0x1c000000; if (chan > 14) tmp |= 0x14000000; run_write(sc, RT3070_LDO_CFG0, tmp); /* N setting. */ run_rt3070_rf_write(sc, 8, freqs->n & 0xff); run_rt3070_rf_read(sc, 9, &rf); rf &= ~(1 << 4); rf |= ((freqs->n & 0x0100) >> 8) << 4; run_rt3070_rf_write(sc, 9, rf); /* K setting. */ run_rt3070_rf_read(sc, 9, &rf); rf &= ~0x0f; rf |= (freqs->k & 0x0f); run_rt3070_rf_write(sc, 9, rf); /* Mode setting. */ run_rt3070_rf_read(sc, 11, &rf); rf &= ~0x0c; rf |= ((freqs->m - 0x8) & 0x3) << 2; run_rt3070_rf_write(sc, 11, rf); run_rt3070_rf_read(sc, 9, &rf); rf &= ~(1 << 7); rf |= (((freqs->m - 0x8) & 0x4) >> 2) << 7; run_rt3070_rf_write(sc, 9, rf); /* R setting. */ run_rt3070_rf_read(sc, 11, &rf); rf &= ~0x03; rf |= (freqs->r - 0x1); run_rt3070_rf_write(sc, 11, rf); if (chan <= 14) { /* Initialize RF registers for 2GHZ. */ for (i = 0; i < nitems(rt5592_2ghz_def_rf); i++) { run_rt3070_rf_write(sc, rt5592_2ghz_def_rf[i].reg, rt5592_2ghz_def_rf[i].val); } rf = (chan <= 10) ? 0x07 : 0x06; run_rt3070_rf_write(sc, 23, rf); run_rt3070_rf_write(sc, 59, rf); run_rt3070_rf_write(sc, 55, 0x43); /* * RF R49/R50 Tx power ALC code. * G-band bit<7:6>=1:0, bit<5:0> range from 0x0 ~ 0x27. */ reg = 2; txpow_bound = 0x27; } else { /* Initialize RF registers for 5GHZ. */ for (i = 0; i < nitems(rt5592_5ghz_def_rf); i++) { run_rt3070_rf_write(sc, rt5592_5ghz_def_rf[i].reg, rt5592_5ghz_def_rf[i].val); } for (i = 0; i < nitems(rt5592_chan_5ghz); i++) { if (chan >= rt5592_chan_5ghz[i].firstchan && chan <= rt5592_chan_5ghz[i].lastchan) { run_rt3070_rf_write(sc, rt5592_chan_5ghz[i].reg, rt5592_chan_5ghz[i].val); } } /* * RF R49/R50 Tx power ALC code. * A-band bit<7:6>=1:1, bit<5:0> range from 0x0 ~ 0x2b. */ reg = 3; txpow_bound = 0x2b; } /* RF R49 ch0 Tx power ALC code. */ run_rt3070_rf_read(sc, 49, &rf); rf &= ~0xc0; rf |= (reg << 6); rf = (rf & ~0x3f) | (txpow1 & 0x3f); if ((rf & 0x3f) > txpow_bound) rf = (rf & ~0x3f) | txpow_bound; run_rt3070_rf_write(sc, 49, rf); /* RF R50 ch1 Tx power ALC code. */ run_rt3070_rf_read(sc, 50, &rf); rf &= ~(1 << 7 | 1 << 6); rf |= (reg << 6); rf = (rf & ~0x3f) | (txpow2 & 0x3f); if ((rf & 0x3f) > txpow_bound) rf = (rf & ~0x3f) | txpow_bound; run_rt3070_rf_write(sc, 50, rf); /* Enable RF_BLOCK, PLL_PD, RX0_PD, and TX0_PD. */ run_rt3070_rf_read(sc, 1, &rf); rf |= (RT3070_RF_BLOCK | RT3070_PLL_PD | RT3070_RX0_PD | RT3070_TX0_PD); if (sc->ntxchains > 1) rf |= RT3070_TX1_PD; if (sc->nrxchains > 1) rf |= RT3070_RX1_PD; run_rt3070_rf_write(sc, 1, rf); run_rt3070_rf_write(sc, 6, 0xe4); run_rt3070_rf_write(sc, 30, 0x10); run_rt3070_rf_write(sc, 31, 0x80); run_rt3070_rf_write(sc, 32, 0x80); run_adjust_freq_offset(sc); /* Enable VCO calibration. */ run_rt3070_rf_read(sc, 3, &rf); rf |= RT5390_VCOCAL; run_rt3070_rf_write(sc, 3, rf); } static void run_set_rx_antenna(struct run_softc *sc, int aux) { uint32_t tmp; uint8_t bbp152; if (aux) { if (sc->rf_rev == RT5390_RF_5370) { run_bbp_read(sc, 152, &bbp152); run_bbp_write(sc, 152, bbp152 & ~0x80); } else { run_mcu_cmd(sc, RT2860_MCU_CMD_ANTSEL, 0); run_read(sc, RT2860_GPIO_CTRL, &tmp); run_write(sc, RT2860_GPIO_CTRL, (tmp & ~0x0808) | 0x08); } } else { if (sc->rf_rev == RT5390_RF_5370) { run_bbp_read(sc, 152, &bbp152); run_bbp_write(sc, 152, bbp152 | 0x80); } else { run_mcu_cmd(sc, RT2860_MCU_CMD_ANTSEL, 1); run_read(sc, RT2860_GPIO_CTRL, &tmp); run_write(sc, RT2860_GPIO_CTRL, tmp & ~0x0808); } } } static int run_set_chan(struct run_softc *sc, struct ieee80211_channel *c) { struct ieee80211com *ic = sc->sc_ifp->if_l2com; u_int chan, group; chan = ieee80211_chan2ieee(ic, c); if (chan == 0 || chan == IEEE80211_CHAN_ANY) return (EINVAL); if (sc->mac_ver == 0x5592) run_rt5592_set_chan(sc, chan); else if (sc->mac_ver >= 0x5390) run_rt5390_set_chan(sc, chan); else if (sc->mac_ver == 0x3593) run_rt3593_set_chan(sc, chan); else if (sc->mac_ver == 0x3572) run_rt3572_set_chan(sc, chan); else if (sc->mac_ver >= 0x3070) run_rt3070_set_chan(sc, chan); else run_rt2870_set_chan(sc, chan); /* determine channel group */ if (chan <= 14) group = 0; else if (chan <= 64) group = 1; else if (chan <= 128) group = 2; else group = 3; /* XXX necessary only when group has changed! */ run_select_chan_group(sc, group); run_delay(sc, 10); /* Perform IQ calibration. */ if (sc->mac_ver >= 0x5392) run_iq_calib(sc, chan); return (0); } static void run_set_channel(struct ieee80211com *ic) { struct run_softc *sc = ic->ic_ifp->if_softc; RUN_LOCK(sc); run_set_chan(sc, ic->ic_curchan); RUN_UNLOCK(sc); return; } static void run_scan_start(struct ieee80211com *ic) { struct run_softc *sc = ic->ic_ifp->if_softc; uint32_t tmp; RUN_LOCK(sc); /* abort TSF synchronization */ run_read(sc, RT2860_BCN_TIME_CFG, &tmp); run_write(sc, RT2860_BCN_TIME_CFG, tmp & ~(RT2860_BCN_TX_EN | RT2860_TSF_TIMER_EN | RT2860_TBTT_TIMER_EN)); run_set_bssid(sc, sc->sc_ifp->if_broadcastaddr); RUN_UNLOCK(sc); return; } static void run_scan_end(struct ieee80211com *ic) { struct run_softc *sc = ic->ic_ifp->if_softc; RUN_LOCK(sc); run_enable_tsf_sync(sc); /* XXX keep local copy */ run_set_bssid(sc, sc->sc_bssid); RUN_UNLOCK(sc); return; } /* * Could be called from ieee80211_node_timeout() * (non-sleepable thread) */ static void run_update_beacon(struct ieee80211vap *vap, int item) { struct ieee80211com *ic = vap->iv_ic; struct run_softc *sc = ic->ic_ifp->if_softc; struct run_vap *rvp = RUN_VAP(vap); int mcast = 0; uint32_t i; KASSERT(vap != NULL, ("no beacon")); switch (item) { case IEEE80211_BEACON_ERP: run_updateslot(ic->ic_ifp); break; case IEEE80211_BEACON_HTINFO: run_updateprot(ic); break; case IEEE80211_BEACON_TIM: mcast = 1; /*TODO*/ break; default: break; } setbit(rvp->bo.bo_flags, item); if (rvp->beacon_mbuf == NULL) { rvp->beacon_mbuf = ieee80211_beacon_alloc(vap->iv_bss, &rvp->bo); if (rvp->beacon_mbuf == NULL) return; } ieee80211_beacon_update(vap->iv_bss, &rvp->bo, rvp->beacon_mbuf, mcast); i = RUN_CMDQ_GET(&sc->cmdq_store); DPRINTF("cmdq_store=%d\n", i); sc->cmdq[i].func = run_update_beacon_cb; sc->cmdq[i].arg0 = vap; ieee80211_runtask(ic, &sc->cmdq_task); return; } static void run_update_beacon_cb(void *arg) { struct ieee80211vap *vap = arg; struct run_vap *rvp = RUN_VAP(vap); struct ieee80211com *ic = vap->iv_ic; struct run_softc *sc = ic->ic_ifp->if_softc; struct rt2860_txwi txwi; struct mbuf *m; uint16_t txwisize; uint8_t ridx; if (vap->iv_bss->ni_chan == IEEE80211_CHAN_ANYC) return; if (ic->ic_bsschan == IEEE80211_CHAN_ANYC) return; /* * No need to call ieee80211_beacon_update(), run_update_beacon() * is taking care of apropriate calls. */ if (rvp->beacon_mbuf == NULL) { rvp->beacon_mbuf = ieee80211_beacon_alloc(vap->iv_bss, &rvp->bo); if (rvp->beacon_mbuf == NULL) return; } m = rvp->beacon_mbuf; memset(&txwi, 0, sizeof(txwi)); txwi.wcid = 0xff; txwi.len = htole16(m->m_pkthdr.len); /* send beacons at the lowest available rate */ ridx = (ic->ic_curmode == IEEE80211_MODE_11A) ? RT2860_RIDX_OFDM6 : RT2860_RIDX_CCK1; txwi.phy = htole16(rt2860_rates[ridx].mcs); if (rt2860_rates[ridx].phy == IEEE80211_T_OFDM) txwi.phy |= htole16(RT2860_PHY_OFDM); txwi.txop = RT2860_TX_TXOP_HT; txwi.flags = RT2860_TX_TS; txwi.xflags = RT2860_TX_NSEQ; txwisize = (sc->mac_ver == 0x5592) ? sizeof(txwi) + sizeof(uint32_t) : sizeof(txwi); run_write_region_1(sc, RT2860_BCN_BASE(rvp->rvp_id), (uint8_t *)&txwi, txwisize); run_write_region_1(sc, RT2860_BCN_BASE(rvp->rvp_id) + txwisize, mtod(m, uint8_t *), (m->m_pkthdr.len + 1) & ~1); } static void run_updateprot(struct ieee80211com *ic) { struct run_softc *sc = ic->ic_ifp->if_softc; uint32_t i; i = RUN_CMDQ_GET(&sc->cmdq_store); DPRINTF("cmdq_store=%d\n", i); sc->cmdq[i].func = run_updateprot_cb; sc->cmdq[i].arg0 = ic; ieee80211_runtask(ic, &sc->cmdq_task); } static void run_updateprot_cb(void *arg) { struct ieee80211com *ic = arg; struct run_softc *sc = ic->ic_ifp->if_softc; uint32_t tmp; tmp = RT2860_RTSTH_EN | RT2860_PROT_NAV_SHORT | RT2860_TXOP_ALLOW_ALL; /* setup protection frame rate (MCS code) */ tmp |= (ic->ic_curmode == IEEE80211_MODE_11A) ? rt2860_rates[RT2860_RIDX_OFDM6].mcs | RT2860_PHY_OFDM : rt2860_rates[RT2860_RIDX_CCK11].mcs; /* CCK frames don't require protection */ run_write(sc, RT2860_CCK_PROT_CFG, tmp); if (ic->ic_flags & IEEE80211_F_USEPROT) { if (ic->ic_protmode == IEEE80211_PROT_RTSCTS) tmp |= RT2860_PROT_CTRL_RTS_CTS; else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY) tmp |= RT2860_PROT_CTRL_CTS; } run_write(sc, RT2860_OFDM_PROT_CFG, tmp); } static void run_usb_timeout_cb(void *arg) { struct ieee80211vap *vap = arg; struct run_softc *sc = vap->iv_ic->ic_ifp->if_softc; RUN_LOCK_ASSERT(sc, MA_OWNED); if(vap->iv_state == IEEE80211_S_RUN && vap->iv_opmode != IEEE80211_M_STA) run_reset_livelock(sc); else if (vap->iv_state == IEEE80211_S_SCAN) { DPRINTF("timeout caused by scan\n"); /* cancel bgscan */ ieee80211_cancel_scan(vap); } else DPRINTF("timeout by unknown cause\n"); } static void run_reset_livelock(struct run_softc *sc) { uint32_t tmp; RUN_LOCK_ASSERT(sc, MA_OWNED); /* * In IBSS or HostAP modes (when the hardware sends beacons), the MAC * can run into a livelock and start sending CTS-to-self frames like * crazy if protection is enabled. Reset MAC/BBP for a while */ run_read(sc, RT2860_DEBUG, &tmp); DPRINTFN(3, "debug reg %08x\n", tmp); if ((tmp & (1 << 29)) && (tmp & (1 << 7 | 1 << 5))) { DPRINTF("CTS-to-self livelock detected\n"); run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_MAC_SRST); run_delay(sc, 1); run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_MAC_RX_EN | RT2860_MAC_TX_EN); } } static void run_update_promisc_locked(struct ifnet *ifp) { struct run_softc *sc = ifp->if_softc; uint32_t tmp; run_read(sc, RT2860_RX_FILTR_CFG, &tmp); tmp |= RT2860_DROP_UC_NOME; if (ifp->if_flags & IFF_PROMISC) tmp &= ~RT2860_DROP_UC_NOME; run_write(sc, RT2860_RX_FILTR_CFG, tmp); DPRINTF("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ? "entering" : "leaving"); } static void run_update_promisc(struct ifnet *ifp) { struct run_softc *sc = ifp->if_softc; if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) return; RUN_LOCK(sc); run_update_promisc_locked(ifp); RUN_UNLOCK(sc); } static void run_enable_tsf_sync(struct run_softc *sc) { struct ieee80211com *ic = sc->sc_ifp->if_l2com; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); uint32_t tmp; DPRINTF("rvp_id=%d ic_opmode=%d\n", RUN_VAP(vap)->rvp_id, ic->ic_opmode); run_read(sc, RT2860_BCN_TIME_CFG, &tmp); tmp &= ~0x1fffff; tmp |= vap->iv_bss->ni_intval * 16; tmp |= RT2860_TSF_TIMER_EN | RT2860_TBTT_TIMER_EN; if (ic->ic_opmode == IEEE80211_M_STA) { /* * Local TSF is always updated with remote TSF on beacon * reception. */ tmp |= 1 << RT2860_TSF_SYNC_MODE_SHIFT; } else if (ic->ic_opmode == IEEE80211_M_IBSS) { tmp |= RT2860_BCN_TX_EN; /* * Local TSF is updated with remote TSF on beacon reception * only if the remote TSF is greater than local TSF. */ tmp |= 2 << RT2860_TSF_SYNC_MODE_SHIFT; } else if (ic->ic_opmode == IEEE80211_M_HOSTAP || ic->ic_opmode == IEEE80211_M_MBSS) { tmp |= RT2860_BCN_TX_EN; /* SYNC with nobody */ tmp |= 3 << RT2860_TSF_SYNC_MODE_SHIFT; } else { DPRINTF("Enabling TSF failed. undefined opmode\n"); return; } run_write(sc, RT2860_BCN_TIME_CFG, tmp); } static void run_enable_mrr(struct run_softc *sc) { #define CCK(mcs) (mcs) #define OFDM(mcs) (1 << 3 | (mcs)) run_write(sc, RT2860_LG_FBK_CFG0, OFDM(6) << 28 | /* 54->48 */ OFDM(5) << 24 | /* 48->36 */ OFDM(4) << 20 | /* 36->24 */ OFDM(3) << 16 | /* 24->18 */ OFDM(2) << 12 | /* 18->12 */ OFDM(1) << 8 | /* 12-> 9 */ OFDM(0) << 4 | /* 9-> 6 */ OFDM(0)); /* 6-> 6 */ run_write(sc, RT2860_LG_FBK_CFG1, CCK(2) << 12 | /* 11->5.5 */ CCK(1) << 8 | /* 5.5-> 2 */ CCK(0) << 4 | /* 2-> 1 */ CCK(0)); /* 1-> 1 */ #undef OFDM #undef CCK } static void run_set_txpreamble(struct run_softc *sc) { struct ieee80211com *ic = sc->sc_ifp->if_l2com; uint32_t tmp; run_read(sc, RT2860_AUTO_RSP_CFG, &tmp); if (ic->ic_flags & IEEE80211_F_SHPREAMBLE) tmp |= RT2860_CCK_SHORT_EN; else tmp &= ~RT2860_CCK_SHORT_EN; run_write(sc, RT2860_AUTO_RSP_CFG, tmp); } static void run_set_basicrates(struct run_softc *sc) { struct ieee80211com *ic = sc->sc_ifp->if_l2com; /* set basic rates mask */ if (ic->ic_curmode == IEEE80211_MODE_11B) run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x003); else if (ic->ic_curmode == IEEE80211_MODE_11A) run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x150); else /* 11g */ run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x15f); } static void run_set_leds(struct run_softc *sc, uint16_t which) { (void)run_mcu_cmd(sc, RT2860_MCU_CMD_LEDS, which | (sc->leds & 0x7f)); } static void run_set_bssid(struct run_softc *sc, const uint8_t *bssid) { run_write(sc, RT2860_MAC_BSSID_DW0, bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24); run_write(sc, RT2860_MAC_BSSID_DW1, bssid[4] | bssid[5] << 8); } static void run_set_macaddr(struct run_softc *sc, const uint8_t *addr) { run_write(sc, RT2860_MAC_ADDR_DW0, addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24); run_write(sc, RT2860_MAC_ADDR_DW1, addr[4] | addr[5] << 8 | 0xff << 16); } static void run_updateslot(struct ifnet *ifp) { struct run_softc *sc = ifp->if_softc; struct ieee80211com *ic = ifp->if_l2com; uint32_t i; i = RUN_CMDQ_GET(&sc->cmdq_store); DPRINTF("cmdq_store=%d\n", i); sc->cmdq[i].func = run_updateslot_cb; sc->cmdq[i].arg0 = ifp; ieee80211_runtask(ic, &sc->cmdq_task); return; } /* ARGSUSED */ static void run_updateslot_cb(void *arg) { struct ifnet *ifp = arg; struct run_softc *sc = ifp->if_softc; struct ieee80211com *ic = ifp->if_l2com; uint32_t tmp; run_read(sc, RT2860_BKOFF_SLOT_CFG, &tmp); tmp &= ~0xff; tmp |= (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20; run_write(sc, RT2860_BKOFF_SLOT_CFG, tmp); } static void run_update_mcast(struct ifnet *ifp) { /* h/w filter supports getting everything or nothing */ ifp->if_flags |= IFF_ALLMULTI; } static int8_t run_rssi2dbm(struct run_softc *sc, uint8_t rssi, uint8_t rxchain) { struct ieee80211com *ic = sc->sc_ifp->if_l2com; struct ieee80211_channel *c = ic->ic_curchan; int delta; if (IEEE80211_IS_CHAN_5GHZ(c)) { u_int chan = ieee80211_chan2ieee(ic, c); delta = sc->rssi_5ghz[rxchain]; /* determine channel group */ if (chan <= 64) delta -= sc->lna[1]; else if (chan <= 128) delta -= sc->lna[2]; else delta -= sc->lna[3]; } else delta = sc->rssi_2ghz[rxchain] - sc->lna[0]; return (-12 - delta - rssi); } static void run_rt5390_bbp_init(struct run_softc *sc) { int i; uint8_t bbp; /* Apply maximum likelihood detection for 2 stream case. */ run_bbp_read(sc, 105, &bbp); if (sc->nrxchains > 1) run_bbp_write(sc, 105, bbp | RT5390_MLD); /* Avoid data lost and CRC error. */ run_bbp_read(sc, 4, &bbp); run_bbp_write(sc, 4, bbp | RT5390_MAC_IF_CTRL); if (sc->mac_ver == 0x5592) { for (i = 0; i < nitems(rt5592_def_bbp); i++) { run_bbp_write(sc, rt5592_def_bbp[i].reg, rt5592_def_bbp[i].val); } for (i = 0; i < nitems(rt5592_bbp_r196); i++) { run_bbp_write(sc, 195, i + 0x80); run_bbp_write(sc, 196, rt5592_bbp_r196[i]); } } else { for (i = 0; i < nitems(rt5390_def_bbp); i++) { run_bbp_write(sc, rt5390_def_bbp[i].reg, rt5390_def_bbp[i].val); } } if (sc->mac_ver == 0x5392) { run_bbp_write(sc, 88, 0x90); run_bbp_write(sc, 95, 0x9a); run_bbp_write(sc, 98, 0x12); run_bbp_write(sc, 106, 0x12); run_bbp_write(sc, 134, 0xd0); run_bbp_write(sc, 135, 0xf6); run_bbp_write(sc, 148, 0x84); } run_bbp_read(sc, 152, &bbp); run_bbp_write(sc, 152, bbp | 0x80); /* Fix BBP254 for RT5592C. */ if (sc->mac_ver == 0x5592 && sc->mac_rev >= 0x0221) { run_bbp_read(sc, 254, &bbp); run_bbp_write(sc, 254, bbp | 0x80); } /* Disable hardware antenna diversity. */ if (sc->mac_ver == 0x5390) run_bbp_write(sc, 154, 0); /* Initialize Rx CCK/OFDM frequency offset report. */ run_bbp_write(sc, 142, 1); run_bbp_write(sc, 143, 57); } static int run_bbp_init(struct run_softc *sc) { int i, error, ntries; uint8_t bbp0; /* wait for BBP to wake up */ for (ntries = 0; ntries < 20; ntries++) { if ((error = run_bbp_read(sc, 0, &bbp0)) != 0) return error; if (bbp0 != 0 && bbp0 != 0xff) break; } if (ntries == 20) return (ETIMEDOUT); /* initialize BBP registers to default values */ if (sc->mac_ver >= 0x5390) run_rt5390_bbp_init(sc); else { for (i = 0; i < nitems(rt2860_def_bbp); i++) { run_bbp_write(sc, rt2860_def_bbp[i].reg, rt2860_def_bbp[i].val); } } if (sc->mac_ver == 0x3593) { run_bbp_write(sc, 79, 0x13); run_bbp_write(sc, 80, 0x05); run_bbp_write(sc, 81, 0x33); run_bbp_write(sc, 86, 0x46); run_bbp_write(sc, 137, 0x0f); } /* fix BBP84 for RT2860E */ if (sc->mac_ver == 0x2860 && sc->mac_rev != 0x0101) run_bbp_write(sc, 84, 0x19); if (sc->mac_ver >= 0x3070 && (sc->mac_ver != 0x3593 && sc->mac_ver != 0x5592)) { run_bbp_write(sc, 79, 0x13); run_bbp_write(sc, 80, 0x05); run_bbp_write(sc, 81, 0x33); } else if (sc->mac_ver == 0x2860 && sc->mac_rev == 0x0100) { run_bbp_write(sc, 69, 0x16); run_bbp_write(sc, 73, 0x12); } return (0); } static int run_rt3070_rf_init(struct run_softc *sc) { uint32_t tmp; uint8_t bbp4, mingain, rf, target; int i; run_rt3070_rf_read(sc, 30, &rf); /* toggle RF R30 bit 7 */ run_rt3070_rf_write(sc, 30, rf | 0x80); run_delay(sc, 10); run_rt3070_rf_write(sc, 30, rf & ~0x80); /* initialize RF registers to default value */ if (sc->mac_ver == 0x3572) { for (i = 0; i < nitems(rt3572_def_rf); i++) { run_rt3070_rf_write(sc, rt3572_def_rf[i].reg, rt3572_def_rf[i].val); } } else { for (i = 0; i < nitems(rt3070_def_rf); i++) { run_rt3070_rf_write(sc, rt3070_def_rf[i].reg, rt3070_def_rf[i].val); } } if (sc->mac_ver == 0x3070 && sc->mac_rev < 0x0201) { /* * Change voltage from 1.2V to 1.35V for RT3070. * The DAC issue (RT3070_LDO_CFG0) has been fixed * in RT3070(F). */ run_read(sc, RT3070_LDO_CFG0, &tmp); tmp = (tmp & ~0x0f000000) | 0x0d000000; run_write(sc, RT3070_LDO_CFG0, tmp); } else if (sc->mac_ver == 0x3071) { run_rt3070_rf_read(sc, 6, &rf); run_rt3070_rf_write(sc, 6, rf | 0x40); run_rt3070_rf_write(sc, 31, 0x14); run_read(sc, RT3070_LDO_CFG0, &tmp); tmp &= ~0x1f000000; if (sc->mac_rev < 0x0211) tmp |= 0x0d000000; /* 1.3V */ else tmp |= 0x01000000; /* 1.2V */ run_write(sc, RT3070_LDO_CFG0, tmp); /* patch LNA_PE_G1 */ run_read(sc, RT3070_GPIO_SWITCH, &tmp); run_write(sc, RT3070_GPIO_SWITCH, tmp & ~0x20); } else if (sc->mac_ver == 0x3572) { run_rt3070_rf_read(sc, 6, &rf); run_rt3070_rf_write(sc, 6, rf | 0x40); /* increase voltage from 1.2V to 1.35V */ run_read(sc, RT3070_LDO_CFG0, &tmp); tmp = (tmp & ~0x1f000000) | 0x0d000000; run_write(sc, RT3070_LDO_CFG0, tmp); if (sc->mac_rev < 0x0211 || !sc->patch_dac) { run_delay(sc, 1); /* wait for 1msec */ /* decrease voltage back to 1.2V */ tmp = (tmp & ~0x1f000000) | 0x01000000; run_write(sc, RT3070_LDO_CFG0, tmp); } } /* select 20MHz bandwidth */ run_rt3070_rf_read(sc, 31, &rf); run_rt3070_rf_write(sc, 31, rf & ~0x20); /* calibrate filter for 20MHz bandwidth */ sc->rf24_20mhz = 0x1f; /* default value */ target = (sc->mac_ver < 0x3071) ? 0x16 : 0x13; run_rt3070_filter_calib(sc, 0x07, target, &sc->rf24_20mhz); /* select 40MHz bandwidth */ run_bbp_read(sc, 4, &bbp4); run_bbp_write(sc, 4, (bbp4 & ~0x18) | 0x10); run_rt3070_rf_read(sc, 31, &rf); run_rt3070_rf_write(sc, 31, rf | 0x20); /* calibrate filter for 40MHz bandwidth */ sc->rf24_40mhz = 0x2f; /* default value */ target = (sc->mac_ver < 0x3071) ? 0x19 : 0x15; run_rt3070_filter_calib(sc, 0x27, target, &sc->rf24_40mhz); /* go back to 20MHz bandwidth */ run_bbp_read(sc, 4, &bbp4); run_bbp_write(sc, 4, bbp4 & ~0x18); if (sc->mac_ver == 0x3572) { /* save default BBP registers 25 and 26 values */ run_bbp_read(sc, 25, &sc->bbp25); run_bbp_read(sc, 26, &sc->bbp26); } else if (sc->mac_rev < 0x0201 || sc->mac_rev < 0x0211) run_rt3070_rf_write(sc, 27, 0x03); run_read(sc, RT3070_OPT_14, &tmp); run_write(sc, RT3070_OPT_14, tmp | 1); if (sc->mac_ver == 0x3070 || sc->mac_ver == 0x3071) { run_rt3070_rf_read(sc, 17, &rf); rf &= ~RT3070_TX_LO1; if ((sc->mac_ver == 0x3070 || (sc->mac_ver == 0x3071 && sc->mac_rev >= 0x0211)) && !sc->ext_2ghz_lna) rf |= 0x20; /* fix for long range Rx issue */ mingain = (sc->mac_ver == 0x3070) ? 1 : 2; if (sc->txmixgain_2ghz >= mingain) rf = (rf & ~0x7) | sc->txmixgain_2ghz; run_rt3070_rf_write(sc, 17, rf); } if (sc->mac_ver == 0x3071) { run_rt3070_rf_read(sc, 1, &rf); rf &= ~(RT3070_RX0_PD | RT3070_TX0_PD); rf |= RT3070_RF_BLOCK | RT3070_RX1_PD | RT3070_TX1_PD; run_rt3070_rf_write(sc, 1, rf); run_rt3070_rf_read(sc, 15, &rf); run_rt3070_rf_write(sc, 15, rf & ~RT3070_TX_LO2); run_rt3070_rf_read(sc, 20, &rf); run_rt3070_rf_write(sc, 20, rf & ~RT3070_RX_LO1); run_rt3070_rf_read(sc, 21, &rf); run_rt3070_rf_write(sc, 21, rf & ~RT3070_RX_LO2); } if (sc->mac_ver == 0x3070 || sc->mac_ver == 0x3071) { /* fix Tx to Rx IQ glitch by raising RF voltage */ run_rt3070_rf_read(sc, 27, &rf); rf &= ~0x77; if (sc->mac_rev < 0x0211) rf |= 0x03; run_rt3070_rf_write(sc, 27, rf); } return (0); } static void run_rt3593_rf_init(struct run_softc *sc) { uint32_t tmp; uint8_t rf; int i; /* Disable the GPIO bits 4 and 7 for LNA PE control. */ run_read(sc, RT3070_GPIO_SWITCH, &tmp); tmp &= ~(1 << 4 | 1 << 7); run_write(sc, RT3070_GPIO_SWITCH, tmp); /* Initialize RF registers to default value. */ for (i = 0; i < nitems(rt3593_def_rf); i++) { run_rt3070_rf_write(sc, rt3593_def_rf[i].reg, rt3593_def_rf[i].val); } /* Toggle RF R2 to initiate calibration. */ run_rt3070_rf_write(sc, 2, RT5390_RESCAL); /* Initialize RF frequency offset. */ run_adjust_freq_offset(sc); run_rt3070_rf_read(sc, 18, &rf); run_rt3070_rf_write(sc, 18, rf | RT3593_AUTOTUNE_BYPASS); /* * Increase voltage from 1.2V to 1.35V, wait for 1 msec to * decrease voltage back to 1.2V. */ run_read(sc, RT3070_LDO_CFG0, &tmp); tmp = (tmp & ~0x1f000000) | 0x0d000000; run_write(sc, RT3070_LDO_CFG0, tmp); run_delay(sc, 1); tmp = (tmp & ~0x1f000000) | 0x01000000; run_write(sc, RT3070_LDO_CFG0, tmp); sc->rf24_20mhz = 0x1f; sc->rf24_40mhz = 0x2f; /* Save default BBP registers 25 and 26 values. */ run_bbp_read(sc, 25, &sc->bbp25); run_bbp_read(sc, 26, &sc->bbp26); run_read(sc, RT3070_OPT_14, &tmp); run_write(sc, RT3070_OPT_14, tmp | 1); } static void run_rt5390_rf_init(struct run_softc *sc) { uint32_t tmp; uint8_t rf; int i; /* Toggle RF R2 to initiate calibration. */ if (sc->mac_ver == 0x5390) { run_rt3070_rf_read(sc, 2, &rf); run_rt3070_rf_write(sc, 2, rf | RT5390_RESCAL); run_delay(sc, 10); run_rt3070_rf_write(sc, 2, rf & ~RT5390_RESCAL); } else { run_rt3070_rf_write(sc, 2, RT5390_RESCAL); run_delay(sc, 10); } /* Initialize RF registers to default value. */ if (sc->mac_ver == 0x5592) { for (i = 0; i < nitems(rt5592_def_rf); i++) { run_rt3070_rf_write(sc, rt5592_def_rf[i].reg, rt5592_def_rf[i].val); } /* Initialize RF frequency offset. */ run_adjust_freq_offset(sc); } else if (sc->mac_ver == 0x5392) { for (i = 0; i < nitems(rt5392_def_rf); i++) { run_rt3070_rf_write(sc, rt5392_def_rf[i].reg, rt5392_def_rf[i].val); } if (sc->mac_rev >= 0x0223) { run_rt3070_rf_write(sc, 23, 0x0f); run_rt3070_rf_write(sc, 24, 0x3e); run_rt3070_rf_write(sc, 51, 0x32); run_rt3070_rf_write(sc, 53, 0x22); run_rt3070_rf_write(sc, 56, 0xc1); run_rt3070_rf_write(sc, 59, 0x0f); } } else { for (i = 0; i < nitems(rt5390_def_rf); i++) { run_rt3070_rf_write(sc, rt5390_def_rf[i].reg, rt5390_def_rf[i].val); } if (sc->mac_rev >= 0x0502) { run_rt3070_rf_write(sc, 6, 0xe0); run_rt3070_rf_write(sc, 25, 0x80); run_rt3070_rf_write(sc, 46, 0x73); run_rt3070_rf_write(sc, 53, 0x00); run_rt3070_rf_write(sc, 56, 0x42); run_rt3070_rf_write(sc, 61, 0xd1); } } sc->rf24_20mhz = 0x1f; /* default value */ sc->rf24_40mhz = (sc->mac_ver == 0x5592) ? 0 : 0x2f; if (sc->mac_rev < 0x0211) run_rt3070_rf_write(sc, 27, 0x3); run_read(sc, RT3070_OPT_14, &tmp); run_write(sc, RT3070_OPT_14, tmp | 1); } static int run_rt3070_filter_calib(struct run_softc *sc, uint8_t init, uint8_t target, uint8_t *val) { uint8_t rf22, rf24; uint8_t bbp55_pb, bbp55_sb, delta; int ntries; /* program filter */ run_rt3070_rf_read(sc, 24, &rf24); rf24 = (rf24 & 0xc0) | init; /* initial filter value */ run_rt3070_rf_write(sc, 24, rf24); /* enable baseband loopback mode */ run_rt3070_rf_read(sc, 22, &rf22); run_rt3070_rf_write(sc, 22, rf22 | 0x01); /* set power and frequency of passband test tone */ run_bbp_write(sc, 24, 0x00); for (ntries = 0; ntries < 100; ntries++) { /* transmit test tone */ run_bbp_write(sc, 25, 0x90); run_delay(sc, 10); /* read received power */ run_bbp_read(sc, 55, &bbp55_pb); if (bbp55_pb != 0) break; } if (ntries == 100) return (ETIMEDOUT); /* set power and frequency of stopband test tone */ run_bbp_write(sc, 24, 0x06); for (ntries = 0; ntries < 100; ntries++) { /* transmit test tone */ run_bbp_write(sc, 25, 0x90); run_delay(sc, 10); /* read received power */ run_bbp_read(sc, 55, &bbp55_sb); delta = bbp55_pb - bbp55_sb; if (delta > target) break; /* reprogram filter */ rf24++; run_rt3070_rf_write(sc, 24, rf24); } if (ntries < 100) { if (rf24 != init) rf24--; /* backtrack */ *val = rf24; run_rt3070_rf_write(sc, 24, rf24); } /* restore initial state */ run_bbp_write(sc, 24, 0x00); /* disable baseband loopback mode */ run_rt3070_rf_read(sc, 22, &rf22); run_rt3070_rf_write(sc, 22, rf22 & ~0x01); return (0); } static void run_rt3070_rf_setup(struct run_softc *sc) { uint8_t bbp, rf; int i; if (sc->mac_ver == 0x3572) { /* enable DC filter */ if (sc->mac_rev >= 0x0201) run_bbp_write(sc, 103, 0xc0); run_bbp_read(sc, 138, &bbp); if (sc->ntxchains == 1) bbp |= 0x20; /* turn off DAC1 */ if (sc->nrxchains == 1) bbp &= ~0x02; /* turn off ADC1 */ run_bbp_write(sc, 138, bbp); if (sc->mac_rev >= 0x0211) { /* improve power consumption */ run_bbp_read(sc, 31, &bbp); run_bbp_write(sc, 31, bbp & ~0x03); } run_rt3070_rf_read(sc, 16, &rf); rf = (rf & ~0x07) | sc->txmixgain_2ghz; run_rt3070_rf_write(sc, 16, rf); } else if (sc->mac_ver == 0x3071) { if (sc->mac_rev >= 0x0211) { /* enable DC filter */ run_bbp_write(sc, 103, 0xc0); /* improve power consumption */ run_bbp_read(sc, 31, &bbp); run_bbp_write(sc, 31, bbp & ~0x03); } run_bbp_read(sc, 138, &bbp); if (sc->ntxchains == 1) bbp |= 0x20; /* turn off DAC1 */ if (sc->nrxchains == 1) bbp &= ~0x02; /* turn off ADC1 */ run_bbp_write(sc, 138, bbp); run_write(sc, RT2860_TX_SW_CFG1, 0); if (sc->mac_rev < 0x0211) { run_write(sc, RT2860_TX_SW_CFG2, sc->patch_dac ? 0x2c : 0x0f); } else run_write(sc, RT2860_TX_SW_CFG2, 0); } else if (sc->mac_ver == 0x3070) { if (sc->mac_rev >= 0x0201) { /* enable DC filter */ run_bbp_write(sc, 103, 0xc0); /* improve power consumption */ run_bbp_read(sc, 31, &bbp); run_bbp_write(sc, 31, bbp & ~0x03); } if (sc->mac_rev < 0x0201) { run_write(sc, RT2860_TX_SW_CFG1, 0); run_write(sc, RT2860_TX_SW_CFG2, 0x2c); } else run_write(sc, RT2860_TX_SW_CFG2, 0); } /* initialize RF registers from ROM for >=RT3071*/ if (sc->mac_ver >= 0x3071) { for (i = 0; i < 10; i++) { if (sc->rf[i].reg == 0 || sc->rf[i].reg == 0xff) continue; run_rt3070_rf_write(sc, sc->rf[i].reg, sc->rf[i].val); } } } static void run_rt3593_rf_setup(struct run_softc *sc) { uint8_t bbp, rf; if (sc->mac_rev >= 0x0211) { /* Enable DC filter. */ run_bbp_write(sc, 103, 0xc0); } run_write(sc, RT2860_TX_SW_CFG1, 0); if (sc->mac_rev < 0x0211) { run_write(sc, RT2860_TX_SW_CFG2, sc->patch_dac ? 0x2c : 0x0f); } else run_write(sc, RT2860_TX_SW_CFG2, 0); run_rt3070_rf_read(sc, 50, &rf); run_rt3070_rf_write(sc, 50, rf & ~RT3593_TX_LO2); run_rt3070_rf_read(sc, 51, &rf); rf = (rf & ~(RT3593_TX_LO1 | 0x0c)) | ((sc->txmixgain_2ghz & 0x07) << 2); run_rt3070_rf_write(sc, 51, rf); run_rt3070_rf_read(sc, 38, &rf); run_rt3070_rf_write(sc, 38, rf & ~RT5390_RX_LO1); run_rt3070_rf_read(sc, 39, &rf); run_rt3070_rf_write(sc, 39, rf & ~RT5390_RX_LO2); run_rt3070_rf_read(sc, 1, &rf); run_rt3070_rf_write(sc, 1, rf & ~(RT3070_RF_BLOCK | RT3070_PLL_PD)); run_rt3070_rf_read(sc, 30, &rf); rf = (rf & ~0x18) | 0x10; run_rt3070_rf_write(sc, 30, rf); /* Apply maximum likelihood detection for 2 stream case. */ run_bbp_read(sc, 105, &bbp); if (sc->nrxchains > 1) run_bbp_write(sc, 105, bbp | RT5390_MLD); /* Avoid data lost and CRC error. */ run_bbp_read(sc, 4, &bbp); run_bbp_write(sc, 4, bbp | RT5390_MAC_IF_CTRL); run_bbp_write(sc, 92, 0x02); run_bbp_write(sc, 82, 0x82); run_bbp_write(sc, 106, 0x05); run_bbp_write(sc, 104, 0x92); run_bbp_write(sc, 88, 0x90); run_bbp_write(sc, 148, 0xc8); run_bbp_write(sc, 47, 0x48); run_bbp_write(sc, 120, 0x50); run_bbp_write(sc, 163, 0x9d); /* SNR mapping. */ run_bbp_write(sc, 142, 0x06); run_bbp_write(sc, 143, 0xa0); run_bbp_write(sc, 142, 0x07); run_bbp_write(sc, 143, 0xa1); run_bbp_write(sc, 142, 0x08); run_bbp_write(sc, 143, 0xa2); run_bbp_write(sc, 31, 0x08); run_bbp_write(sc, 68, 0x0b); run_bbp_write(sc, 105, 0x04); } static void run_rt5390_rf_setup(struct run_softc *sc) { uint8_t bbp, rf; if (sc->mac_rev >= 0x0211) { /* Enable DC filter. */ run_bbp_write(sc, 103, 0xc0); if (sc->mac_ver != 0x5592) { /* Improve power consumption. */ run_bbp_read(sc, 31, &bbp); run_bbp_write(sc, 31, bbp & ~0x03); } } run_bbp_read(sc, 138, &bbp); if (sc->ntxchains == 1) bbp |= 0x20; /* turn off DAC1 */ if (sc->nrxchains == 1) bbp &= ~0x02; /* turn off ADC1 */ run_bbp_write(sc, 138, bbp); run_rt3070_rf_read(sc, 38, &rf); run_rt3070_rf_write(sc, 38, rf & ~RT5390_RX_LO1); run_rt3070_rf_read(sc, 39, &rf); run_rt3070_rf_write(sc, 39, rf & ~RT5390_RX_LO2); /* Avoid data lost and CRC error. */ run_bbp_read(sc, 4, &bbp); run_bbp_write(sc, 4, bbp | RT5390_MAC_IF_CTRL); run_rt3070_rf_read(sc, 30, &rf); rf = (rf & ~0x18) | 0x10; run_rt3070_rf_write(sc, 30, rf); if (sc->mac_ver != 0x5592) { run_write(sc, RT2860_TX_SW_CFG1, 0); if (sc->mac_rev < 0x0211) { run_write(sc, RT2860_TX_SW_CFG2, sc->patch_dac ? 0x2c : 0x0f); } else run_write(sc, RT2860_TX_SW_CFG2, 0); } } static int run_txrx_enable(struct run_softc *sc) { struct ieee80211com *ic = sc->sc_ifp->if_l2com; uint32_t tmp; int error, ntries; run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_MAC_TX_EN); for (ntries = 0; ntries < 200; ntries++) { if ((error = run_read(sc, RT2860_WPDMA_GLO_CFG, &tmp)) != 0) return (error); if ((tmp & (RT2860_TX_DMA_BUSY | RT2860_RX_DMA_BUSY)) == 0) break; run_delay(sc, 50); } if (ntries == 200) return (ETIMEDOUT); run_delay(sc, 50); tmp |= RT2860_RX_DMA_EN | RT2860_TX_DMA_EN | RT2860_TX_WB_DDONE; run_write(sc, RT2860_WPDMA_GLO_CFG, tmp); /* enable Rx bulk aggregation (set timeout and limit) */ tmp = RT2860_USB_TX_EN | RT2860_USB_RX_EN | RT2860_USB_RX_AGG_EN | RT2860_USB_RX_AGG_TO(128) | RT2860_USB_RX_AGG_LMT(2); run_write(sc, RT2860_USB_DMA_CFG, tmp); /* set Rx filter */ tmp = RT2860_DROP_CRC_ERR | RT2860_DROP_PHY_ERR; if (ic->ic_opmode != IEEE80211_M_MONITOR) { tmp |= RT2860_DROP_UC_NOME | RT2860_DROP_DUPL | RT2860_DROP_CTS | RT2860_DROP_BA | RT2860_DROP_ACK | RT2860_DROP_VER_ERR | RT2860_DROP_CTRL_RSV | RT2860_DROP_CFACK | RT2860_DROP_CFEND; if (ic->ic_opmode == IEEE80211_M_STA) tmp |= RT2860_DROP_RTS | RT2860_DROP_PSPOLL; } run_write(sc, RT2860_RX_FILTR_CFG, tmp); run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_MAC_RX_EN | RT2860_MAC_TX_EN); return (0); } static void run_adjust_freq_offset(struct run_softc *sc) { uint8_t rf, tmp; run_rt3070_rf_read(sc, 17, &rf); tmp = rf; rf = (rf & ~0x7f) | (sc->freq & 0x7f); rf = MIN(rf, 0x5f); if (tmp != rf) run_mcu_cmd(sc, 0x74, (tmp << 8 ) | rf); } static void run_init_locked(struct run_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; uint32_t tmp; uint8_t bbp1, bbp3; int i; int ridx; int ntries; if (ic->ic_nrunning > 1) return; run_stop(sc); if (run_load_microcode(sc) != 0) { device_printf(sc->sc_dev, "could not load 8051 microcode\n"); goto fail; } for (ntries = 0; ntries < 100; ntries++) { if (run_read(sc, RT2860_ASIC_VER_ID, &tmp) != 0) goto fail; if (tmp != 0 && tmp != 0xffffffff) break; run_delay(sc, 10); } if (ntries == 100) goto fail; for (i = 0; i != RUN_EP_QUEUES; i++) run_setup_tx_list(sc, &sc->sc_epq[i]); run_set_macaddr(sc, IF_LLADDR(ifp)); for (ntries = 0; ntries < 100; ntries++) { if (run_read(sc, RT2860_WPDMA_GLO_CFG, &tmp) != 0) goto fail; if ((tmp & (RT2860_TX_DMA_BUSY | RT2860_RX_DMA_BUSY)) == 0) break; run_delay(sc, 10); } if (ntries == 100) { device_printf(sc->sc_dev, "timeout waiting for DMA engine\n"); goto fail; } tmp &= 0xff0; tmp |= RT2860_TX_WB_DDONE; run_write(sc, RT2860_WPDMA_GLO_CFG, tmp); /* turn off PME_OEN to solve high-current issue */ run_read(sc, RT2860_SYS_CTRL, &tmp); run_write(sc, RT2860_SYS_CTRL, tmp & ~RT2860_PME_OEN); run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_BBP_HRST | RT2860_MAC_SRST); run_write(sc, RT2860_USB_DMA_CFG, 0); if (run_reset(sc) != 0) { device_printf(sc->sc_dev, "could not reset chipset\n"); goto fail; } run_write(sc, RT2860_MAC_SYS_CTRL, 0); /* init Tx power for all Tx rates (from EEPROM) */ for (ridx = 0; ridx < 5; ridx++) { if (sc->txpow20mhz[ridx] == 0xffffffff) continue; run_write(sc, RT2860_TX_PWR_CFG(ridx), sc->txpow20mhz[ridx]); } for (i = 0; i < nitems(rt2870_def_mac); i++) run_write(sc, rt2870_def_mac[i].reg, rt2870_def_mac[i].val); run_write(sc, RT2860_WMM_AIFSN_CFG, 0x00002273); run_write(sc, RT2860_WMM_CWMIN_CFG, 0x00002344); run_write(sc, RT2860_WMM_CWMAX_CFG, 0x000034aa); if (sc->mac_ver >= 0x5390) { run_write(sc, RT2860_TX_SW_CFG0, 4 << RT2860_DLY_PAPE_EN_SHIFT | 4); if (sc->mac_ver >= 0x5392) { run_write(sc, RT2860_MAX_LEN_CFG, 0x00002fff); if (sc->mac_ver == 0x5592) { run_write(sc, RT2860_HT_FBK_CFG1, 0xedcba980); run_write(sc, RT2860_TXOP_HLDR_ET, 0x00000082); } else { run_write(sc, RT2860_HT_FBK_CFG1, 0xedcb4980); run_write(sc, RT2860_LG_FBK_CFG0, 0xedcba322); } } } else if (sc->mac_ver == 0x3593) { run_write(sc, RT2860_TX_SW_CFG0, 4 << RT2860_DLY_PAPE_EN_SHIFT | 2); } else if (sc->mac_ver >= 0x3070) { /* set delay of PA_PE assertion to 1us (unit of 0.25us) */ run_write(sc, RT2860_TX_SW_CFG0, 4 << RT2860_DLY_PAPE_EN_SHIFT); } /* wait while MAC is busy */ for (ntries = 0; ntries < 100; ntries++) { if (run_read(sc, RT2860_MAC_STATUS_REG, &tmp) != 0) goto fail; if (!(tmp & (RT2860_RX_STATUS_BUSY | RT2860_TX_STATUS_BUSY))) break; run_delay(sc, 10); } if (ntries == 100) goto fail; /* clear Host to MCU mailbox */ run_write(sc, RT2860_H2M_BBPAGENT, 0); run_write(sc, RT2860_H2M_MAILBOX, 0); run_delay(sc, 10); if (run_bbp_init(sc) != 0) { device_printf(sc->sc_dev, "could not initialize BBP\n"); goto fail; } /* abort TSF synchronization */ run_read(sc, RT2860_BCN_TIME_CFG, &tmp); tmp &= ~(RT2860_BCN_TX_EN | RT2860_TSF_TIMER_EN | RT2860_TBTT_TIMER_EN); run_write(sc, RT2860_BCN_TIME_CFG, tmp); /* clear RX WCID search table */ run_set_region_4(sc, RT2860_WCID_ENTRY(0), 0, 512); /* clear WCID attribute table */ run_set_region_4(sc, RT2860_WCID_ATTR(0), 0, 8 * 32); /* hostapd sets a key before init. So, don't clear it. */ if (sc->cmdq_key_set != RUN_CMDQ_GO) { /* clear shared key table */ run_set_region_4(sc, RT2860_SKEY(0, 0), 0, 8 * 32); /* clear shared key mode */ run_set_region_4(sc, RT2860_SKEY_MODE_0_7, 0, 4); } run_read(sc, RT2860_US_CYC_CNT, &tmp); tmp = (tmp & ~0xff) | 0x1e; run_write(sc, RT2860_US_CYC_CNT, tmp); if (sc->mac_rev != 0x0101) run_write(sc, RT2860_TXOP_CTRL_CFG, 0x0000583f); run_write(sc, RT2860_WMM_TXOP0_CFG, 0); run_write(sc, RT2860_WMM_TXOP1_CFG, 48 << 16 | 96); /* write vendor-specific BBP values (from EEPROM) */ if (sc->mac_ver < 0x3593) { for (i = 0; i < 10; i++) { if (sc->bbp[i].reg == 0 || sc->bbp[i].reg == 0xff) continue; run_bbp_write(sc, sc->bbp[i].reg, sc->bbp[i].val); } } /* select Main antenna for 1T1R devices */ if (sc->rf_rev == RT3070_RF_3020 || sc->rf_rev == RT5390_RF_5370) run_set_rx_antenna(sc, 0); /* send LEDs operating mode to microcontroller */ (void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED1, sc->led[0]); (void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED2, sc->led[1]); (void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED3, sc->led[2]); if (sc->mac_ver >= 0x5390) run_rt5390_rf_init(sc); else if (sc->mac_ver == 0x3593) run_rt3593_rf_init(sc); else if (sc->mac_ver >= 0x3070) run_rt3070_rf_init(sc); /* disable non-existing Rx chains */ run_bbp_read(sc, 3, &bbp3); bbp3 &= ~(1 << 3 | 1 << 4); if (sc->nrxchains == 2) bbp3 |= 1 << 3; else if (sc->nrxchains == 3) bbp3 |= 1 << 4; run_bbp_write(sc, 3, bbp3); /* disable non-existing Tx chains */ run_bbp_read(sc, 1, &bbp1); if (sc->ntxchains == 1) bbp1 &= ~(1 << 3 | 1 << 4); run_bbp_write(sc, 1, bbp1); if (sc->mac_ver >= 0x5390) run_rt5390_rf_setup(sc); else if (sc->mac_ver == 0x3593) run_rt3593_rf_setup(sc); else if (sc->mac_ver >= 0x3070) run_rt3070_rf_setup(sc); /* select default channel */ run_set_chan(sc, ic->ic_curchan); /* setup initial protection mode */ run_updateprot_cb(ic); /* turn radio LED on */ run_set_leds(sc, RT2860_LED_RADIO); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; ifp->if_drv_flags |= IFF_DRV_RUNNING; sc->cmdq_run = RUN_CMDQ_GO; for (i = 0; i != RUN_N_XFER; i++) usbd_xfer_set_stall(sc->sc_xfer[i]); usbd_transfer_start(sc->sc_xfer[RUN_BULK_RX]); if (run_txrx_enable(sc) != 0) goto fail; return; fail: run_stop(sc); } static void run_init(void *arg) { struct run_softc *sc = arg; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; RUN_LOCK(sc); run_init_locked(sc); RUN_UNLOCK(sc); if (ifp->if_drv_flags & IFF_DRV_RUNNING) ieee80211_start_all(ic); } static void run_stop(void *arg) { struct run_softc *sc = (struct run_softc *)arg; struct ifnet *ifp = sc->sc_ifp; uint32_t tmp; int i; int ntries; RUN_LOCK_ASSERT(sc, MA_OWNED); if (ifp->if_drv_flags & IFF_DRV_RUNNING) run_set_leds(sc, 0); /* turn all LEDs off */ ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); sc->ratectl_run = RUN_RATECTL_OFF; sc->cmdq_run = sc->cmdq_key_set; RUN_UNLOCK(sc); for(i = 0; i < RUN_N_XFER; i++) usbd_transfer_drain(sc->sc_xfer[i]); RUN_LOCK(sc); if (sc->rx_m != NULL) { m_free(sc->rx_m); sc->rx_m = NULL; } /* Disable Tx/Rx DMA. */ if (run_read(sc, RT2860_WPDMA_GLO_CFG, &tmp) != 0) return; tmp &= ~(RT2860_RX_DMA_EN | RT2860_TX_DMA_EN); run_write(sc, RT2860_WPDMA_GLO_CFG, tmp); for (ntries = 0; ntries < 100; ntries++) { if (run_read(sc, RT2860_WPDMA_GLO_CFG, &tmp) != 0) return; if ((tmp & (RT2860_TX_DMA_BUSY | RT2860_RX_DMA_BUSY)) == 0) break; run_delay(sc, 10); } if (ntries == 100) { device_printf(sc->sc_dev, "timeout waiting for DMA engine\n"); return; } /* disable Tx/Rx */ run_read(sc, RT2860_MAC_SYS_CTRL, &tmp); tmp &= ~(RT2860_MAC_RX_EN | RT2860_MAC_TX_EN); run_write(sc, RT2860_MAC_SYS_CTRL, tmp); /* wait for pending Tx to complete */ for (ntries = 0; ntries < 100; ntries++) { if (run_read(sc, RT2860_TXRXQ_PCNT, &tmp) != 0) { DPRINTF("Cannot read Tx queue count\n"); break; } if ((tmp & RT2860_TX2Q_PCNT_MASK) == 0) { DPRINTF("All Tx cleared\n"); break; } run_delay(sc, 10); } if (ntries >= 100) DPRINTF("There are still pending Tx\n"); run_delay(sc, 10); run_write(sc, RT2860_USB_DMA_CFG, 0); run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_BBP_HRST | RT2860_MAC_SRST); run_write(sc, RT2860_MAC_SYS_CTRL, 0); for (i = 0; i != RUN_EP_QUEUES; i++) run_unsetup_tx_list(sc, &sc->sc_epq[i]); } static void run_delay(struct run_softc *sc, u_int ms) { usb_pause_mtx(mtx_owned(&sc->sc_mtx) ? &sc->sc_mtx : NULL, USB_MS_TO_TICKS(ms)); } static device_method_t run_methods[] = { /* Device interface */ DEVMETHOD(device_probe, run_match), DEVMETHOD(device_attach, run_attach), DEVMETHOD(device_detach, run_detach), DEVMETHOD_END }; static driver_t run_driver = { .name = "run", .methods = run_methods, .size = sizeof(struct run_softc) }; static devclass_t run_devclass; DRIVER_MODULE(run, uhub, run_driver, run_devclass, run_driver_loaded, NULL); MODULE_DEPEND(run, wlan, 1, 1, 1); MODULE_DEPEND(run, usb, 1, 1, 1); MODULE_DEPEND(run, firmware, 1, 1, 1); MODULE_VERSION(run, 1); Index: head/sys/dev/usb/wlan/if_ural.c =================================================================== --- head/sys/dev/usb/wlan/if_ural.c (revision 276700) +++ head/sys/dev/usb/wlan/if_ural.c (revision 276701) @@ -1,2300 +1,2300 @@ /* $FreeBSD$ */ /*- * Copyright (c) 2005, 2006 * Damien Bergamini * * Copyright (c) 2006, 2008 * Hans Petter Selasky * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include __FBSDID("$FreeBSD$"); /*- * Ralink Technology RT2500USB chipset driver * http://www.ralinktech.com/ */ #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 #ifdef INET #include #include #include #include #include #endif #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR ural_debug #include #include #include #ifdef USB_DEBUG static int ural_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, ural, CTLFLAG_RW, 0, "USB ural"); -SYSCTL_INT(_hw_usb_ural, OID_AUTO, debug, CTLFLAG_RW, &ural_debug, 0, +SYSCTL_INT(_hw_usb_ural, OID_AUTO, debug, CTLFLAG_RWTUN, &ural_debug, 0, "Debug level"); #endif #define URAL_RSSI(rssi) \ ((rssi) > (RAL_NOISE_FLOOR + RAL_RSSI_CORR) ? \ ((rssi) - (RAL_NOISE_FLOOR + RAL_RSSI_CORR)) : 0) /* various supported device vendors/products */ static const STRUCT_USB_HOST_ID ural_devs[] = { #define URAL_DEV(v,p) { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) } URAL_DEV(ASUS, WL167G), URAL_DEV(ASUS, RT2570), URAL_DEV(BELKIN, F5D7050), URAL_DEV(BELKIN, F5D7051), URAL_DEV(CISCOLINKSYS, HU200TS), URAL_DEV(CISCOLINKSYS, WUSB54G), URAL_DEV(CISCOLINKSYS, WUSB54GP), URAL_DEV(CONCEPTRONIC2, C54RU), URAL_DEV(DLINK, DWLG122), URAL_DEV(GIGABYTE, GN54G), URAL_DEV(GIGABYTE, GNWBKG), URAL_DEV(GUILLEMOT, HWGUSB254), URAL_DEV(MELCO, KG54), URAL_DEV(MELCO, KG54AI), URAL_DEV(MELCO, KG54YB), URAL_DEV(MELCO, NINWIFI), URAL_DEV(MSI, RT2570), URAL_DEV(MSI, RT2570_2), URAL_DEV(MSI, RT2570_3), URAL_DEV(NOVATECH, NV902), URAL_DEV(RALINK, RT2570), URAL_DEV(RALINK, RT2570_2), URAL_DEV(RALINK, RT2570_3), URAL_DEV(SIEMENS2, WL54G), URAL_DEV(SMC, 2862WG), URAL_DEV(SPHAIRON, UB801R), URAL_DEV(SURECOM, RT2570), URAL_DEV(VTECH, RT2570), URAL_DEV(ZINWELL, RT2570), #undef URAL_DEV }; static usb_callback_t ural_bulk_read_callback; static usb_callback_t ural_bulk_write_callback; static usb_error_t ural_do_request(struct ural_softc *sc, struct usb_device_request *req, void *data); static struct ieee80211vap *ural_vap_create(struct ieee80211com *, const char [IFNAMSIZ], int, enum ieee80211_opmode, int, const uint8_t [IEEE80211_ADDR_LEN], const uint8_t [IEEE80211_ADDR_LEN]); static void ural_vap_delete(struct ieee80211vap *); static void ural_tx_free(struct ural_tx_data *, int); static void ural_setup_tx_list(struct ural_softc *); static void ural_unsetup_tx_list(struct ural_softc *); static int ural_newstate(struct ieee80211vap *, enum ieee80211_state, int); static void ural_setup_tx_desc(struct ural_softc *, struct ural_tx_desc *, uint32_t, int, int); static int ural_tx_bcn(struct ural_softc *, struct mbuf *, struct ieee80211_node *); static int ural_tx_mgt(struct ural_softc *, struct mbuf *, struct ieee80211_node *); static int ural_tx_data(struct ural_softc *, struct mbuf *, struct ieee80211_node *); static void ural_start(struct ifnet *); static int ural_ioctl(struct ifnet *, u_long, caddr_t); static void ural_set_testmode(struct ural_softc *); static void ural_eeprom_read(struct ural_softc *, uint16_t, void *, int); static uint16_t ural_read(struct ural_softc *, uint16_t); static void ural_read_multi(struct ural_softc *, uint16_t, void *, int); static void ural_write(struct ural_softc *, uint16_t, uint16_t); static void ural_write_multi(struct ural_softc *, uint16_t, void *, int) __unused; static void ural_bbp_write(struct ural_softc *, uint8_t, uint8_t); static uint8_t ural_bbp_read(struct ural_softc *, uint8_t); static void ural_rf_write(struct ural_softc *, uint8_t, uint32_t); static void ural_scan_start(struct ieee80211com *); static void ural_scan_end(struct ieee80211com *); static void ural_set_channel(struct ieee80211com *); static void ural_set_chan(struct ural_softc *, struct ieee80211_channel *); static void ural_disable_rf_tune(struct ural_softc *); static void ural_enable_tsf_sync(struct ural_softc *); static void ural_enable_tsf(struct ural_softc *); static void ural_update_slot(struct ifnet *); static void ural_set_txpreamble(struct ural_softc *); static void ural_set_basicrates(struct ural_softc *, const struct ieee80211_channel *); static void ural_set_bssid(struct ural_softc *, const uint8_t *); static void ural_set_macaddr(struct ural_softc *, uint8_t *); static void ural_update_promisc(struct ifnet *); static void ural_setpromisc(struct ural_softc *); static const char *ural_get_rf(int); static void ural_read_eeprom(struct ural_softc *); static int ural_bbp_init(struct ural_softc *); static void ural_set_txantenna(struct ural_softc *, int); static void ural_set_rxantenna(struct ural_softc *, int); static void ural_init_locked(struct ural_softc *); static void ural_init(void *); static void ural_stop(struct ural_softc *); static int ural_raw_xmit(struct ieee80211_node *, struct mbuf *, const struct ieee80211_bpf_params *); static void ural_ratectl_start(struct ural_softc *, struct ieee80211_node *); static void ural_ratectl_timeout(void *); static void ural_ratectl_task(void *, int); static int ural_pause(struct ural_softc *sc, int timeout); /* * Default values for MAC registers; values taken from the reference driver. */ static const struct { uint16_t reg; uint16_t val; } ural_def_mac[] = { { RAL_TXRX_CSR5, 0x8c8d }, { RAL_TXRX_CSR6, 0x8b8a }, { RAL_TXRX_CSR7, 0x8687 }, { RAL_TXRX_CSR8, 0x0085 }, { RAL_MAC_CSR13, 0x1111 }, { RAL_MAC_CSR14, 0x1e11 }, { RAL_TXRX_CSR21, 0xe78f }, { RAL_MAC_CSR9, 0xff1d }, { RAL_MAC_CSR11, 0x0002 }, { RAL_MAC_CSR22, 0x0053 }, { RAL_MAC_CSR15, 0x0000 }, { RAL_MAC_CSR8, RAL_FRAME_SIZE }, { RAL_TXRX_CSR19, 0x0000 }, { RAL_TXRX_CSR18, 0x005a }, { RAL_PHY_CSR2, 0x0000 }, { RAL_TXRX_CSR0, 0x1ec0 }, { RAL_PHY_CSR4, 0x000f } }; /* * Default values for BBP registers; values taken from the reference driver. */ static const struct { uint8_t reg; uint8_t val; } ural_def_bbp[] = { { 3, 0x02 }, { 4, 0x19 }, { 14, 0x1c }, { 15, 0x30 }, { 16, 0xac }, { 17, 0x48 }, { 18, 0x18 }, { 19, 0xff }, { 20, 0x1e }, { 21, 0x08 }, { 22, 0x08 }, { 23, 0x08 }, { 24, 0x80 }, { 25, 0x50 }, { 26, 0x08 }, { 27, 0x23 }, { 30, 0x10 }, { 31, 0x2b }, { 32, 0xb9 }, { 34, 0x12 }, { 35, 0x50 }, { 39, 0xc4 }, { 40, 0x02 }, { 41, 0x60 }, { 53, 0x10 }, { 54, 0x18 }, { 56, 0x08 }, { 57, 0x10 }, { 58, 0x08 }, { 61, 0x60 }, { 62, 0x10 }, { 75, 0xff } }; /* * Default values for RF register R2 indexed by channel numbers. */ static const uint32_t ural_rf2522_r2[] = { 0x307f6, 0x307fb, 0x30800, 0x30805, 0x3080a, 0x3080f, 0x30814, 0x30819, 0x3081e, 0x30823, 0x30828, 0x3082d, 0x30832, 0x3083e }; static const uint32_t ural_rf2523_r2[] = { 0x00327, 0x00328, 0x00329, 0x0032a, 0x0032b, 0x0032c, 0x0032d, 0x0032e, 0x0032f, 0x00340, 0x00341, 0x00342, 0x00343, 0x00346 }; static const uint32_t ural_rf2524_r2[] = { 0x00327, 0x00328, 0x00329, 0x0032a, 0x0032b, 0x0032c, 0x0032d, 0x0032e, 0x0032f, 0x00340, 0x00341, 0x00342, 0x00343, 0x00346 }; static const uint32_t ural_rf2525_r2[] = { 0x20327, 0x20328, 0x20329, 0x2032a, 0x2032b, 0x2032c, 0x2032d, 0x2032e, 0x2032f, 0x20340, 0x20341, 0x20342, 0x20343, 0x20346 }; static const uint32_t ural_rf2525_hi_r2[] = { 0x2032f, 0x20340, 0x20341, 0x20342, 0x20343, 0x20344, 0x20345, 0x20346, 0x20347, 0x20348, 0x20349, 0x2034a, 0x2034b, 0x2034e }; static const uint32_t ural_rf2525e_r2[] = { 0x2044d, 0x2044e, 0x2044f, 0x20460, 0x20461, 0x20462, 0x20463, 0x20464, 0x20465, 0x20466, 0x20467, 0x20468, 0x20469, 0x2046b }; static const uint32_t ural_rf2526_hi_r2[] = { 0x0022a, 0x0022b, 0x0022b, 0x0022c, 0x0022c, 0x0022d, 0x0022d, 0x0022e, 0x0022e, 0x0022f, 0x0022d, 0x00240, 0x00240, 0x00241 }; static const uint32_t ural_rf2526_r2[] = { 0x00226, 0x00227, 0x00227, 0x00228, 0x00228, 0x00229, 0x00229, 0x0022a, 0x0022a, 0x0022b, 0x0022b, 0x0022c, 0x0022c, 0x0022d }; /* * For dual-band RF, RF registers R1 and R4 also depend on channel number; * values taken from the reference driver. */ static const struct { uint8_t chan; uint32_t r1; uint32_t r2; uint32_t r4; } ural_rf5222[] = { { 1, 0x08808, 0x0044d, 0x00282 }, { 2, 0x08808, 0x0044e, 0x00282 }, { 3, 0x08808, 0x0044f, 0x00282 }, { 4, 0x08808, 0x00460, 0x00282 }, { 5, 0x08808, 0x00461, 0x00282 }, { 6, 0x08808, 0x00462, 0x00282 }, { 7, 0x08808, 0x00463, 0x00282 }, { 8, 0x08808, 0x00464, 0x00282 }, { 9, 0x08808, 0x00465, 0x00282 }, { 10, 0x08808, 0x00466, 0x00282 }, { 11, 0x08808, 0x00467, 0x00282 }, { 12, 0x08808, 0x00468, 0x00282 }, { 13, 0x08808, 0x00469, 0x00282 }, { 14, 0x08808, 0x0046b, 0x00286 }, { 36, 0x08804, 0x06225, 0x00287 }, { 40, 0x08804, 0x06226, 0x00287 }, { 44, 0x08804, 0x06227, 0x00287 }, { 48, 0x08804, 0x06228, 0x00287 }, { 52, 0x08804, 0x06229, 0x00287 }, { 56, 0x08804, 0x0622a, 0x00287 }, { 60, 0x08804, 0x0622b, 0x00287 }, { 64, 0x08804, 0x0622c, 0x00287 }, { 100, 0x08804, 0x02200, 0x00283 }, { 104, 0x08804, 0x02201, 0x00283 }, { 108, 0x08804, 0x02202, 0x00283 }, { 112, 0x08804, 0x02203, 0x00283 }, { 116, 0x08804, 0x02204, 0x00283 }, { 120, 0x08804, 0x02205, 0x00283 }, { 124, 0x08804, 0x02206, 0x00283 }, { 128, 0x08804, 0x02207, 0x00283 }, { 132, 0x08804, 0x02208, 0x00283 }, { 136, 0x08804, 0x02209, 0x00283 }, { 140, 0x08804, 0x0220a, 0x00283 }, { 149, 0x08808, 0x02429, 0x00281 }, { 153, 0x08808, 0x0242b, 0x00281 }, { 157, 0x08808, 0x0242d, 0x00281 }, { 161, 0x08808, 0x0242f, 0x00281 } }; static const struct usb_config ural_config[URAL_N_TRANSFER] = { [URAL_BULK_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = (RAL_FRAME_SIZE + RAL_TX_DESC_SIZE + 4), .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = ural_bulk_write_callback, .timeout = 5000, /* ms */ }, [URAL_BULK_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = (RAL_FRAME_SIZE + RAL_RX_DESC_SIZE), .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = ural_bulk_read_callback, }, }; static device_probe_t ural_match; static device_attach_t ural_attach; static device_detach_t ural_detach; static device_method_t ural_methods[] = { /* Device interface */ DEVMETHOD(device_probe, ural_match), DEVMETHOD(device_attach, ural_attach), DEVMETHOD(device_detach, ural_detach), DEVMETHOD_END }; static driver_t ural_driver = { .name = "ural", .methods = ural_methods, .size = sizeof(struct ural_softc), }; static devclass_t ural_devclass; DRIVER_MODULE(ural, uhub, ural_driver, ural_devclass, NULL, 0); MODULE_DEPEND(ural, usb, 1, 1, 1); MODULE_DEPEND(ural, wlan, 1, 1, 1); MODULE_VERSION(ural, 1); static int ural_match(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != 0) return (ENXIO); if (uaa->info.bIfaceIndex != RAL_IFACE_INDEX) return (ENXIO); return (usbd_lookup_id_by_uaa(ural_devs, sizeof(ural_devs), uaa)); } static int ural_attach(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); struct ural_softc *sc = device_get_softc(self); struct ifnet *ifp; struct ieee80211com *ic; uint8_t iface_index, bands; int error; device_set_usb_desc(self); sc->sc_udev = uaa->device; sc->sc_dev = self; mtx_init(&sc->sc_mtx, device_get_nameunit(self), MTX_NETWORK_LOCK, MTX_DEF); iface_index = RAL_IFACE_INDEX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, ural_config, URAL_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(self, "could not allocate USB transfers, " "err=%s\n", usbd_errstr(error)); goto detach; } RAL_LOCK(sc); /* retrieve RT2570 rev. no */ sc->asic_rev = ural_read(sc, RAL_MAC_CSR0); /* retrieve MAC address and various other things from EEPROM */ ural_read_eeprom(sc); RAL_UNLOCK(sc); device_printf(self, "MAC/BBP RT2570 (rev 0x%02x), RF %s\n", sc->asic_rev, ural_get_rf(sc->rf_rev)); ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211); if (ifp == NULL) { device_printf(sc->sc_dev, "can not if_alloc()\n"); goto detach; } ic = ifp->if_l2com; ifp->if_softc = sc; if_initname(ifp, "ural", device_get_unit(sc->sc_dev)); ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; ifp->if_init = ural_init; ifp->if_ioctl = ural_ioctl; ifp->if_start = ural_start; IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen); ifp->if_snd.ifq_drv_maxlen = ifqmaxlen; IFQ_SET_READY(&ifp->if_snd); ic->ic_ifp = ifp; ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */ /* set device capabilities */ ic->ic_caps = IEEE80211_C_STA /* station mode supported */ | IEEE80211_C_IBSS /* IBSS mode supported */ | IEEE80211_C_MONITOR /* monitor mode supported */ | IEEE80211_C_HOSTAP /* HostAp mode supported */ | IEEE80211_C_TXPMGT /* tx power management */ | IEEE80211_C_SHPREAMBLE /* short preamble supported */ | IEEE80211_C_SHSLOT /* short slot time supported */ | IEEE80211_C_BGSCAN /* bg scanning supported */ | IEEE80211_C_WPA /* 802.11i */ ; bands = 0; setbit(&bands, IEEE80211_MODE_11B); setbit(&bands, IEEE80211_MODE_11G); if (sc->rf_rev == RAL_RF_5222) setbit(&bands, IEEE80211_MODE_11A); ieee80211_init_channels(ic, NULL, &bands); ieee80211_ifattach(ic, sc->sc_bssid); ic->ic_update_promisc = ural_update_promisc; ic->ic_raw_xmit = ural_raw_xmit; ic->ic_scan_start = ural_scan_start; ic->ic_scan_end = ural_scan_end; ic->ic_set_channel = ural_set_channel; ic->ic_vap_create = ural_vap_create; ic->ic_vap_delete = ural_vap_delete; ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap), RAL_TX_RADIOTAP_PRESENT, &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap), RAL_RX_RADIOTAP_PRESENT); if (bootverbose) ieee80211_announce(ic); return (0); detach: ural_detach(self); return (ENXIO); /* failure */ } static int ural_detach(device_t self) { struct ural_softc *sc = device_get_softc(self); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic; /* prevent further ioctls */ RAL_LOCK(sc); sc->sc_detached = 1; RAL_UNLOCK(sc); /* stop all USB transfers */ usbd_transfer_unsetup(sc->sc_xfer, URAL_N_TRANSFER); /* free TX list, if any */ RAL_LOCK(sc); ural_unsetup_tx_list(sc); RAL_UNLOCK(sc); if (ifp) { ic = ifp->if_l2com; ieee80211_ifdetach(ic); if_free(ifp); } mtx_destroy(&sc->sc_mtx); return (0); } static usb_error_t ural_do_request(struct ural_softc *sc, struct usb_device_request *req, void *data) { usb_error_t err; int ntries = 10; while (ntries--) { err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx, req, data, 0, NULL, 250 /* ms */); if (err == 0) break; DPRINTFN(1, "Control request failed, %s (retrying)\n", usbd_errstr(err)); if (ural_pause(sc, hz / 100)) break; } return (err); } static struct ieee80211vap * ural_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit, enum ieee80211_opmode opmode, int flags, const uint8_t bssid[IEEE80211_ADDR_LEN], const uint8_t mac[IEEE80211_ADDR_LEN]) { struct ural_softc *sc = ic->ic_ifp->if_softc; struct ural_vap *uvp; struct ieee80211vap *vap; if (!TAILQ_EMPTY(&ic->ic_vaps)) /* only one at a time */ return NULL; uvp = (struct ural_vap *) malloc(sizeof(struct ural_vap), M_80211_VAP, M_NOWAIT | M_ZERO); if (uvp == NULL) return NULL; vap = &uvp->vap; /* enable s/w bmiss handling for sta mode */ if (ieee80211_vap_setup(ic, vap, name, unit, opmode, flags | IEEE80211_CLONE_NOBEACONS, bssid, mac) != 0) { /* out of memory */ free(uvp, M_80211_VAP); return (NULL); } /* override state transition machine */ uvp->newstate = vap->iv_newstate; vap->iv_newstate = ural_newstate; usb_callout_init_mtx(&uvp->ratectl_ch, &sc->sc_mtx, 0); TASK_INIT(&uvp->ratectl_task, 0, ural_ratectl_task, uvp); ieee80211_ratectl_init(vap); ieee80211_ratectl_setinterval(vap, 1000 /* 1 sec */); /* complete setup */ ieee80211_vap_attach(vap, ieee80211_media_change, ieee80211_media_status); ic->ic_opmode = opmode; return vap; } static void ural_vap_delete(struct ieee80211vap *vap) { struct ural_vap *uvp = URAL_VAP(vap); struct ieee80211com *ic = vap->iv_ic; usb_callout_drain(&uvp->ratectl_ch); ieee80211_draintask(ic, &uvp->ratectl_task); ieee80211_ratectl_deinit(vap); ieee80211_vap_detach(vap); free(uvp, M_80211_VAP); } static void ural_tx_free(struct ural_tx_data *data, int txerr) { struct ural_softc *sc = data->sc; if (data->m != NULL) { if (data->m->m_flags & M_TXCB) ieee80211_process_callback(data->ni, data->m, txerr ? ETIMEDOUT : 0); m_freem(data->m); data->m = NULL; ieee80211_free_node(data->ni); data->ni = NULL; } STAILQ_INSERT_TAIL(&sc->tx_free, data, next); sc->tx_nfree++; } static void ural_setup_tx_list(struct ural_softc *sc) { struct ural_tx_data *data; int i; sc->tx_nfree = 0; STAILQ_INIT(&sc->tx_q); STAILQ_INIT(&sc->tx_free); for (i = 0; i < RAL_TX_LIST_COUNT; i++) { data = &sc->tx_data[i]; data->sc = sc; STAILQ_INSERT_TAIL(&sc->tx_free, data, next); sc->tx_nfree++; } } static void ural_unsetup_tx_list(struct ural_softc *sc) { struct ural_tx_data *data; int i; /* make sure any subsequent use of the queues will fail */ sc->tx_nfree = 0; STAILQ_INIT(&sc->tx_q); STAILQ_INIT(&sc->tx_free); /* free up all node references and mbufs */ for (i = 0; i < RAL_TX_LIST_COUNT; i++) { data = &sc->tx_data[i]; if (data->m != NULL) { m_freem(data->m); data->m = NULL; } if (data->ni != NULL) { ieee80211_free_node(data->ni); data->ni = NULL; } } } static int ural_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg) { struct ural_vap *uvp = URAL_VAP(vap); struct ieee80211com *ic = vap->iv_ic; struct ural_softc *sc = ic->ic_ifp->if_softc; const struct ieee80211_txparam *tp; struct ieee80211_node *ni; struct mbuf *m; DPRINTF("%s -> %s\n", ieee80211_state_name[vap->iv_state], ieee80211_state_name[nstate]); IEEE80211_UNLOCK(ic); RAL_LOCK(sc); usb_callout_stop(&uvp->ratectl_ch); switch (nstate) { case IEEE80211_S_INIT: if (vap->iv_state == IEEE80211_S_RUN) { /* abort TSF synchronization */ ural_write(sc, RAL_TXRX_CSR19, 0); /* force tx led to stop blinking */ ural_write(sc, RAL_MAC_CSR20, 0); } break; case IEEE80211_S_RUN: ni = ieee80211_ref_node(vap->iv_bss); if (vap->iv_opmode != IEEE80211_M_MONITOR) { if (ic->ic_bsschan == IEEE80211_CHAN_ANYC) { RAL_UNLOCK(sc); IEEE80211_LOCK(ic); ieee80211_free_node(ni); return (-1); } ural_update_slot(ic->ic_ifp); ural_set_txpreamble(sc); ural_set_basicrates(sc, ic->ic_bsschan); IEEE80211_ADDR_COPY(sc->sc_bssid, ni->ni_bssid); ural_set_bssid(sc, sc->sc_bssid); } if (vap->iv_opmode == IEEE80211_M_HOSTAP || vap->iv_opmode == IEEE80211_M_IBSS) { m = ieee80211_beacon_alloc(ni, &uvp->bo); if (m == NULL) { device_printf(sc->sc_dev, "could not allocate beacon\n"); RAL_UNLOCK(sc); IEEE80211_LOCK(ic); ieee80211_free_node(ni); return (-1); } ieee80211_ref_node(ni); if (ural_tx_bcn(sc, m, ni) != 0) { device_printf(sc->sc_dev, "could not send beacon\n"); RAL_UNLOCK(sc); IEEE80211_LOCK(ic); ieee80211_free_node(ni); return (-1); } } /* make tx led blink on tx (controlled by ASIC) */ ural_write(sc, RAL_MAC_CSR20, 1); if (vap->iv_opmode != IEEE80211_M_MONITOR) ural_enable_tsf_sync(sc); else ural_enable_tsf(sc); /* enable automatic rate adaptation */ /* XXX should use ic_bsschan but not valid until after newstate call below */ tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)]; if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE) ural_ratectl_start(sc, ni); ieee80211_free_node(ni); break; default: break; } RAL_UNLOCK(sc); IEEE80211_LOCK(ic); return (uvp->newstate(vap, nstate, arg)); } static void ural_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct ural_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct ieee80211vap *vap; struct ural_tx_data *data; struct mbuf *m; struct usb_page_cache *pc; int len; usbd_xfer_status(xfer, &len, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(11, "transfer complete, %d bytes\n", len); /* free resources */ data = usbd_xfer_get_priv(xfer); ural_tx_free(data, 0); usbd_xfer_set_priv(xfer, NULL); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: data = STAILQ_FIRST(&sc->tx_q); if (data) { STAILQ_REMOVE_HEAD(&sc->tx_q, next); m = data->m; if (m->m_pkthdr.len > (int)(RAL_FRAME_SIZE + RAL_TX_DESC_SIZE)) { DPRINTFN(0, "data overflow, %u bytes\n", m->m_pkthdr.len); m->m_pkthdr.len = (RAL_FRAME_SIZE + RAL_TX_DESC_SIZE); } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, &data->desc, RAL_TX_DESC_SIZE); usbd_m_copy_in(pc, RAL_TX_DESC_SIZE, m, 0, m->m_pkthdr.len); vap = data->ni->ni_vap; if (ieee80211_radiotap_active_vap(vap)) { struct ural_tx_radiotap_header *tap = &sc->sc_txtap; tap->wt_flags = 0; tap->wt_rate = data->rate; tap->wt_antenna = sc->tx_ant; ieee80211_radiotap_tx(vap, m); } /* xfer length needs to be a multiple of two! */ len = (RAL_TX_DESC_SIZE + m->m_pkthdr.len + 1) & ~1; if ((len % 64) == 0) len += 2; DPRINTFN(11, "sending frame len=%u xferlen=%u\n", m->m_pkthdr.len, len); usbd_xfer_set_frame_len(xfer, 0, len); usbd_xfer_set_priv(xfer, data); usbd_transfer_submit(xfer); } RAL_UNLOCK(sc); ural_start(ifp); RAL_LOCK(sc); break; default: /* Error */ DPRINTFN(11, "transfer error, %s\n", usbd_errstr(error)); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); data = usbd_xfer_get_priv(xfer); if (data != NULL) { ural_tx_free(data, error); usbd_xfer_set_priv(xfer, NULL); } if (error == USB_ERR_STALLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } if (error == USB_ERR_TIMEOUT) device_printf(sc->sc_dev, "device timeout\n"); break; } } static void ural_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct ural_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211_node *ni; struct mbuf *m = NULL; struct usb_page_cache *pc; uint32_t flags; int8_t rssi = 0, nf = 0; int len; usbd_xfer_status(xfer, &len, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTFN(15, "rx done, actlen=%d\n", len); if (len < (int)(RAL_RX_DESC_SIZE + IEEE80211_MIN_LEN)) { DPRINTF("%s: xfer too short %d\n", device_get_nameunit(sc->sc_dev), len); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } len -= RAL_RX_DESC_SIZE; /* rx descriptor is located at the end */ pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, len, &sc->sc_rx_desc, RAL_RX_DESC_SIZE); rssi = URAL_RSSI(sc->sc_rx_desc.rssi); nf = RAL_NOISE_FLOOR; flags = le32toh(sc->sc_rx_desc.flags); if (flags & (RAL_RX_PHY_ERROR | RAL_RX_CRC_ERROR)) { /* * This should not happen since we did not * request to receive those frames when we * filled RAL_TXRX_CSR2: */ DPRINTFN(5, "PHY or CRC error\n"); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); if (m == NULL) { DPRINTF("could not allocate mbuf\n"); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } usbd_copy_out(pc, 0, mtod(m, uint8_t *), len); /* finalize mbuf */ m->m_pkthdr.rcvif = ifp; m->m_pkthdr.len = m->m_len = (flags >> 16) & 0xfff; if (ieee80211_radiotap_active(ic)) { struct ural_rx_radiotap_header *tap = &sc->sc_rxtap; /* XXX set once */ tap->wr_flags = 0; tap->wr_rate = ieee80211_plcp2rate(sc->sc_rx_desc.rate, (flags & RAL_RX_OFDM) ? IEEE80211_T_OFDM : IEEE80211_T_CCK); tap->wr_antenna = sc->rx_ant; tap->wr_antsignal = nf + rssi; tap->wr_antnoise = nf; } /* Strip trailing 802.11 MAC FCS. */ m_adj(m, -IEEE80211_CRC_LEN); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); /* * At the end of a USB callback it is always safe to unlock * the private mutex of a device! That is why we do the * "ieee80211_input" here, and not some lines up! */ RAL_UNLOCK(sc); if (m) { ni = ieee80211_find_rxnode(ic, mtod(m, struct ieee80211_frame_min *)); if (ni != NULL) { (void) ieee80211_input(ni, m, rssi, nf); ieee80211_free_node(ni); } else (void) ieee80211_input_all(ic, m, rssi, nf); } if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0 && !IFQ_IS_EMPTY(&ifp->if_snd)) ural_start(ifp); RAL_LOCK(sc); return; default: /* Error */ if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } return; } } static uint8_t ural_plcp_signal(int rate) { switch (rate) { /* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */ case 12: return 0xb; case 18: return 0xf; case 24: return 0xa; case 36: return 0xe; case 48: return 0x9; case 72: return 0xd; case 96: return 0x8; case 108: return 0xc; /* CCK rates (NB: not IEEE std, device-specific) */ case 2: return 0x0; case 4: return 0x1; case 11: return 0x2; case 22: return 0x3; } return 0xff; /* XXX unsupported/unknown rate */ } static void ural_setup_tx_desc(struct ural_softc *sc, struct ural_tx_desc *desc, uint32_t flags, int len, int rate) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; uint16_t plcp_length; int remainder; desc->flags = htole32(flags); desc->flags |= htole32(RAL_TX_NEWSEQ); desc->flags |= htole32(len << 16); desc->wme = htole16(RAL_AIFSN(2) | RAL_LOGCWMIN(3) | RAL_LOGCWMAX(5)); desc->wme |= htole16(RAL_IVOFFSET(sizeof (struct ieee80211_frame))); /* setup PLCP fields */ desc->plcp_signal = ural_plcp_signal(rate); desc->plcp_service = 4; len += IEEE80211_CRC_LEN; if (ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM) { desc->flags |= htole32(RAL_TX_OFDM); plcp_length = len & 0xfff; desc->plcp_length_hi = plcp_length >> 6; desc->plcp_length_lo = plcp_length & 0x3f; } else { if (rate == 0) rate = 2; /* avoid division by zero */ plcp_length = (16 * len + rate - 1) / rate; if (rate == 22) { remainder = (16 * len) % 22; if (remainder != 0 && remainder < 7) desc->plcp_service |= RAL_PLCP_LENGEXT; } desc->plcp_length_hi = plcp_length >> 8; desc->plcp_length_lo = plcp_length & 0xff; if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE)) desc->plcp_signal |= 0x08; } desc->iv = 0; desc->eiv = 0; } #define RAL_TX_TIMEOUT 5000 static int ural_tx_bcn(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni) { struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = ni->ni_ic; struct ifnet *ifp = sc->sc_ifp; const struct ieee80211_txparam *tp; struct ural_tx_data *data; if (sc->tx_nfree == 0) { ifp->if_drv_flags |= IFF_DRV_OACTIVE; m_freem(m0); ieee80211_free_node(ni); return (EIO); } if (ic->ic_bsschan == IEEE80211_CHAN_ANYC) { m_freem(m0); ieee80211_free_node(ni); return (ENXIO); } data = STAILQ_FIRST(&sc->tx_free); STAILQ_REMOVE_HEAD(&sc->tx_free, next); sc->tx_nfree--; tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_bsschan)]; data->m = m0; data->ni = ni; data->rate = tp->mgmtrate; ural_setup_tx_desc(sc, &data->desc, RAL_TX_IFS_NEWBACKOFF | RAL_TX_TIMESTAMP, m0->m_pkthdr.len, tp->mgmtrate); DPRINTFN(10, "sending beacon frame len=%u rate=%u\n", m0->m_pkthdr.len, tp->mgmtrate); STAILQ_INSERT_TAIL(&sc->tx_q, data, next); usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]); return (0); } static int ural_tx_mgt(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni) { struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = ni->ni_ic; const struct ieee80211_txparam *tp; struct ural_tx_data *data; struct ieee80211_frame *wh; struct ieee80211_key *k; uint32_t flags; uint16_t dur; RAL_LOCK_ASSERT(sc, MA_OWNED); data = STAILQ_FIRST(&sc->tx_free); STAILQ_REMOVE_HEAD(&sc->tx_free, next); sc->tx_nfree--; tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)]; wh = mtod(m0, struct ieee80211_frame *); if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) { k = ieee80211_crypto_encap(ni, m0); if (k == NULL) { m_freem(m0); return ENOBUFS; } wh = mtod(m0, struct ieee80211_frame *); } data->m = m0; data->ni = ni; data->rate = tp->mgmtrate; flags = 0; if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) { flags |= RAL_TX_ACK; dur = ieee80211_ack_duration(ic->ic_rt, tp->mgmtrate, ic->ic_flags & IEEE80211_F_SHPREAMBLE); USETW(wh->i_dur, dur); /* tell hardware to add timestamp for probe responses */ if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_MGT && (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PROBE_RESP) flags |= RAL_TX_TIMESTAMP; } ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, tp->mgmtrate); DPRINTFN(10, "sending mgt frame len=%u rate=%u\n", m0->m_pkthdr.len, tp->mgmtrate); STAILQ_INSERT_TAIL(&sc->tx_q, data, next); usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]); return 0; } static int ural_sendprot(struct ural_softc *sc, const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate) { struct ieee80211com *ic = ni->ni_ic; const struct ieee80211_frame *wh; struct ural_tx_data *data; struct mbuf *mprot; int protrate, ackrate, pktlen, flags, isshort; uint16_t dur; KASSERT(prot == IEEE80211_PROT_RTSCTS || prot == IEEE80211_PROT_CTSONLY, ("protection %d", prot)); wh = mtod(m, const struct ieee80211_frame *); pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN; protrate = ieee80211_ctl_rate(ic->ic_rt, rate); ackrate = ieee80211_ack_rate(ic->ic_rt, rate); isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0; dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort) + ieee80211_ack_duration(ic->ic_rt, rate, isshort); flags = RAL_TX_RETRY(7); if (prot == IEEE80211_PROT_RTSCTS) { /* NB: CTS is the same size as an ACK */ dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort); flags |= RAL_TX_ACK; mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur); } else { mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur); } if (mprot == NULL) { /* XXX stat + msg */ return ENOBUFS; } data = STAILQ_FIRST(&sc->tx_free); STAILQ_REMOVE_HEAD(&sc->tx_free, next); sc->tx_nfree--; data->m = mprot; data->ni = ieee80211_ref_node(ni); data->rate = protrate; ural_setup_tx_desc(sc, &data->desc, flags, mprot->m_pkthdr.len, protrate); STAILQ_INSERT_TAIL(&sc->tx_q, data, next); usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]); return 0; } static int ural_tx_raw(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni, const struct ieee80211_bpf_params *params) { struct ieee80211com *ic = ni->ni_ic; struct ural_tx_data *data; uint32_t flags; int error; int rate; RAL_LOCK_ASSERT(sc, MA_OWNED); KASSERT(params != NULL, ("no raw xmit params")); rate = params->ibp_rate0; if (!ieee80211_isratevalid(ic->ic_rt, rate)) { m_freem(m0); return EINVAL; } flags = 0; if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0) flags |= RAL_TX_ACK; if (params->ibp_flags & (IEEE80211_BPF_RTS|IEEE80211_BPF_CTS)) { error = ural_sendprot(sc, m0, ni, params->ibp_flags & IEEE80211_BPF_RTS ? IEEE80211_PROT_RTSCTS : IEEE80211_PROT_CTSONLY, rate); if (error || sc->tx_nfree == 0) { m_freem(m0); return ENOBUFS; } flags |= RAL_TX_IFS_SIFS; } data = STAILQ_FIRST(&sc->tx_free); STAILQ_REMOVE_HEAD(&sc->tx_free, next); sc->tx_nfree--; data->m = m0; data->ni = ni; data->rate = rate; /* XXX need to setup descriptor ourself */ ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, rate); DPRINTFN(10, "sending raw frame len=%u rate=%u\n", m0->m_pkthdr.len, rate); STAILQ_INSERT_TAIL(&sc->tx_q, data, next); usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]); return 0; } static int ural_tx_data(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni) { struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = ni->ni_ic; struct ural_tx_data *data; struct ieee80211_frame *wh; const struct ieee80211_txparam *tp; struct ieee80211_key *k; uint32_t flags = 0; uint16_t dur; int error, rate; RAL_LOCK_ASSERT(sc, MA_OWNED); wh = mtod(m0, struct ieee80211_frame *); tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)]; if (IEEE80211_IS_MULTICAST(wh->i_addr1)) rate = tp->mcastrate; else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) rate = tp->ucastrate; else rate = ni->ni_txrate; if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) { k = ieee80211_crypto_encap(ni, m0); if (k == NULL) { m_freem(m0); return ENOBUFS; } /* packet header may have moved, reset our local pointer */ wh = mtod(m0, struct ieee80211_frame *); } if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) { int prot = IEEE80211_PROT_NONE; if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold) prot = IEEE80211_PROT_RTSCTS; else if ((ic->ic_flags & IEEE80211_F_USEPROT) && ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM) prot = ic->ic_protmode; if (prot != IEEE80211_PROT_NONE) { error = ural_sendprot(sc, m0, ni, prot, rate); if (error || sc->tx_nfree == 0) { m_freem(m0); return ENOBUFS; } flags |= RAL_TX_IFS_SIFS; } } data = STAILQ_FIRST(&sc->tx_free); STAILQ_REMOVE_HEAD(&sc->tx_free, next); sc->tx_nfree--; data->m = m0; data->ni = ni; data->rate = rate; if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) { flags |= RAL_TX_ACK; flags |= RAL_TX_RETRY(7); dur = ieee80211_ack_duration(ic->ic_rt, rate, ic->ic_flags & IEEE80211_F_SHPREAMBLE); USETW(wh->i_dur, dur); } ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, rate); DPRINTFN(10, "sending data frame len=%u rate=%u\n", m0->m_pkthdr.len, rate); STAILQ_INSERT_TAIL(&sc->tx_q, data, next); usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]); return 0; } static void ural_start(struct ifnet *ifp) { struct ural_softc *sc = ifp->if_softc; struct ieee80211_node *ni; struct mbuf *m; RAL_LOCK(sc); if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) { RAL_UNLOCK(sc); return; } for (;;) { IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; if (sc->tx_nfree < RAL_TX_MINFREE) { IFQ_DRV_PREPEND(&ifp->if_snd, m); ifp->if_drv_flags |= IFF_DRV_OACTIVE; break; } ni = (struct ieee80211_node *) m->m_pkthdr.rcvif; if (ural_tx_data(sc, m, ni) != 0) { ieee80211_free_node(ni); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); break; } } RAL_UNLOCK(sc); } static int ural_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) { struct ural_softc *sc = ifp->if_softc; struct ieee80211com *ic = ifp->if_l2com; struct ifreq *ifr = (struct ifreq *) data; int error; int startall = 0; RAL_LOCK(sc); error = sc->sc_detached ? ENXIO : 0; RAL_UNLOCK(sc); if (error) return (error); switch (cmd) { case SIOCSIFFLAGS: RAL_LOCK(sc); if (ifp->if_flags & IFF_UP) { if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) { ural_init_locked(sc); startall = 1; } else ural_setpromisc(sc); } else { if (ifp->if_drv_flags & IFF_DRV_RUNNING) ural_stop(sc); } RAL_UNLOCK(sc); if (startall) ieee80211_start_all(ic); break; case SIOCGIFMEDIA: case SIOCSIFMEDIA: error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd); break; default: error = ether_ioctl(ifp, cmd, data); break; } return error; } static void ural_set_testmode(struct ural_softc *sc) { struct usb_device_request req; usb_error_t error; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = RAL_VENDOR_REQUEST; USETW(req.wValue, 4); USETW(req.wIndex, 1); USETW(req.wLength, 0); error = ural_do_request(sc, &req, NULL); if (error != 0) { device_printf(sc->sc_dev, "could not set test mode: %s\n", usbd_errstr(error)); } } static void ural_eeprom_read(struct ural_softc *sc, uint16_t addr, void *buf, int len) { struct usb_device_request req; usb_error_t error; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = RAL_READ_EEPROM; USETW(req.wValue, 0); USETW(req.wIndex, addr); USETW(req.wLength, len); error = ural_do_request(sc, &req, buf); if (error != 0) { device_printf(sc->sc_dev, "could not read EEPROM: %s\n", usbd_errstr(error)); } } static uint16_t ural_read(struct ural_softc *sc, uint16_t reg) { struct usb_device_request req; usb_error_t error; uint16_t val; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = RAL_READ_MAC; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, sizeof (uint16_t)); error = ural_do_request(sc, &req, &val); if (error != 0) { device_printf(sc->sc_dev, "could not read MAC register: %s\n", usbd_errstr(error)); return 0; } return le16toh(val); } static void ural_read_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len) { struct usb_device_request req; usb_error_t error; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = RAL_READ_MULTI_MAC; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, len); error = ural_do_request(sc, &req, buf); if (error != 0) { device_printf(sc->sc_dev, "could not read MAC register: %s\n", usbd_errstr(error)); } } static void ural_write(struct ural_softc *sc, uint16_t reg, uint16_t val) { struct usb_device_request req; usb_error_t error; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = RAL_WRITE_MAC; USETW(req.wValue, val); USETW(req.wIndex, reg); USETW(req.wLength, 0); error = ural_do_request(sc, &req, NULL); if (error != 0) { device_printf(sc->sc_dev, "could not write MAC register: %s\n", usbd_errstr(error)); } } static void ural_write_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len) { struct usb_device_request req; usb_error_t error; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = RAL_WRITE_MULTI_MAC; USETW(req.wValue, 0); USETW(req.wIndex, reg); USETW(req.wLength, len); error = ural_do_request(sc, &req, buf); if (error != 0) { device_printf(sc->sc_dev, "could not write MAC register: %s\n", usbd_errstr(error)); } } static void ural_bbp_write(struct ural_softc *sc, uint8_t reg, uint8_t val) { uint16_t tmp; int ntries; for (ntries = 0; ntries < 100; ntries++) { if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY)) break; if (ural_pause(sc, hz / 100)) break; } if (ntries == 100) { device_printf(sc->sc_dev, "could not write to BBP\n"); return; } tmp = reg << 8 | val; ural_write(sc, RAL_PHY_CSR7, tmp); } static uint8_t ural_bbp_read(struct ural_softc *sc, uint8_t reg) { uint16_t val; int ntries; val = RAL_BBP_WRITE | reg << 8; ural_write(sc, RAL_PHY_CSR7, val); for (ntries = 0; ntries < 100; ntries++) { if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY)) break; if (ural_pause(sc, hz / 100)) break; } if (ntries == 100) { device_printf(sc->sc_dev, "could not read BBP\n"); return 0; } return ural_read(sc, RAL_PHY_CSR7) & 0xff; } static void ural_rf_write(struct ural_softc *sc, uint8_t reg, uint32_t val) { uint32_t tmp; int ntries; for (ntries = 0; ntries < 100; ntries++) { if (!(ural_read(sc, RAL_PHY_CSR10) & RAL_RF_LOBUSY)) break; if (ural_pause(sc, hz / 100)) break; } if (ntries == 100) { device_printf(sc->sc_dev, "could not write to RF\n"); return; } tmp = RAL_RF_BUSY | RAL_RF_20BIT | (val & 0xfffff) << 2 | (reg & 0x3); ural_write(sc, RAL_PHY_CSR9, tmp & 0xffff); ural_write(sc, RAL_PHY_CSR10, tmp >> 16); /* remember last written value in sc */ sc->rf_regs[reg] = val; DPRINTFN(15, "RF R[%u] <- 0x%05x\n", reg & 0x3, val & 0xfffff); } static void ural_scan_start(struct ieee80211com *ic) { struct ifnet *ifp = ic->ic_ifp; struct ural_softc *sc = ifp->if_softc; RAL_LOCK(sc); ural_write(sc, RAL_TXRX_CSR19, 0); ural_set_bssid(sc, ifp->if_broadcastaddr); RAL_UNLOCK(sc); } static void ural_scan_end(struct ieee80211com *ic) { struct ural_softc *sc = ic->ic_ifp->if_softc; RAL_LOCK(sc); ural_enable_tsf_sync(sc); ural_set_bssid(sc, sc->sc_bssid); RAL_UNLOCK(sc); } static void ural_set_channel(struct ieee80211com *ic) { struct ural_softc *sc = ic->ic_ifp->if_softc; RAL_LOCK(sc); ural_set_chan(sc, ic->ic_curchan); RAL_UNLOCK(sc); } static void ural_set_chan(struct ural_softc *sc, struct ieee80211_channel *c) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; uint8_t power, tmp; int i, chan; chan = ieee80211_chan2ieee(ic, c); if (chan == 0 || chan == IEEE80211_CHAN_ANY) return; if (IEEE80211_IS_CHAN_2GHZ(c)) power = min(sc->txpow[chan - 1], 31); else power = 31; /* adjust txpower using ifconfig settings */ power -= (100 - ic->ic_txpowlimit) / 8; DPRINTFN(2, "setting channel to %u, txpower to %u\n", chan, power); switch (sc->rf_rev) { case RAL_RF_2522: ural_rf_write(sc, RAL_RF1, 0x00814); ural_rf_write(sc, RAL_RF2, ural_rf2522_r2[chan - 1]); ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040); break; case RAL_RF_2523: ural_rf_write(sc, RAL_RF1, 0x08804); ural_rf_write(sc, RAL_RF2, ural_rf2523_r2[chan - 1]); ural_rf_write(sc, RAL_RF3, power << 7 | 0x38044); ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286); break; case RAL_RF_2524: ural_rf_write(sc, RAL_RF1, 0x0c808); ural_rf_write(sc, RAL_RF2, ural_rf2524_r2[chan - 1]); ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040); ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286); break; case RAL_RF_2525: ural_rf_write(sc, RAL_RF1, 0x08808); ural_rf_write(sc, RAL_RF2, ural_rf2525_hi_r2[chan - 1]); ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044); ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286); ural_rf_write(sc, RAL_RF1, 0x08808); ural_rf_write(sc, RAL_RF2, ural_rf2525_r2[chan - 1]); ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044); ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286); break; case RAL_RF_2525E: ural_rf_write(sc, RAL_RF1, 0x08808); ural_rf_write(sc, RAL_RF2, ural_rf2525e_r2[chan - 1]); ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044); ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00286 : 0x00282); break; case RAL_RF_2526: ural_rf_write(sc, RAL_RF2, ural_rf2526_hi_r2[chan - 1]); ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381); ural_rf_write(sc, RAL_RF1, 0x08804); ural_rf_write(sc, RAL_RF2, ural_rf2526_r2[chan - 1]); ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044); ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381); break; /* dual-band RF */ case RAL_RF_5222: for (i = 0; ural_rf5222[i].chan != chan; i++); ural_rf_write(sc, RAL_RF1, ural_rf5222[i].r1); ural_rf_write(sc, RAL_RF2, ural_rf5222[i].r2); ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040); ural_rf_write(sc, RAL_RF4, ural_rf5222[i].r4); break; } if (ic->ic_opmode != IEEE80211_M_MONITOR && (ic->ic_flags & IEEE80211_F_SCAN) == 0) { /* set Japan filter bit for channel 14 */ tmp = ural_bbp_read(sc, 70); tmp &= ~RAL_JAPAN_FILTER; if (chan == 14) tmp |= RAL_JAPAN_FILTER; ural_bbp_write(sc, 70, tmp); /* clear CRC errors */ ural_read(sc, RAL_STA_CSR0); ural_pause(sc, hz / 100); ural_disable_rf_tune(sc); } /* XXX doesn't belong here */ /* update basic rate set */ ural_set_basicrates(sc, c); /* give the hardware some time to do the switchover */ ural_pause(sc, hz / 100); } /* * Disable RF auto-tuning. */ static void ural_disable_rf_tune(struct ural_softc *sc) { uint32_t tmp; if (sc->rf_rev != RAL_RF_2523) { tmp = sc->rf_regs[RAL_RF1] & ~RAL_RF1_AUTOTUNE; ural_rf_write(sc, RAL_RF1, tmp); } tmp = sc->rf_regs[RAL_RF3] & ~RAL_RF3_AUTOTUNE; ural_rf_write(sc, RAL_RF3, tmp); DPRINTFN(2, "disabling RF autotune\n"); } /* * Refer to IEEE Std 802.11-1999 pp. 123 for more information on TSF * synchronization. */ static void ural_enable_tsf_sync(struct ural_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); uint16_t logcwmin, preload, tmp; /* first, disable TSF synchronization */ ural_write(sc, RAL_TXRX_CSR19, 0); tmp = (16 * vap->iv_bss->ni_intval) << 4; ural_write(sc, RAL_TXRX_CSR18, tmp); logcwmin = (ic->ic_opmode == IEEE80211_M_IBSS) ? 2 : 0; preload = (ic->ic_opmode == IEEE80211_M_IBSS) ? 320 : 6; tmp = logcwmin << 12 | preload; ural_write(sc, RAL_TXRX_CSR20, tmp); /* finally, enable TSF synchronization */ tmp = RAL_ENABLE_TSF | RAL_ENABLE_TBCN; if (ic->ic_opmode == IEEE80211_M_STA) tmp |= RAL_ENABLE_TSF_SYNC(1); else tmp |= RAL_ENABLE_TSF_SYNC(2) | RAL_ENABLE_BEACON_GENERATOR; ural_write(sc, RAL_TXRX_CSR19, tmp); DPRINTF("enabling TSF synchronization\n"); } static void ural_enable_tsf(struct ural_softc *sc) { /* first, disable TSF synchronization */ ural_write(sc, RAL_TXRX_CSR19, 0); ural_write(sc, RAL_TXRX_CSR19, RAL_ENABLE_TSF | RAL_ENABLE_TSF_SYNC(2)); } #define RAL_RXTX_TURNAROUND 5 /* us */ static void ural_update_slot(struct ifnet *ifp) { struct ural_softc *sc = ifp->if_softc; struct ieee80211com *ic = ifp->if_l2com; uint16_t slottime, sifs, eifs; slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20; /* * These settings may sound a bit inconsistent but this is what the * reference driver does. */ if (ic->ic_curmode == IEEE80211_MODE_11B) { sifs = 16 - RAL_RXTX_TURNAROUND; eifs = 364; } else { sifs = 10 - RAL_RXTX_TURNAROUND; eifs = 64; } ural_write(sc, RAL_MAC_CSR10, slottime); ural_write(sc, RAL_MAC_CSR11, sifs); ural_write(sc, RAL_MAC_CSR12, eifs); } static void ural_set_txpreamble(struct ural_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; uint16_t tmp; tmp = ural_read(sc, RAL_TXRX_CSR10); tmp &= ~RAL_SHORT_PREAMBLE; if (ic->ic_flags & IEEE80211_F_SHPREAMBLE) tmp |= RAL_SHORT_PREAMBLE; ural_write(sc, RAL_TXRX_CSR10, tmp); } static void ural_set_basicrates(struct ural_softc *sc, const struct ieee80211_channel *c) { /* XXX wrong, take from rate set */ /* update basic rate set */ if (IEEE80211_IS_CHAN_5GHZ(c)) { /* 11a basic rates: 6, 12, 24Mbps */ ural_write(sc, RAL_TXRX_CSR11, 0x150); } else if (IEEE80211_IS_CHAN_ANYG(c)) { /* 11g basic rates: 1, 2, 5.5, 11, 6, 12, 24Mbps */ ural_write(sc, RAL_TXRX_CSR11, 0x15f); } else { /* 11b basic rates: 1, 2Mbps */ ural_write(sc, RAL_TXRX_CSR11, 0x3); } } static void ural_set_bssid(struct ural_softc *sc, const uint8_t *bssid) { uint16_t tmp; tmp = bssid[0] | bssid[1] << 8; ural_write(sc, RAL_MAC_CSR5, tmp); tmp = bssid[2] | bssid[3] << 8; ural_write(sc, RAL_MAC_CSR6, tmp); tmp = bssid[4] | bssid[5] << 8; ural_write(sc, RAL_MAC_CSR7, tmp); DPRINTF("setting BSSID to %6D\n", bssid, ":"); } static void ural_set_macaddr(struct ural_softc *sc, uint8_t *addr) { uint16_t tmp; tmp = addr[0] | addr[1] << 8; ural_write(sc, RAL_MAC_CSR2, tmp); tmp = addr[2] | addr[3] << 8; ural_write(sc, RAL_MAC_CSR3, tmp); tmp = addr[4] | addr[5] << 8; ural_write(sc, RAL_MAC_CSR4, tmp); DPRINTF("setting MAC address to %6D\n", addr, ":"); } static void ural_setpromisc(struct ural_softc *sc) { struct ifnet *ifp = sc->sc_ifp; uint32_t tmp; tmp = ural_read(sc, RAL_TXRX_CSR2); tmp &= ~RAL_DROP_NOT_TO_ME; if (!(ifp->if_flags & IFF_PROMISC)) tmp |= RAL_DROP_NOT_TO_ME; ural_write(sc, RAL_TXRX_CSR2, tmp); DPRINTF("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ? "entering" : "leaving"); } static void ural_update_promisc(struct ifnet *ifp) { struct ural_softc *sc = ifp->if_softc; if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) return; RAL_LOCK(sc); ural_setpromisc(sc); RAL_UNLOCK(sc); } static const char * ural_get_rf(int rev) { switch (rev) { case RAL_RF_2522: return "RT2522"; case RAL_RF_2523: return "RT2523"; case RAL_RF_2524: return "RT2524"; case RAL_RF_2525: return "RT2525"; case RAL_RF_2525E: return "RT2525e"; case RAL_RF_2526: return "RT2526"; case RAL_RF_5222: return "RT5222"; default: return "unknown"; } } static void ural_read_eeprom(struct ural_softc *sc) { uint16_t val; ural_eeprom_read(sc, RAL_EEPROM_CONFIG0, &val, 2); val = le16toh(val); sc->rf_rev = (val >> 11) & 0x7; sc->hw_radio = (val >> 10) & 0x1; sc->led_mode = (val >> 6) & 0x7; sc->rx_ant = (val >> 4) & 0x3; sc->tx_ant = (val >> 2) & 0x3; sc->nb_ant = val & 0x3; /* read MAC address */ ural_eeprom_read(sc, RAL_EEPROM_ADDRESS, sc->sc_bssid, 6); /* read default values for BBP registers */ ural_eeprom_read(sc, RAL_EEPROM_BBP_BASE, sc->bbp_prom, 2 * 16); /* read Tx power for all b/g channels */ ural_eeprom_read(sc, RAL_EEPROM_TXPOWER, sc->txpow, 14); } static int ural_bbp_init(struct ural_softc *sc) { #define N(a) ((int)(sizeof (a) / sizeof ((a)[0]))) int i, ntries; /* wait for BBP to be ready */ for (ntries = 0; ntries < 100; ntries++) { if (ural_bbp_read(sc, RAL_BBP_VERSION) != 0) break; if (ural_pause(sc, hz / 100)) break; } if (ntries == 100) { device_printf(sc->sc_dev, "timeout waiting for BBP\n"); return EIO; } /* initialize BBP registers to default values */ for (i = 0; i < N(ural_def_bbp); i++) ural_bbp_write(sc, ural_def_bbp[i].reg, ural_def_bbp[i].val); #if 0 /* initialize BBP registers to values stored in EEPROM */ for (i = 0; i < 16; i++) { if (sc->bbp_prom[i].reg == 0xff) continue; ural_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val); } #endif return 0; #undef N } static void ural_set_txantenna(struct ural_softc *sc, int antenna) { uint16_t tmp; uint8_t tx; tx = ural_bbp_read(sc, RAL_BBP_TX) & ~RAL_BBP_ANTMASK; if (antenna == 1) tx |= RAL_BBP_ANTA; else if (antenna == 2) tx |= RAL_BBP_ANTB; else tx |= RAL_BBP_DIVERSITY; /* need to force I/Q flip for RF 2525e, 2526 and 5222 */ if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526 || sc->rf_rev == RAL_RF_5222) tx |= RAL_BBP_FLIPIQ; ural_bbp_write(sc, RAL_BBP_TX, tx); /* update values in PHY_CSR5 and PHY_CSR6 */ tmp = ural_read(sc, RAL_PHY_CSR5) & ~0x7; ural_write(sc, RAL_PHY_CSR5, tmp | (tx & 0x7)); tmp = ural_read(sc, RAL_PHY_CSR6) & ~0x7; ural_write(sc, RAL_PHY_CSR6, tmp | (tx & 0x7)); } static void ural_set_rxantenna(struct ural_softc *sc, int antenna) { uint8_t rx; rx = ural_bbp_read(sc, RAL_BBP_RX) & ~RAL_BBP_ANTMASK; if (antenna == 1) rx |= RAL_BBP_ANTA; else if (antenna == 2) rx |= RAL_BBP_ANTB; else rx |= RAL_BBP_DIVERSITY; /* need to force no I/Q flip for RF 2525e and 2526 */ if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526) rx &= ~RAL_BBP_FLIPIQ; ural_bbp_write(sc, RAL_BBP_RX, rx); } static void ural_init_locked(struct ural_softc *sc) { #define N(a) ((int)(sizeof (a) / sizeof ((a)[0]))) struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; uint16_t tmp; int i, ntries; RAL_LOCK_ASSERT(sc, MA_OWNED); ural_set_testmode(sc); ural_write(sc, 0x308, 0x00f0); /* XXX magic */ ural_stop(sc); /* initialize MAC registers to default values */ for (i = 0; i < N(ural_def_mac); i++) ural_write(sc, ural_def_mac[i].reg, ural_def_mac[i].val); /* wait for BBP and RF to wake up (this can take a long time!) */ for (ntries = 0; ntries < 100; ntries++) { tmp = ural_read(sc, RAL_MAC_CSR17); if ((tmp & (RAL_BBP_AWAKE | RAL_RF_AWAKE)) == (RAL_BBP_AWAKE | RAL_RF_AWAKE)) break; if (ural_pause(sc, hz / 100)) break; } if (ntries == 100) { device_printf(sc->sc_dev, "timeout waiting for BBP/RF to wakeup\n"); goto fail; } /* we're ready! */ ural_write(sc, RAL_MAC_CSR1, RAL_HOST_READY); /* set basic rate set (will be updated later) */ ural_write(sc, RAL_TXRX_CSR11, 0x15f); if (ural_bbp_init(sc) != 0) goto fail; ural_set_chan(sc, ic->ic_curchan); /* clear statistic registers (STA_CSR0 to STA_CSR10) */ ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta); ural_set_txantenna(sc, sc->tx_ant); ural_set_rxantenna(sc, sc->rx_ant); ural_set_macaddr(sc, IF_LLADDR(ifp)); /* * Allocate Tx and Rx xfer queues. */ ural_setup_tx_list(sc); /* kick Rx */ tmp = RAL_DROP_PHY | RAL_DROP_CRC; if (ic->ic_opmode != IEEE80211_M_MONITOR) { tmp |= RAL_DROP_CTL | RAL_DROP_BAD_VERSION; if (ic->ic_opmode != IEEE80211_M_HOSTAP) tmp |= RAL_DROP_TODS; if (!(ifp->if_flags & IFF_PROMISC)) tmp |= RAL_DROP_NOT_TO_ME; } ural_write(sc, RAL_TXRX_CSR2, tmp); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; ifp->if_drv_flags |= IFF_DRV_RUNNING; usbd_xfer_set_stall(sc->sc_xfer[URAL_BULK_WR]); usbd_transfer_start(sc->sc_xfer[URAL_BULK_RD]); return; fail: ural_stop(sc); #undef N } static void ural_init(void *priv) { struct ural_softc *sc = priv; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; RAL_LOCK(sc); ural_init_locked(sc); RAL_UNLOCK(sc); if (ifp->if_drv_flags & IFF_DRV_RUNNING) ieee80211_start_all(ic); /* start all vap's */ } static void ural_stop(struct ural_softc *sc) { struct ifnet *ifp = sc->sc_ifp; RAL_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); /* * Drain all the transfers, if not already drained: */ RAL_UNLOCK(sc); usbd_transfer_drain(sc->sc_xfer[URAL_BULK_WR]); usbd_transfer_drain(sc->sc_xfer[URAL_BULK_RD]); RAL_LOCK(sc); ural_unsetup_tx_list(sc); /* disable Rx */ ural_write(sc, RAL_TXRX_CSR2, RAL_DISABLE_RX); /* reset ASIC and BBP (but won't reset MAC registers!) */ ural_write(sc, RAL_MAC_CSR1, RAL_RESET_ASIC | RAL_RESET_BBP); /* wait a little */ ural_pause(sc, hz / 10); ural_write(sc, RAL_MAC_CSR1, 0); /* wait a little */ ural_pause(sc, hz / 10); } static int ural_raw_xmit(struct ieee80211_node *ni, struct mbuf *m, const struct ieee80211_bpf_params *params) { struct ieee80211com *ic = ni->ni_ic; struct ifnet *ifp = ic->ic_ifp; struct ural_softc *sc = ifp->if_softc; RAL_LOCK(sc); /* prevent management frames from being sent if we're not ready */ if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) { RAL_UNLOCK(sc); m_freem(m); ieee80211_free_node(ni); return ENETDOWN; } if (sc->tx_nfree < RAL_TX_MINFREE) { ifp->if_drv_flags |= IFF_DRV_OACTIVE; RAL_UNLOCK(sc); m_freem(m); ieee80211_free_node(ni); return EIO; } if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); if (params == NULL) { /* * Legacy path; interpret frame contents to decide * precisely how to send the frame. */ if (ural_tx_mgt(sc, m, ni) != 0) goto bad; } else { /* * Caller supplied explicit parameters to use in * sending the frame. */ if (ural_tx_raw(sc, m, ni, params) != 0) goto bad; } RAL_UNLOCK(sc); return 0; bad: if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); RAL_UNLOCK(sc); ieee80211_free_node(ni); return EIO; /* XXX */ } static void ural_ratectl_start(struct ural_softc *sc, struct ieee80211_node *ni) { struct ieee80211vap *vap = ni->ni_vap; struct ural_vap *uvp = URAL_VAP(vap); /* clear statistic registers (STA_CSR0 to STA_CSR10) */ ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta); usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp); } static void ural_ratectl_timeout(void *arg) { struct ural_vap *uvp = arg; struct ieee80211vap *vap = &uvp->vap; struct ieee80211com *ic = vap->iv_ic; ieee80211_runtask(ic, &uvp->ratectl_task); } static void ural_ratectl_task(void *arg, int pending) { struct ural_vap *uvp = arg; struct ieee80211vap *vap = &uvp->vap; struct ieee80211com *ic = vap->iv_ic; struct ifnet *ifp = ic->ic_ifp; struct ural_softc *sc = ifp->if_softc; struct ieee80211_node *ni; int ok, fail; int sum, retrycnt; ni = ieee80211_ref_node(vap->iv_bss); RAL_LOCK(sc); /* read and clear statistic registers (STA_CSR0 to STA_CSR10) */ ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof(sc->sta)); ok = sc->sta[7] + /* TX ok w/o retry */ sc->sta[8]; /* TX ok w/ retry */ fail = sc->sta[9]; /* TX retry-fail count */ sum = ok+fail; retrycnt = sc->sta[8] + fail; ieee80211_ratectl_tx_update(vap, ni, &sum, &ok, &retrycnt); (void) ieee80211_ratectl_rate(ni, NULL, 0); if_inc_counter(ifp, IFCOUNTER_OERRORS, fail); /* count TX retry-fail as Tx errors */ usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp); RAL_UNLOCK(sc); ieee80211_free_node(ni); } static int ural_pause(struct ural_softc *sc, int timeout) { usb_pause_mtx(&sc->sc_mtx, timeout); return (0); } Index: head/sys/dev/usb/wlan/if_urtwn.c =================================================================== --- head/sys/dev/usb/wlan/if_urtwn.c (revision 276700) +++ head/sys/dev/usb/wlan/if_urtwn.c (revision 276701) @@ -1,3575 +1,3575 @@ /* $OpenBSD: if_urtwn.c,v 1.16 2011/02/10 17:26:40 jakemsr Exp $ */ /*- * Copyright (c) 2010 Damien Bergamini * Copyright (c) 2014 Kevin Lo * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include __FBSDID("$FreeBSD$"); /* * Driver for Realtek RTL8188CE-VAU/RTL8188CUS/RTL8188EU/RTL8188RU/RTL8192CU. */ #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 #include #include #include #include #include #include #include "usbdevs.h" #define USB_DEBUG_VAR urtwn_debug #include #include #ifdef USB_DEBUG static int urtwn_debug = 0; SYSCTL_NODE(_hw_usb, OID_AUTO, urtwn, CTLFLAG_RW, 0, "USB urtwn"); -SYSCTL_INT(_hw_usb_urtwn, OID_AUTO, debug, CTLFLAG_RW, &urtwn_debug, 0, +SYSCTL_INT(_hw_usb_urtwn, OID_AUTO, debug, CTLFLAG_RWTUN, &urtwn_debug, 0, "Debug level"); #endif #define URTWN_RSSI(r) (r) - 110 #define IEEE80211_HAS_ADDR4(wh) \ (((wh)->i_fc[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_DSTODS) /* various supported device vendors/products */ static const STRUCT_USB_HOST_ID urtwn_devs[] = { #define URTWN_DEV(v,p) { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) } #define URTWN_RTL8188E_DEV(v,p) \ { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, URTWN_RTL8188E) } #define URTWN_RTL8188E 1 URTWN_DEV(ABOCOM, RTL8188CU_1), URTWN_DEV(ABOCOM, RTL8188CU_2), URTWN_DEV(ABOCOM, RTL8192CU), URTWN_DEV(ASUS, RTL8192CU), URTWN_DEV(ASUS, USBN10NANO), URTWN_DEV(AZUREWAVE, RTL8188CE_1), URTWN_DEV(AZUREWAVE, RTL8188CE_2), URTWN_DEV(AZUREWAVE, RTL8188CU), URTWN_DEV(BELKIN, F7D2102), URTWN_DEV(BELKIN, RTL8188CU), URTWN_DEV(BELKIN, RTL8192CU), URTWN_DEV(CHICONY, RTL8188CUS_1), URTWN_DEV(CHICONY, RTL8188CUS_2), URTWN_DEV(CHICONY, RTL8188CUS_3), URTWN_DEV(CHICONY, RTL8188CUS_4), URTWN_DEV(CHICONY, RTL8188CUS_5), URTWN_DEV(COREGA, RTL8192CU), URTWN_DEV(DLINK, RTL8188CU), URTWN_DEV(DLINK, RTL8192CU_1), URTWN_DEV(DLINK, RTL8192CU_2), URTWN_DEV(DLINK, RTL8192CU_3), URTWN_DEV(DLINK, DWA131B), URTWN_DEV(EDIMAX, EW7811UN), URTWN_DEV(EDIMAX, RTL8192CU), URTWN_DEV(FEIXUN, RTL8188CU), URTWN_DEV(FEIXUN, RTL8192CU), URTWN_DEV(GUILLEMOT, HWNUP150), URTWN_DEV(HAWKING, RTL8192CU), URTWN_DEV(HP3, RTL8188CU), URTWN_DEV(NETGEAR, WNA1000M), URTWN_DEV(NETGEAR, RTL8192CU), URTWN_DEV(NETGEAR4, RTL8188CU), URTWN_DEV(NOVATECH, RTL8188CU), URTWN_DEV(PLANEX2, RTL8188CU_1), URTWN_DEV(PLANEX2, RTL8188CU_2), URTWN_DEV(PLANEX2, RTL8188CU_3), URTWN_DEV(PLANEX2, RTL8188CU_4), URTWN_DEV(PLANEX2, RTL8188CUS), URTWN_DEV(PLANEX2, RTL8192CU), URTWN_DEV(REALTEK, RTL8188CE_0), URTWN_DEV(REALTEK, RTL8188CE_1), URTWN_DEV(REALTEK, RTL8188CTV), URTWN_DEV(REALTEK, RTL8188CU_0), URTWN_DEV(REALTEK, RTL8188CU_1), URTWN_DEV(REALTEK, RTL8188CU_2), URTWN_DEV(REALTEK, RTL8188CU_COMBO), URTWN_DEV(REALTEK, RTL8188CUS), URTWN_DEV(REALTEK, RTL8188RU_1), URTWN_DEV(REALTEK, RTL8188RU_2), URTWN_DEV(REALTEK, RTL8188RU_3), URTWN_DEV(REALTEK, RTL8191CU), URTWN_DEV(REALTEK, RTL8192CE), URTWN_DEV(REALTEK, RTL8192CU), URTWN_DEV(REALTEK, RTL8188CU_0), URTWN_DEV(SITECOMEU, RTL8188CU_1), URTWN_DEV(SITECOMEU, RTL8188CU_2), URTWN_DEV(SITECOMEU, RTL8192CU), URTWN_DEV(TRENDNET, RTL8188CU), URTWN_DEV(TRENDNET, RTL8192CU), URTWN_DEV(ZYXEL, RTL8192CU), /* URTWN_RTL8188E */ URTWN_RTL8188E_DEV(DLINK, DWA123D1), URTWN_RTL8188E_DEV(DLINK, DWA125D1), URTWN_RTL8188E_DEV(ELECOM, WDC150SU2M), URTWN_RTL8188E_DEV(REALTEK, RTL8188ETV), URTWN_RTL8188E_DEV(REALTEK, RTL8188EU), #undef URTWN_RTL8188E_DEV #undef URTWN_DEV }; static device_probe_t urtwn_match; static device_attach_t urtwn_attach; static device_detach_t urtwn_detach; static usb_callback_t urtwn_bulk_tx_callback; static usb_callback_t urtwn_bulk_rx_callback; static usb_error_t urtwn_do_request(struct urtwn_softc *sc, struct usb_device_request *req, void *data); static struct ieee80211vap *urtwn_vap_create(struct ieee80211com *, const char [IFNAMSIZ], int, enum ieee80211_opmode, int, const uint8_t [IEEE80211_ADDR_LEN], const uint8_t [IEEE80211_ADDR_LEN]); static void urtwn_vap_delete(struct ieee80211vap *); static struct mbuf * urtwn_rx_frame(struct urtwn_softc *, uint8_t *, int, int *); static struct mbuf * urtwn_rxeof(struct usb_xfer *, struct urtwn_data *, int *, int8_t *); static void urtwn_txeof(struct usb_xfer *, struct urtwn_data *); static int urtwn_alloc_list(struct urtwn_softc *, struct urtwn_data[], int, int); static int urtwn_alloc_rx_list(struct urtwn_softc *); static int urtwn_alloc_tx_list(struct urtwn_softc *); static void urtwn_free_tx_list(struct urtwn_softc *); static void urtwn_free_rx_list(struct urtwn_softc *); static void urtwn_free_list(struct urtwn_softc *, struct urtwn_data data[], int); static struct urtwn_data * _urtwn_getbuf(struct urtwn_softc *); static struct urtwn_data * urtwn_getbuf(struct urtwn_softc *); static int urtwn_write_region_1(struct urtwn_softc *, uint16_t, uint8_t *, int); static void urtwn_write_1(struct urtwn_softc *, uint16_t, uint8_t); static void urtwn_write_2(struct urtwn_softc *, uint16_t, uint16_t); static void urtwn_write_4(struct urtwn_softc *, uint16_t, uint32_t); static int urtwn_read_region_1(struct urtwn_softc *, uint16_t, uint8_t *, int); static uint8_t urtwn_read_1(struct urtwn_softc *, uint16_t); static uint16_t urtwn_read_2(struct urtwn_softc *, uint16_t); static uint32_t urtwn_read_4(struct urtwn_softc *, uint16_t); static int urtwn_fw_cmd(struct urtwn_softc *, uint8_t, const void *, int); static void urtwn_r92c_rf_write(struct urtwn_softc *, int, uint8_t, uint32_t); static void urtwn_r88e_rf_write(struct urtwn_softc *, int, uint8_t, uint32_t); static uint32_t urtwn_rf_read(struct urtwn_softc *, int, uint8_t); static int urtwn_llt_write(struct urtwn_softc *, uint32_t, uint32_t); static uint8_t urtwn_efuse_read_1(struct urtwn_softc *, uint16_t); static void urtwn_efuse_read(struct urtwn_softc *); static void urtwn_efuse_switch_power(struct urtwn_softc *); static int urtwn_read_chipid(struct urtwn_softc *); static void urtwn_read_rom(struct urtwn_softc *); static void urtwn_r88e_read_rom(struct urtwn_softc *); static int urtwn_ra_init(struct urtwn_softc *); static void urtwn_tsf_sync_enable(struct urtwn_softc *); static void urtwn_set_led(struct urtwn_softc *, int, int); static int urtwn_newstate(struct ieee80211vap *, enum ieee80211_state, int); static void urtwn_watchdog(void *); static void urtwn_update_avgrssi(struct urtwn_softc *, int, int8_t); static int8_t urtwn_get_rssi(struct urtwn_softc *, int, void *); static int8_t urtwn_r88e_get_rssi(struct urtwn_softc *, int, void *); static int urtwn_tx_start(struct urtwn_softc *, struct ieee80211_node *, struct mbuf *, struct urtwn_data *); static void urtwn_start(struct ifnet *); static void urtwn_start_locked(struct ifnet *, struct urtwn_softc *); static int urtwn_ioctl(struct ifnet *, u_long, caddr_t); static int urtwn_r92c_power_on(struct urtwn_softc *); static int urtwn_r88e_power_on(struct urtwn_softc *); static int urtwn_llt_init(struct urtwn_softc *); static void urtwn_fw_reset(struct urtwn_softc *); static void urtwn_r88e_fw_reset(struct urtwn_softc *); static int urtwn_fw_loadpage(struct urtwn_softc *, int, const uint8_t *, int); static int urtwn_load_firmware(struct urtwn_softc *); static int urtwn_r92c_dma_init(struct urtwn_softc *); static int urtwn_r88e_dma_init(struct urtwn_softc *); static void urtwn_mac_init(struct urtwn_softc *); static void urtwn_bb_init(struct urtwn_softc *); static void urtwn_rf_init(struct urtwn_softc *); static void urtwn_cam_init(struct urtwn_softc *); static void urtwn_pa_bias_init(struct urtwn_softc *); static void urtwn_rxfilter_init(struct urtwn_softc *); static void urtwn_edca_init(struct urtwn_softc *); static void urtwn_write_txpower(struct urtwn_softc *, int, uint16_t[]); static void urtwn_get_txpower(struct urtwn_softc *, int, struct ieee80211_channel *, struct ieee80211_channel *, uint16_t[]); static void urtwn_r88e_get_txpower(struct urtwn_softc *, int, struct ieee80211_channel *, struct ieee80211_channel *, uint16_t[]); static void urtwn_set_txpower(struct urtwn_softc *, struct ieee80211_channel *, struct ieee80211_channel *); static void urtwn_scan_start(struct ieee80211com *); static void urtwn_scan_end(struct ieee80211com *); static void urtwn_set_channel(struct ieee80211com *); static void urtwn_set_chan(struct urtwn_softc *, struct ieee80211_channel *, struct ieee80211_channel *); static void urtwn_update_mcast(struct ifnet *); static void urtwn_iq_calib(struct urtwn_softc *); static void urtwn_lc_calib(struct urtwn_softc *); static void urtwn_init(void *); static void urtwn_init_locked(void *); static void urtwn_stop(struct ifnet *); static void urtwn_stop_locked(struct ifnet *); static void urtwn_abort_xfers(struct urtwn_softc *); static int urtwn_raw_xmit(struct ieee80211_node *, struct mbuf *, const struct ieee80211_bpf_params *); static void urtwn_ms_delay(struct urtwn_softc *); /* Aliases. */ #define urtwn_bb_write urtwn_write_4 #define urtwn_bb_read urtwn_read_4 static const struct usb_config urtwn_config[URTWN_N_TRANSFER] = { [URTWN_BULK_RX] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = URTWN_RXBUFSZ, .flags = { .pipe_bof = 1, .short_xfer_ok = 1 }, .callback = urtwn_bulk_rx_callback, }, [URTWN_BULK_TX_BE] = { .type = UE_BULK, .endpoint = 0x03, .direction = UE_DIR_OUT, .bufsize = URTWN_TXBUFSZ, .flags = { .ext_buffer = 1, .pipe_bof = 1, .force_short_xfer = 1 }, .callback = urtwn_bulk_tx_callback, .timeout = URTWN_TX_TIMEOUT, /* ms */ }, [URTWN_BULK_TX_BK] = { .type = UE_BULK, .endpoint = 0x03, .direction = UE_DIR_OUT, .bufsize = URTWN_TXBUFSZ, .flags = { .ext_buffer = 1, .pipe_bof = 1, .force_short_xfer = 1, }, .callback = urtwn_bulk_tx_callback, .timeout = URTWN_TX_TIMEOUT, /* ms */ }, [URTWN_BULK_TX_VI] = { .type = UE_BULK, .endpoint = 0x02, .direction = UE_DIR_OUT, .bufsize = URTWN_TXBUFSZ, .flags = { .ext_buffer = 1, .pipe_bof = 1, .force_short_xfer = 1 }, .callback = urtwn_bulk_tx_callback, .timeout = URTWN_TX_TIMEOUT, /* ms */ }, [URTWN_BULK_TX_VO] = { .type = UE_BULK, .endpoint = 0x02, .direction = UE_DIR_OUT, .bufsize = URTWN_TXBUFSZ, .flags = { .ext_buffer = 1, .pipe_bof = 1, .force_short_xfer = 1 }, .callback = urtwn_bulk_tx_callback, .timeout = URTWN_TX_TIMEOUT, /* ms */ }, }; static int urtwn_match(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != URTWN_CONFIG_INDEX) return (ENXIO); if (uaa->info.bIfaceIndex != URTWN_IFACE_INDEX) return (ENXIO); return (usbd_lookup_id_by_uaa(urtwn_devs, sizeof(urtwn_devs), uaa)); } static int urtwn_attach(device_t self) { struct usb_attach_arg *uaa = device_get_ivars(self); struct urtwn_softc *sc = device_get_softc(self); struct ifnet *ifp; struct ieee80211com *ic; uint8_t iface_index, bands; int error; device_set_usb_desc(self); sc->sc_udev = uaa->device; sc->sc_dev = self; if (USB_GET_DRIVER_INFO(uaa) == URTWN_RTL8188E) sc->chip |= URTWN_CHIP_88E; mtx_init(&sc->sc_mtx, device_get_nameunit(self), MTX_NETWORK_LOCK, MTX_DEF); callout_init(&sc->sc_watchdog_ch, 0); iface_index = URTWN_IFACE_INDEX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, urtwn_config, URTWN_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(self, "could not allocate USB transfers, " "err=%s\n", usbd_errstr(error)); goto detach; } URTWN_LOCK(sc); error = urtwn_read_chipid(sc); if (error) { device_printf(sc->sc_dev, "unsupported test chip\n"); URTWN_UNLOCK(sc); goto detach; } /* Determine number of Tx/Rx chains. */ if (sc->chip & URTWN_CHIP_92C) { sc->ntxchains = (sc->chip & URTWN_CHIP_92C_1T2R) ? 1 : 2; sc->nrxchains = 2; } else { sc->ntxchains = 1; sc->nrxchains = 1; } if (sc->chip & URTWN_CHIP_88E) urtwn_r88e_read_rom(sc); else urtwn_read_rom(sc); device_printf(sc->sc_dev, "MAC/BB RTL%s, RF 6052 %dT%dR\n", (sc->chip & URTWN_CHIP_92C) ? "8192CU" : (sc->chip & URTWN_CHIP_88E) ? "8188EU" : (sc->board_type == R92C_BOARD_TYPE_HIGHPA) ? "8188RU" : (sc->board_type == R92C_BOARD_TYPE_MINICARD) ? "8188CE-VAU" : "8188CUS", sc->ntxchains, sc->nrxchains); URTWN_UNLOCK(sc); ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211); if (ifp == NULL) { device_printf(sc->sc_dev, "can not if_alloc()\n"); goto detach; } ic = ifp->if_l2com; ifp->if_softc = sc; if_initname(ifp, "urtwn", device_get_unit(sc->sc_dev)); ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; ifp->if_init = urtwn_init; ifp->if_ioctl = urtwn_ioctl; ifp->if_start = urtwn_start; IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen); ifp->if_snd.ifq_drv_maxlen = ifqmaxlen; IFQ_SET_READY(&ifp->if_snd); ic->ic_ifp = ifp; ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */ ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */ /* set device capabilities */ ic->ic_caps = IEEE80211_C_STA /* station mode */ | IEEE80211_C_MONITOR /* monitor mode */ | IEEE80211_C_SHPREAMBLE /* short preamble supported */ | IEEE80211_C_SHSLOT /* short slot time supported */ | IEEE80211_C_BGSCAN /* capable of bg scanning */ | IEEE80211_C_WPA /* 802.11i */ ; bands = 0; setbit(&bands, IEEE80211_MODE_11B); setbit(&bands, IEEE80211_MODE_11G); ieee80211_init_channels(ic, NULL, &bands); ieee80211_ifattach(ic, sc->sc_bssid); ic->ic_raw_xmit = urtwn_raw_xmit; ic->ic_scan_start = urtwn_scan_start; ic->ic_scan_end = urtwn_scan_end; ic->ic_set_channel = urtwn_set_channel; ic->ic_vap_create = urtwn_vap_create; ic->ic_vap_delete = urtwn_vap_delete; ic->ic_update_mcast = urtwn_update_mcast; ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap), URTWN_TX_RADIOTAP_PRESENT, &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap), URTWN_RX_RADIOTAP_PRESENT); if (bootverbose) ieee80211_announce(ic); return (0); detach: urtwn_detach(self); return (ENXIO); /* failure */ } static int urtwn_detach(device_t self) { struct urtwn_softc *sc = device_get_softc(self); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; unsigned int x; /* Prevent further ioctls. */ URTWN_LOCK(sc); sc->sc_flags |= URTWN_DETACHED; URTWN_UNLOCK(sc); urtwn_stop(ifp); callout_drain(&sc->sc_watchdog_ch); /* Prevent further allocations from RX/TX data lists. */ URTWN_LOCK(sc); STAILQ_INIT(&sc->sc_tx_active); STAILQ_INIT(&sc->sc_tx_inactive); STAILQ_INIT(&sc->sc_tx_pending); STAILQ_INIT(&sc->sc_rx_active); STAILQ_INIT(&sc->sc_rx_inactive); URTWN_UNLOCK(sc); /* drain USB transfers */ for (x = 0; x != URTWN_N_TRANSFER; x++) usbd_transfer_drain(sc->sc_xfer[x]); /* Free data buffers. */ URTWN_LOCK(sc); urtwn_free_tx_list(sc); urtwn_free_rx_list(sc); URTWN_UNLOCK(sc); /* stop all USB transfers */ usbd_transfer_unsetup(sc->sc_xfer, URTWN_N_TRANSFER); ieee80211_ifdetach(ic); if_free(ifp); mtx_destroy(&sc->sc_mtx); return (0); } static void urtwn_free_tx_list(struct urtwn_softc *sc) { urtwn_free_list(sc, sc->sc_tx, URTWN_TX_LIST_COUNT); } static void urtwn_free_rx_list(struct urtwn_softc *sc) { urtwn_free_list(sc, sc->sc_rx, URTWN_RX_LIST_COUNT); } static void urtwn_free_list(struct urtwn_softc *sc, struct urtwn_data data[], int ndata) { int i; for (i = 0; i < ndata; i++) { struct urtwn_data *dp = &data[i]; if (dp->buf != NULL) { free(dp->buf, M_USBDEV); dp->buf = NULL; } if (dp->ni != NULL) { ieee80211_free_node(dp->ni); dp->ni = NULL; } } } static usb_error_t urtwn_do_request(struct urtwn_softc *sc, struct usb_device_request *req, void *data) { usb_error_t err; int ntries = 10; URTWN_ASSERT_LOCKED(sc); while (ntries--) { err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx, req, data, 0, NULL, 250 /* ms */); if (err == 0) break; DPRINTFN(1, "Control request failed, %s (retrying)\n", usbd_errstr(err)); usb_pause_mtx(&sc->sc_mtx, hz / 100); } return (err); } static struct ieee80211vap * urtwn_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit, enum ieee80211_opmode opmode, int flags, const uint8_t bssid[IEEE80211_ADDR_LEN], const uint8_t mac[IEEE80211_ADDR_LEN]) { struct urtwn_vap *uvp; struct ieee80211vap *vap; if (!TAILQ_EMPTY(&ic->ic_vaps)) /* only one at a time */ return (NULL); uvp = (struct urtwn_vap *) malloc(sizeof(struct urtwn_vap), M_80211_VAP, M_NOWAIT | M_ZERO); if (uvp == NULL) return (NULL); vap = &uvp->vap; /* enable s/w bmiss handling for sta mode */ if (ieee80211_vap_setup(ic, vap, name, unit, opmode, flags | IEEE80211_CLONE_NOBEACONS, bssid, mac) != 0) { /* out of memory */ free(uvp, M_80211_VAP); return (NULL); } /* override state transition machine */ uvp->newstate = vap->iv_newstate; vap->iv_newstate = urtwn_newstate; /* complete setup */ ieee80211_vap_attach(vap, ieee80211_media_change, ieee80211_media_status); ic->ic_opmode = opmode; return (vap); } static void urtwn_vap_delete(struct ieee80211vap *vap) { struct urtwn_vap *uvp = URTWN_VAP(vap); ieee80211_vap_detach(vap); free(uvp, M_80211_VAP); } static struct mbuf * urtwn_rx_frame(struct urtwn_softc *sc, uint8_t *buf, int pktlen, int *rssi_p) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211_frame *wh; struct mbuf *m; struct r92c_rx_stat *stat; uint32_t rxdw0, rxdw3; uint8_t rate; int8_t rssi = 0; int infosz; /* * don't pass packets to the ieee80211 framework if the driver isn't * RUNNING. */ if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) return (NULL); stat = (struct r92c_rx_stat *)buf; rxdw0 = le32toh(stat->rxdw0); rxdw3 = le32toh(stat->rxdw3); if (rxdw0 & (R92C_RXDW0_CRCERR | R92C_RXDW0_ICVERR)) { /* * This should not happen since we setup our Rx filter * to not receive these frames. */ if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); return (NULL); } if (pktlen < sizeof(*wh) || pktlen > MCLBYTES) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); return (NULL); } rate = MS(rxdw3, R92C_RXDW3_RATE); infosz = MS(rxdw0, R92C_RXDW0_INFOSZ) * 8; /* Get RSSI from PHY status descriptor if present. */ if (infosz != 0 && (rxdw0 & R92C_RXDW0_PHYST)) { if (sc->chip & URTWN_CHIP_88E) rssi = urtwn_r88e_get_rssi(sc, rate, &stat[1]); else rssi = urtwn_get_rssi(sc, rate, &stat[1]); /* Update our average RSSI. */ urtwn_update_avgrssi(sc, rate, rssi); /* * Convert the RSSI to a range that will be accepted * by net80211. */ rssi = URTWN_RSSI(rssi); } m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); if (m == NULL) { device_printf(sc->sc_dev, "could not create RX mbuf\n"); return (NULL); } /* Finalize mbuf. */ m->m_pkthdr.rcvif = ifp; wh = (struct ieee80211_frame *)((uint8_t *)&stat[1] + infosz); memcpy(mtod(m, uint8_t *), wh, pktlen); m->m_pkthdr.len = m->m_len = pktlen; if (ieee80211_radiotap_active(ic)) { struct urtwn_rx_radiotap_header *tap = &sc->sc_rxtap; tap->wr_flags = 0; /* Map HW rate index to 802.11 rate. */ if (!(rxdw3 & R92C_RXDW3_HT)) { switch (rate) { /* CCK. */ case 0: tap->wr_rate = 2; break; case 1: tap->wr_rate = 4; break; case 2: tap->wr_rate = 11; break; case 3: tap->wr_rate = 22; break; /* OFDM. */ case 4: tap->wr_rate = 12; break; case 5: tap->wr_rate = 18; break; case 6: tap->wr_rate = 24; break; case 7: tap->wr_rate = 36; break; case 8: tap->wr_rate = 48; break; case 9: tap->wr_rate = 72; break; case 10: tap->wr_rate = 96; break; case 11: tap->wr_rate = 108; break; } } else if (rate >= 12) { /* MCS0~15. */ /* Bit 7 set means HT MCS instead of rate. */ tap->wr_rate = 0x80 | (rate - 12); } tap->wr_dbm_antsignal = rssi; tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq); tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags); } *rssi_p = rssi; return (m); } static struct mbuf * urtwn_rxeof(struct usb_xfer *xfer, struct urtwn_data *data, int *rssi, int8_t *nf) { struct urtwn_softc *sc = data->sc; struct ifnet *ifp = sc->sc_ifp; struct r92c_rx_stat *stat; struct mbuf *m, *m0 = NULL, *prevm = NULL; uint32_t rxdw0; uint8_t *buf; int len, totlen, pktlen, infosz, npkts; usbd_xfer_status(xfer, &len, NULL, NULL, NULL); if (len < sizeof(*stat)) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); return (NULL); } buf = data->buf; /* Get the number of encapsulated frames. */ stat = (struct r92c_rx_stat *)buf; npkts = MS(le32toh(stat->rxdw2), R92C_RXDW2_PKTCNT); DPRINTFN(6, "Rx %d frames in one chunk\n", npkts); /* Process all of them. */ while (npkts-- > 0) { if (len < sizeof(*stat)) break; stat = (struct r92c_rx_stat *)buf; rxdw0 = le32toh(stat->rxdw0); pktlen = MS(rxdw0, R92C_RXDW0_PKTLEN); if (pktlen == 0) break; infosz = MS(rxdw0, R92C_RXDW0_INFOSZ) * 8; /* Make sure everything fits in xfer. */ totlen = sizeof(*stat) + infosz + pktlen; if (totlen > len) break; m = urtwn_rx_frame(sc, buf, pktlen, rssi); if (m0 == NULL) m0 = m; if (prevm == NULL) prevm = m; else { prevm->m_next = m; prevm = m; } /* Next chunk is 128-byte aligned. */ totlen = (totlen + 127) & ~127; buf += totlen; len -= totlen; } return (m0); } static void urtwn_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error) { struct urtwn_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211_frame *wh; struct ieee80211_node *ni; struct mbuf *m = NULL, *next; struct urtwn_data *data; int8_t nf; int rssi = 1; URTWN_ASSERT_LOCKED(sc); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: data = STAILQ_FIRST(&sc->sc_rx_active); if (data == NULL) goto tr_setup; STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next); m = urtwn_rxeof(xfer, data, &rssi, &nf); STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: data = STAILQ_FIRST(&sc->sc_rx_inactive); if (data == NULL) { KASSERT(m == NULL, ("mbuf isn't NULL")); return; } STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next); STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next); usbd_xfer_set_frame_data(xfer, 0, data->buf, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); /* * To avoid LOR we should unlock our private mutex here to call * ieee80211_input() because here is at the end of a USB * callback and safe to unlock. */ URTWN_UNLOCK(sc); while (m != NULL) { next = m->m_next; m->m_next = NULL; wh = mtod(m, struct ieee80211_frame *); ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh); nf = URTWN_NOISE_FLOOR; if (ni != NULL) { (void)ieee80211_input(ni, m, rssi, nf); ieee80211_free_node(ni); } else (void)ieee80211_input_all(ic, m, rssi, nf); m = next; } URTWN_LOCK(sc); break; default: /* needs it to the inactive queue due to a error. */ data = STAILQ_FIRST(&sc->sc_rx_active); if (data != NULL) { STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next); STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next); } if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); goto tr_setup; } break; } } static void urtwn_txeof(struct usb_xfer *xfer, struct urtwn_data *data) { struct urtwn_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct mbuf *m; URTWN_ASSERT_LOCKED(sc); /* * Do any tx complete callback. Note this must be done before releasing * the node reference. */ if (data->m) { m = data->m; if (m->m_flags & M_TXCB) { /* XXX status? */ ieee80211_process_callback(data->ni, m, 0); } m_freem(m); data->m = NULL; } if (data->ni) { ieee80211_free_node(data->ni); data->ni = NULL; } sc->sc_txtimer = 0; if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; } static void urtwn_bulk_tx_callback(struct usb_xfer *xfer, usb_error_t error) { struct urtwn_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct urtwn_data *data; URTWN_ASSERT_LOCKED(sc); switch (USB_GET_STATE(xfer)){ case USB_ST_TRANSFERRED: data = STAILQ_FIRST(&sc->sc_tx_active); if (data == NULL) goto tr_setup; STAILQ_REMOVE_HEAD(&sc->sc_tx_active, next); urtwn_txeof(xfer, data); STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, data, next); /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: data = STAILQ_FIRST(&sc->sc_tx_pending); if (data == NULL) { DPRINTF("%s: empty pending queue\n", __func__); return; } STAILQ_REMOVE_HEAD(&sc->sc_tx_pending, next); STAILQ_INSERT_TAIL(&sc->sc_tx_active, data, next); usbd_xfer_set_frame_data(xfer, 0, data->buf, data->buflen); usbd_transfer_submit(xfer); urtwn_start_locked(ifp, sc); break; default: data = STAILQ_FIRST(&sc->sc_tx_active); if (data == NULL) goto tr_setup; if (data->ni != NULL) { ieee80211_free_node(data->ni); data->ni = NULL; if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); } if (error != USB_ERR_CANCELLED) { usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static struct urtwn_data * _urtwn_getbuf(struct urtwn_softc *sc) { struct urtwn_data *bf; bf = STAILQ_FIRST(&sc->sc_tx_inactive); if (bf != NULL) STAILQ_REMOVE_HEAD(&sc->sc_tx_inactive, next); else bf = NULL; if (bf == NULL) DPRINTF("%s: %s\n", __func__, "out of xmit buffers"); return (bf); } static struct urtwn_data * urtwn_getbuf(struct urtwn_softc *sc) { struct urtwn_data *bf; URTWN_ASSERT_LOCKED(sc); bf = _urtwn_getbuf(sc); if (bf == NULL) { struct ifnet *ifp = sc->sc_ifp; DPRINTF("%s: stop queue\n", __func__); ifp->if_drv_flags |= IFF_DRV_OACTIVE; } return (bf); } static int urtwn_write_region_1(struct urtwn_softc *sc, uint16_t addr, uint8_t *buf, int len) { usb_device_request_t req; req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = R92C_REQ_REGS; USETW(req.wValue, addr); USETW(req.wIndex, 0); USETW(req.wLength, len); return (urtwn_do_request(sc, &req, buf)); } static void urtwn_write_1(struct urtwn_softc *sc, uint16_t addr, uint8_t val) { urtwn_write_region_1(sc, addr, &val, 1); } static void urtwn_write_2(struct urtwn_softc *sc, uint16_t addr, uint16_t val) { val = htole16(val); urtwn_write_region_1(sc, addr, (uint8_t *)&val, 2); } static void urtwn_write_4(struct urtwn_softc *sc, uint16_t addr, uint32_t val) { val = htole32(val); urtwn_write_region_1(sc, addr, (uint8_t *)&val, 4); } static int urtwn_read_region_1(struct urtwn_softc *sc, uint16_t addr, uint8_t *buf, int len) { usb_device_request_t req; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = R92C_REQ_REGS; USETW(req.wValue, addr); USETW(req.wIndex, 0); USETW(req.wLength, len); return (urtwn_do_request(sc, &req, buf)); } static uint8_t urtwn_read_1(struct urtwn_softc *sc, uint16_t addr) { uint8_t val; if (urtwn_read_region_1(sc, addr, &val, 1) != 0) return (0xff); return (val); } static uint16_t urtwn_read_2(struct urtwn_softc *sc, uint16_t addr) { uint16_t val; if (urtwn_read_region_1(sc, addr, (uint8_t *)&val, 2) != 0) return (0xffff); return (le16toh(val)); } static uint32_t urtwn_read_4(struct urtwn_softc *sc, uint16_t addr) { uint32_t val; if (urtwn_read_region_1(sc, addr, (uint8_t *)&val, 4) != 0) return (0xffffffff); return (le32toh(val)); } static int urtwn_fw_cmd(struct urtwn_softc *sc, uint8_t id, const void *buf, int len) { struct r92c_fw_cmd cmd; int ntries; /* Wait for current FW box to be empty. */ for (ntries = 0; ntries < 100; ntries++) { if (!(urtwn_read_1(sc, R92C_HMETFR) & (1 << sc->fwcur))) break; urtwn_ms_delay(sc); } if (ntries == 100) { device_printf(sc->sc_dev, "could not send firmware command\n"); return (ETIMEDOUT); } memset(&cmd, 0, sizeof(cmd)); cmd.id = id; if (len > 3) cmd.id |= R92C_CMD_FLAG_EXT; KASSERT(len <= sizeof(cmd.msg), ("urtwn_fw_cmd\n")); memcpy(cmd.msg, buf, len); /* Write the first word last since that will trigger the FW. */ urtwn_write_region_1(sc, R92C_HMEBOX_EXT(sc->fwcur), (uint8_t *)&cmd + 4, 2); urtwn_write_region_1(sc, R92C_HMEBOX(sc->fwcur), (uint8_t *)&cmd + 0, 4); sc->fwcur = (sc->fwcur + 1) % R92C_H2C_NBOX; return (0); } static __inline void urtwn_rf_write(struct urtwn_softc *sc, int chain, uint8_t addr, uint32_t val) { sc->sc_rf_write(sc, chain, addr, val); } static void urtwn_r92c_rf_write(struct urtwn_softc *sc, int chain, uint8_t addr, uint32_t val) { urtwn_bb_write(sc, R92C_LSSI_PARAM(chain), SM(R92C_LSSI_PARAM_ADDR, addr) | SM(R92C_LSSI_PARAM_DATA, val)); } static void urtwn_r88e_rf_write(struct urtwn_softc *sc, int chain, uint8_t addr, uint32_t val) { urtwn_bb_write(sc, R92C_LSSI_PARAM(chain), SM(R88E_LSSI_PARAM_ADDR, addr) | SM(R92C_LSSI_PARAM_DATA, val)); } static uint32_t urtwn_rf_read(struct urtwn_softc *sc, int chain, uint8_t addr) { uint32_t reg[R92C_MAX_CHAINS], val; reg[0] = urtwn_bb_read(sc, R92C_HSSI_PARAM2(0)); if (chain != 0) reg[chain] = urtwn_bb_read(sc, R92C_HSSI_PARAM2(chain)); urtwn_bb_write(sc, R92C_HSSI_PARAM2(0), reg[0] & ~R92C_HSSI_PARAM2_READ_EDGE); urtwn_ms_delay(sc); urtwn_bb_write(sc, R92C_HSSI_PARAM2(chain), RW(reg[chain], R92C_HSSI_PARAM2_READ_ADDR, addr) | R92C_HSSI_PARAM2_READ_EDGE); urtwn_ms_delay(sc); urtwn_bb_write(sc, R92C_HSSI_PARAM2(0), reg[0] | R92C_HSSI_PARAM2_READ_EDGE); urtwn_ms_delay(sc); if (urtwn_bb_read(sc, R92C_HSSI_PARAM1(chain)) & R92C_HSSI_PARAM1_PI) val = urtwn_bb_read(sc, R92C_HSPI_READBACK(chain)); else val = urtwn_bb_read(sc, R92C_LSSI_READBACK(chain)); return (MS(val, R92C_LSSI_READBACK_DATA)); } static int urtwn_llt_write(struct urtwn_softc *sc, uint32_t addr, uint32_t data) { int ntries; urtwn_write_4(sc, R92C_LLT_INIT, SM(R92C_LLT_INIT_OP, R92C_LLT_INIT_OP_WRITE) | SM(R92C_LLT_INIT_ADDR, addr) | SM(R92C_LLT_INIT_DATA, data)); /* Wait for write operation to complete. */ for (ntries = 0; ntries < 20; ntries++) { if (MS(urtwn_read_4(sc, R92C_LLT_INIT), R92C_LLT_INIT_OP) == R92C_LLT_INIT_OP_NO_ACTIVE) return (0); urtwn_ms_delay(sc); } return (ETIMEDOUT); } static uint8_t urtwn_efuse_read_1(struct urtwn_softc *sc, uint16_t addr) { uint32_t reg; int ntries; reg = urtwn_read_4(sc, R92C_EFUSE_CTRL); reg = RW(reg, R92C_EFUSE_CTRL_ADDR, addr); reg &= ~R92C_EFUSE_CTRL_VALID; urtwn_write_4(sc, R92C_EFUSE_CTRL, reg); /* Wait for read operation to complete. */ for (ntries = 0; ntries < 100; ntries++) { reg = urtwn_read_4(sc, R92C_EFUSE_CTRL); if (reg & R92C_EFUSE_CTRL_VALID) return (MS(reg, R92C_EFUSE_CTRL_DATA)); urtwn_ms_delay(sc); } device_printf(sc->sc_dev, "could not read efuse byte at address 0x%x\n", addr); return (0xff); } static void urtwn_efuse_read(struct urtwn_softc *sc) { uint8_t *rom = (uint8_t *)&sc->rom; uint16_t addr = 0; uint32_t reg; uint8_t off, msk; int i; urtwn_efuse_switch_power(sc); memset(&sc->rom, 0xff, sizeof(sc->rom)); while (addr < 512) { reg = urtwn_efuse_read_1(sc, addr); if (reg == 0xff) break; addr++; off = reg >> 4; msk = reg & 0xf; for (i = 0; i < 4; i++) { if (msk & (1 << i)) continue; rom[off * 8 + i * 2 + 0] = urtwn_efuse_read_1(sc, addr); addr++; rom[off * 8 + i * 2 + 1] = urtwn_efuse_read_1(sc, addr); addr++; } } #ifdef URTWN_DEBUG if (urtwn_debug >= 2) { /* Dump ROM content. */ printf("\n"); for (i = 0; i < sizeof(sc->rom); i++) printf("%02x:", rom[i]); printf("\n"); } #endif } static void urtwn_efuse_switch_power(struct urtwn_softc *sc) { uint32_t reg; reg = urtwn_read_2(sc, R92C_SYS_ISO_CTRL); if (!(reg & R92C_SYS_ISO_CTRL_PWC_EV12V)) { urtwn_write_2(sc, R92C_SYS_ISO_CTRL, reg | R92C_SYS_ISO_CTRL_PWC_EV12V); } reg = urtwn_read_2(sc, R92C_SYS_FUNC_EN); if (!(reg & R92C_SYS_FUNC_EN_ELDR)) { urtwn_write_2(sc, R92C_SYS_FUNC_EN, reg | R92C_SYS_FUNC_EN_ELDR); } reg = urtwn_read_2(sc, R92C_SYS_CLKR); if ((reg & (R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M)) != (R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M)) { urtwn_write_2(sc, R92C_SYS_CLKR, reg | R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M); } } static int urtwn_read_chipid(struct urtwn_softc *sc) { uint32_t reg; if (sc->chip & URTWN_CHIP_88E) return (0); reg = urtwn_read_4(sc, R92C_SYS_CFG); if (reg & R92C_SYS_CFG_TRP_VAUX_EN) return (EIO); if (reg & R92C_SYS_CFG_TYPE_92C) { sc->chip |= URTWN_CHIP_92C; /* Check if it is a castrated 8192C. */ if (MS(urtwn_read_4(sc, R92C_HPON_FSM), R92C_HPON_FSM_CHIP_BONDING_ID) == R92C_HPON_FSM_CHIP_BONDING_ID_92C_1T2R) sc->chip |= URTWN_CHIP_92C_1T2R; } if (reg & R92C_SYS_CFG_VENDOR_UMC) { sc->chip |= URTWN_CHIP_UMC; if (MS(reg, R92C_SYS_CFG_CHIP_VER_RTL) == 0) sc->chip |= URTWN_CHIP_UMC_A_CUT; } return (0); } static void urtwn_read_rom(struct urtwn_softc *sc) { struct r92c_rom *rom = &sc->rom; /* Read full ROM image. */ urtwn_efuse_read(sc); /* XXX Weird but this is what the vendor driver does. */ sc->pa_setting = urtwn_efuse_read_1(sc, 0x1fa); DPRINTF("PA setting=0x%x\n", sc->pa_setting); sc->board_type = MS(rom->rf_opt1, R92C_ROM_RF1_BOARD_TYPE); sc->regulatory = MS(rom->rf_opt1, R92C_ROM_RF1_REGULATORY); DPRINTF("regulatory type=%d\n", sc->regulatory); IEEE80211_ADDR_COPY(sc->sc_bssid, rom->macaddr); sc->sc_rf_write = urtwn_r92c_rf_write; sc->sc_power_on = urtwn_r92c_power_on; sc->sc_dma_init = urtwn_r92c_dma_init; } static void urtwn_r88e_read_rom(struct urtwn_softc *sc) { uint8_t *rom = sc->r88e_rom; uint16_t addr = 0; uint32_t reg; uint8_t off, msk, tmp; int i; off = 0; urtwn_efuse_switch_power(sc); /* Read full ROM image. */ memset(&sc->r88e_rom, 0xff, sizeof(sc->r88e_rom)); while (addr < 1024) { reg = urtwn_efuse_read_1(sc, addr); if (reg == 0xff) break; addr++; if ((reg & 0x1f) == 0x0f) { tmp = (reg & 0xe0) >> 5; reg = urtwn_efuse_read_1(sc, addr); if ((reg & 0x0f) != 0x0f) off = ((reg & 0xf0) >> 1) | tmp; addr++; } else off = reg >> 4; msk = reg & 0xf; for (i = 0; i < 4; i++) { if (msk & (1 << i)) continue; rom[off * 8 + i * 2 + 0] = urtwn_efuse_read_1(sc, addr); addr++; rom[off * 8 + i * 2 + 1] = urtwn_efuse_read_1(sc, addr); addr++; } } addr = 0x10; for (i = 0; i < 6; i++) sc->cck_tx_pwr[i] = sc->r88e_rom[addr++]; for (i = 0; i < 5; i++) sc->ht40_tx_pwr[i] = sc->r88e_rom[addr++]; sc->bw20_tx_pwr_diff = (sc->r88e_rom[addr] & 0xf0) >> 4; if (sc->bw20_tx_pwr_diff & 0x08) sc->bw20_tx_pwr_diff |= 0xf0; sc->ofdm_tx_pwr_diff = (sc->r88e_rom[addr] & 0xf); if (sc->ofdm_tx_pwr_diff & 0x08) sc->ofdm_tx_pwr_diff |= 0xf0; sc->regulatory = MS(sc->r88e_rom[0xc1], R92C_ROM_RF1_REGULATORY); IEEE80211_ADDR_COPY(sc->sc_bssid, &sc->r88e_rom[0xd7]); sc->sc_rf_write = urtwn_r88e_rf_write; sc->sc_power_on = urtwn_r88e_power_on; sc->sc_dma_init = urtwn_r88e_dma_init; } /* * Initialize rate adaptation in firmware. */ static int urtwn_ra_init(struct urtwn_softc *sc) { static const uint8_t map[] = { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 }; struct ieee80211com *ic = sc->sc_ifp->if_l2com; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); struct ieee80211_node *ni; struct ieee80211_rateset *rs; struct r92c_fw_cmd_macid_cfg cmd; uint32_t rates, basicrates; uint8_t mode; int maxrate, maxbasicrate, error, i, j; ni = ieee80211_ref_node(vap->iv_bss); rs = &ni->ni_rates; /* Get normal and basic rates mask. */ rates = basicrates = 0; maxrate = maxbasicrate = 0; for (i = 0; i < rs->rs_nrates; i++) { /* Convert 802.11 rate to HW rate index. */ for (j = 0; j < nitems(map); j++) if ((rs->rs_rates[i] & IEEE80211_RATE_VAL) == map[j]) break; if (j == nitems(map)) /* Unknown rate, skip. */ continue; rates |= 1 << j; if (j > maxrate) maxrate = j; if (rs->rs_rates[i] & IEEE80211_RATE_BASIC) { basicrates |= 1 << j; if (j > maxbasicrate) maxbasicrate = j; } } if (ic->ic_curmode == IEEE80211_MODE_11B) mode = R92C_RAID_11B; else mode = R92C_RAID_11BG; DPRINTF("mode=0x%x rates=0x%08x, basicrates=0x%08x\n", mode, rates, basicrates); /* Set rates mask for group addressed frames. */ cmd.macid = URTWN_MACID_BC | URTWN_MACID_VALID; cmd.mask = htole32(mode << 28 | basicrates); error = urtwn_fw_cmd(sc, R92C_CMD_MACID_CONFIG, &cmd, sizeof(cmd)); if (error != 0) { ieee80211_free_node(ni); device_printf(sc->sc_dev, "could not add broadcast station\n"); return (error); } /* Set initial MRR rate. */ DPRINTF("maxbasicrate=%d\n", maxbasicrate); urtwn_write_1(sc, R92C_INIDATA_RATE_SEL(URTWN_MACID_BC), maxbasicrate); /* Set rates mask for unicast frames. */ cmd.macid = URTWN_MACID_BSS | URTWN_MACID_VALID; cmd.mask = htole32(mode << 28 | rates); error = urtwn_fw_cmd(sc, R92C_CMD_MACID_CONFIG, &cmd, sizeof(cmd)); if (error != 0) { ieee80211_free_node(ni); device_printf(sc->sc_dev, "could not add BSS station\n"); return (error); } /* Set initial MRR rate. */ DPRINTF("maxrate=%d\n", maxrate); urtwn_write_1(sc, R92C_INIDATA_RATE_SEL(URTWN_MACID_BSS), maxrate); /* Indicate highest supported rate. */ ni->ni_txrate = rs->rs_rates[rs->rs_nrates - 1]; ieee80211_free_node(ni); return (0); } void urtwn_tsf_sync_enable(struct urtwn_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); struct ieee80211_node *ni = vap->iv_bss; uint64_t tsf; /* Enable TSF synchronization. */ urtwn_write_1(sc, R92C_BCN_CTRL, urtwn_read_1(sc, R92C_BCN_CTRL) & ~R92C_BCN_CTRL_DIS_TSF_UDT0); urtwn_write_1(sc, R92C_BCN_CTRL, urtwn_read_1(sc, R92C_BCN_CTRL) & ~R92C_BCN_CTRL_EN_BCN); /* Set initial TSF. */ memcpy(&tsf, ni->ni_tstamp.data, 8); tsf = le64toh(tsf); tsf = tsf - (tsf % (vap->iv_bss->ni_intval * IEEE80211_DUR_TU)); tsf -= IEEE80211_DUR_TU; urtwn_write_4(sc, R92C_TSFTR + 0, tsf); urtwn_write_4(sc, R92C_TSFTR + 4, tsf >> 32); urtwn_write_1(sc, R92C_BCN_CTRL, urtwn_read_1(sc, R92C_BCN_CTRL) | R92C_BCN_CTRL_EN_BCN); } static void urtwn_set_led(struct urtwn_softc *sc, int led, int on) { uint8_t reg; if (led == URTWN_LED_LINK) { if (sc->chip & URTWN_CHIP_88E) { reg = urtwn_read_1(sc, R92C_LEDCFG2) & 0xf0; urtwn_write_1(sc, R92C_LEDCFG2, reg | 0x60); if (!on) { reg = urtwn_read_1(sc, R92C_LEDCFG2) & 0x90; urtwn_write_1(sc, R92C_LEDCFG2, reg | R92C_LEDCFG0_DIS); urtwn_write_1(sc, R92C_MAC_PINMUX_CFG, urtwn_read_1(sc, R92C_MAC_PINMUX_CFG) & 0xfe); } } else { reg = urtwn_read_1(sc, R92C_LEDCFG0) & 0x70; if (!on) reg |= R92C_LEDCFG0_DIS; urtwn_write_1(sc, R92C_LEDCFG0, reg); } sc->ledlink = on; /* Save LED state. */ } } static int urtwn_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg) { struct urtwn_vap *uvp = URTWN_VAP(vap); struct ieee80211com *ic = vap->iv_ic; struct urtwn_softc *sc = ic->ic_ifp->if_softc; struct ieee80211_node *ni; enum ieee80211_state ostate; uint32_t reg; ostate = vap->iv_state; DPRINTF("%s -> %s\n", ieee80211_state_name[ostate], ieee80211_state_name[nstate]); IEEE80211_UNLOCK(ic); URTWN_LOCK(sc); callout_stop(&sc->sc_watchdog_ch); if (ostate == IEEE80211_S_RUN) { /* Turn link LED off. */ urtwn_set_led(sc, URTWN_LED_LINK, 0); /* Set media status to 'No Link'. */ reg = urtwn_read_4(sc, R92C_CR); reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_NOLINK); urtwn_write_4(sc, R92C_CR, reg); /* Stop Rx of data frames. */ urtwn_write_2(sc, R92C_RXFLTMAP2, 0); /* Rest TSF. */ urtwn_write_1(sc, R92C_DUAL_TSF_RST, 0x03); /* Disable TSF synchronization. */ urtwn_write_1(sc, R92C_BCN_CTRL, urtwn_read_1(sc, R92C_BCN_CTRL) | R92C_BCN_CTRL_DIS_TSF_UDT0); /* Reset EDCA parameters. */ urtwn_write_4(sc, R92C_EDCA_VO_PARAM, 0x002f3217); urtwn_write_4(sc, R92C_EDCA_VI_PARAM, 0x005e4317); urtwn_write_4(sc, R92C_EDCA_BE_PARAM, 0x00105320); urtwn_write_4(sc, R92C_EDCA_BK_PARAM, 0x0000a444); } switch (nstate) { case IEEE80211_S_INIT: /* Turn link LED off. */ urtwn_set_led(sc, URTWN_LED_LINK, 0); break; case IEEE80211_S_SCAN: if (ostate != IEEE80211_S_SCAN) { /* Allow Rx from any BSSID. */ urtwn_write_4(sc, R92C_RCR, urtwn_read_4(sc, R92C_RCR) & ~(R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN)); /* Set gain for scanning. */ reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(0)); reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x20); urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), reg); if (!(sc->chip & URTWN_CHIP_88E)) { reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(1)); reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x20); urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(1), reg); } } /* Make link LED blink during scan. */ urtwn_set_led(sc, URTWN_LED_LINK, !sc->ledlink); /* Pause AC Tx queues. */ urtwn_write_1(sc, R92C_TXPAUSE, urtwn_read_1(sc, R92C_TXPAUSE) | 0x0f); urtwn_set_chan(sc, ic->ic_curchan, NULL); break; case IEEE80211_S_AUTH: /* Set initial gain under link. */ reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(0)); reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x32); urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), reg); if (!(sc->chip & URTWN_CHIP_88E)) { reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(1)); reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x32); urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(1), reg); } urtwn_set_chan(sc, ic->ic_curchan, NULL); break; case IEEE80211_S_RUN: if (vap->iv_opmode == IEEE80211_M_MONITOR) { /* Enable Rx of data frames. */ urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff); /* Turn link LED on. */ urtwn_set_led(sc, URTWN_LED_LINK, 1); break; } ni = ieee80211_ref_node(vap->iv_bss); /* Set media status to 'Associated'. */ reg = urtwn_read_4(sc, R92C_CR); reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_INFRA); urtwn_write_4(sc, R92C_CR, reg); /* Set BSSID. */ urtwn_write_4(sc, R92C_BSSID + 0, LE_READ_4(&ni->ni_bssid[0])); urtwn_write_4(sc, R92C_BSSID + 4, LE_READ_2(&ni->ni_bssid[4])); if (ic->ic_curmode == IEEE80211_MODE_11B) urtwn_write_1(sc, R92C_INIRTS_RATE_SEL, 0); else /* 802.11b/g */ urtwn_write_1(sc, R92C_INIRTS_RATE_SEL, 3); /* Enable Rx of data frames. */ urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff); /* Flush all AC queues. */ urtwn_write_1(sc, R92C_TXPAUSE, 0); /* Set beacon interval. */ urtwn_write_2(sc, R92C_BCN_INTERVAL, ni->ni_intval); /* Allow Rx from our BSSID only. */ urtwn_write_4(sc, R92C_RCR, urtwn_read_4(sc, R92C_RCR) | R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN); /* Enable TSF synchronization. */ urtwn_tsf_sync_enable(sc); urtwn_write_1(sc, R92C_SIFS_CCK + 1, 10); urtwn_write_1(sc, R92C_SIFS_OFDM + 1, 10); urtwn_write_1(sc, R92C_SPEC_SIFS + 1, 10); urtwn_write_1(sc, R92C_MAC_SPEC_SIFS + 1, 10); urtwn_write_1(sc, R92C_R2T_SIFS + 1, 10); urtwn_write_1(sc, R92C_T2T_SIFS + 1, 10); /* Intialize rate adaptation. */ if (sc->chip & URTWN_CHIP_88E) ni->ni_txrate = ni->ni_rates.rs_rates[ni->ni_rates.rs_nrates-1]; else urtwn_ra_init(sc); /* Turn link LED on. */ urtwn_set_led(sc, URTWN_LED_LINK, 1); sc->avg_pwdb = -1; /* Reset average RSSI. */ /* Reset temperature calibration state machine. */ sc->thcal_state = 0; sc->thcal_lctemp = 0; ieee80211_free_node(ni); break; default: break; } URTWN_UNLOCK(sc); IEEE80211_LOCK(ic); return(uvp->newstate(vap, nstate, arg)); } static void urtwn_watchdog(void *arg) { struct urtwn_softc *sc = arg; struct ifnet *ifp = sc->sc_ifp; if (sc->sc_txtimer > 0) { if (--sc->sc_txtimer == 0) { device_printf(sc->sc_dev, "device timeout\n"); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); return; } callout_reset(&sc->sc_watchdog_ch, hz, urtwn_watchdog, sc); } } static void urtwn_update_avgrssi(struct urtwn_softc *sc, int rate, int8_t rssi) { int pwdb; /* Convert antenna signal to percentage. */ if (rssi <= -100 || rssi >= 20) pwdb = 0; else if (rssi >= 0) pwdb = 100; else pwdb = 100 + rssi; if (!(sc->chip & URTWN_CHIP_88E)) { if (rate <= 3) { /* CCK gain is smaller than OFDM/MCS gain. */ pwdb += 6; if (pwdb > 100) pwdb = 100; if (pwdb <= 14) pwdb -= 4; else if (pwdb <= 26) pwdb -= 8; else if (pwdb <= 34) pwdb -= 6; else if (pwdb <= 42) pwdb -= 2; } } if (sc->avg_pwdb == -1) /* Init. */ sc->avg_pwdb = pwdb; else if (sc->avg_pwdb < pwdb) sc->avg_pwdb = ((sc->avg_pwdb * 19 + pwdb) / 20) + 1; else sc->avg_pwdb = ((sc->avg_pwdb * 19 + pwdb) / 20); DPRINTFN(4, "PWDB=%d EMA=%d\n", pwdb, sc->avg_pwdb); } static int8_t urtwn_get_rssi(struct urtwn_softc *sc, int rate, void *physt) { static const int8_t cckoff[] = { 16, -12, -26, -46 }; struct r92c_rx_phystat *phy; struct r92c_rx_cck *cck; uint8_t rpt; int8_t rssi; if (rate <= 3) { cck = (struct r92c_rx_cck *)physt; if (sc->sc_flags & URTWN_FLAG_CCK_HIPWR) { rpt = (cck->agc_rpt >> 5) & 0x3; rssi = (cck->agc_rpt & 0x1f) << 1; } else { rpt = (cck->agc_rpt >> 6) & 0x3; rssi = cck->agc_rpt & 0x3e; } rssi = cckoff[rpt] - rssi; } else { /* OFDM/HT. */ phy = (struct r92c_rx_phystat *)physt; rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 110; } return (rssi); } static int8_t urtwn_r88e_get_rssi(struct urtwn_softc *sc, int rate, void *physt) { struct r92c_rx_phystat *phy; struct r88e_rx_cck *cck; uint8_t cck_agc_rpt, lna_idx, vga_idx; int8_t rssi; rssi = 0; if (rate <= 3) { cck = (struct r88e_rx_cck *)physt; cck_agc_rpt = cck->agc_rpt; lna_idx = (cck_agc_rpt & 0xe0) >> 5; vga_idx = cck_agc_rpt & 0x1f; switch (lna_idx) { case 7: if (vga_idx <= 27) rssi = -100 + 2* (27 - vga_idx); else rssi = -100; break; case 6: rssi = -48 + 2 * (2 - vga_idx); break; case 5: rssi = -42 + 2 * (7 - vga_idx); break; case 4: rssi = -36 + 2 * (7 - vga_idx); break; case 3: rssi = -24 + 2 * (7 - vga_idx); break; case 2: rssi = -12 + 2 * (5 - vga_idx); break; case 1: rssi = 8 - (2 * vga_idx); break; case 0: rssi = 14 - (2 * vga_idx); break; } rssi += 6; } else { /* OFDM/HT. */ phy = (struct r92c_rx_phystat *)physt; rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 110; } return (rssi); } static int urtwn_tx_start(struct urtwn_softc *sc, struct ieee80211_node *ni, struct mbuf *m0, struct urtwn_data *data) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211_frame *wh; struct ieee80211_key *k; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211vap *vap = ni->ni_vap; struct usb_xfer *xfer; struct r92c_tx_desc *txd; uint8_t raid, type; uint16_t sum; int i, hasqos, xferlen; struct usb_xfer *urtwn_pipes[4] = { sc->sc_xfer[URTWN_BULK_TX_BE], sc->sc_xfer[URTWN_BULK_TX_BK], sc->sc_xfer[URTWN_BULK_TX_VI], sc->sc_xfer[URTWN_BULK_TX_VO] }; URTWN_ASSERT_LOCKED(sc); /* * Software crypto. */ wh = mtod(m0, struct ieee80211_frame *); type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK; if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) { k = ieee80211_crypto_encap(ni, m0); if (k == NULL) { device_printf(sc->sc_dev, "ieee80211_crypto_encap returns NULL.\n"); /* XXX we don't expect the fragmented frames */ m_freem(m0); return (ENOBUFS); } /* in case packet header moved, reset pointer */ wh = mtod(m0, struct ieee80211_frame *); } switch (type) { case IEEE80211_FC0_TYPE_CTL: case IEEE80211_FC0_TYPE_MGT: xfer = sc->sc_xfer[URTWN_BULK_TX_VO]; break; default: KASSERT(M_WME_GETAC(m0) < 4, ("unsupported WME pipe %d", M_WME_GETAC(m0))); xfer = urtwn_pipes[M_WME_GETAC(m0)]; break; } hasqos = 0; /* Fill Tx descriptor. */ txd = (struct r92c_tx_desc *)data->buf; memset(txd, 0, sizeof(*txd)); txd->txdw0 |= htole32( SM(R92C_TXDW0_PKTLEN, m0->m_pkthdr.len) | SM(R92C_TXDW0_OFFSET, sizeof(*txd)) | R92C_TXDW0_OWN | R92C_TXDW0_FSG | R92C_TXDW0_LSG); if (IEEE80211_IS_MULTICAST(wh->i_addr1)) txd->txdw0 |= htole32(R92C_TXDW0_BMCAST); if (!IEEE80211_IS_MULTICAST(wh->i_addr1) && type == IEEE80211_FC0_TYPE_DATA) { if (ic->ic_curmode == IEEE80211_MODE_11B) raid = R92C_RAID_11B; else raid = R92C_RAID_11BG; if (sc->chip & URTWN_CHIP_88E) { txd->txdw1 |= htole32( SM(R88E_TXDW1_MACID, URTWN_MACID_BSS) | SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_BE) | SM(R92C_TXDW1_RAID, raid)); txd->txdw2 |= htole32(R88E_TXDW2_AGGBK); } else { txd->txdw1 |= htole32( SM(R92C_TXDW1_MACID, URTWN_MACID_BSS) | SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_BE) | SM(R92C_TXDW1_RAID, raid) | R92C_TXDW1_AGGBK); } if (ic->ic_flags & IEEE80211_F_USEPROT) { if (ic->ic_protmode == IEEE80211_PROT_CTSONLY) { txd->txdw4 |= htole32(R92C_TXDW4_CTS2SELF | R92C_TXDW4_HWRTSEN); } else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS) { txd->txdw4 |= htole32(R92C_TXDW4_RTSEN | R92C_TXDW4_HWRTSEN); } } /* Send RTS at OFDM24. */ txd->txdw4 |= htole32(SM(R92C_TXDW4_RTSRATE, 8)); txd->txdw5 |= htole32(0x0001ff00); /* Send data at OFDM54. */ if (sc->chip & URTWN_CHIP_88E) txd->txdw5 |= htole32(0x13 & 0x3f); else txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 11)); } else { txd->txdw1 |= htole32( SM(R92C_TXDW1_MACID, 0) | SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_MGNT) | SM(R92C_TXDW1_RAID, R92C_RAID_11B)); /* Force CCK1. */ txd->txdw4 |= htole32(R92C_TXDW4_DRVRATE); txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 0)); } /* Set sequence number (already little endian). */ txd->txdseq |= *(uint16_t *)wh->i_seq; if (!hasqos) { /* Use HW sequence numbering for non-QoS frames. */ txd->txdw4 |= htole32(R92C_TXDW4_HWSEQ); txd->txdseq |= htole16(0x8000); } else txd->txdw4 |= htole32(R92C_TXDW4_QOS); /* Compute Tx descriptor checksum. */ sum = 0; for (i = 0; i < sizeof(*txd) / 2; i++) sum ^= ((uint16_t *)txd)[i]; txd->txdsum = sum; /* NB: already little endian. */ if (ieee80211_radiotap_active_vap(vap)) { struct urtwn_tx_radiotap_header *tap = &sc->sc_txtap; tap->wt_flags = 0; tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq); tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags); ieee80211_radiotap_tx(vap, m0); } xferlen = sizeof(*txd) + m0->m_pkthdr.len; m_copydata(m0, 0, m0->m_pkthdr.len, (caddr_t)&txd[1]); data->buflen = xferlen; data->ni = ni; data->m = m0; STAILQ_INSERT_TAIL(&sc->sc_tx_pending, data, next); usbd_transfer_start(xfer); return (0); } static void urtwn_start(struct ifnet *ifp) { struct urtwn_softc *sc = ifp->if_softc; if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) return; URTWN_LOCK(sc); urtwn_start_locked(ifp, sc); URTWN_UNLOCK(sc); } static void urtwn_start_locked(struct ifnet *ifp, struct urtwn_softc *sc) { struct ieee80211_node *ni; struct mbuf *m; struct urtwn_data *bf; URTWN_ASSERT_LOCKED(sc); for (;;) { IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; bf = urtwn_getbuf(sc); if (bf == NULL) { IFQ_DRV_PREPEND(&ifp->if_snd, m); break; } ni = (struct ieee80211_node *)m->m_pkthdr.rcvif; m->m_pkthdr.rcvif = NULL; if (urtwn_tx_start(sc, ni, m, bf) != 0) { if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next); ieee80211_free_node(ni); break; } sc->sc_txtimer = 5; callout_reset(&sc->sc_watchdog_ch, hz, urtwn_watchdog, sc); } } static int urtwn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) { struct urtwn_softc *sc = ifp->if_softc; struct ieee80211com *ic = ifp->if_l2com; struct ifreq *ifr = (struct ifreq *) data; int error = 0, startall = 0; URTWN_LOCK(sc); error = (sc->sc_flags & URTWN_DETACHED) ? ENXIO : 0; URTWN_UNLOCK(sc); if (error != 0) return (error); switch (cmd) { case SIOCSIFFLAGS: if (ifp->if_flags & IFF_UP) { if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) { urtwn_init(ifp->if_softc); startall = 1; } } else { if (ifp->if_drv_flags & IFF_DRV_RUNNING) urtwn_stop(ifp); } if (startall) ieee80211_start_all(ic); break; case SIOCGIFMEDIA: error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd); break; case SIOCGIFADDR: error = ether_ioctl(ifp, cmd, data); break; default: error = EINVAL; break; } return (error); } static int urtwn_alloc_list(struct urtwn_softc *sc, struct urtwn_data data[], int ndata, int maxsz) { int i, error; for (i = 0; i < ndata; i++) { struct urtwn_data *dp = &data[i]; dp->sc = sc; dp->m = NULL; dp->buf = malloc(maxsz, M_USBDEV, M_NOWAIT); if (dp->buf == NULL) { device_printf(sc->sc_dev, "could not allocate buffer\n"); error = ENOMEM; goto fail; } dp->ni = NULL; } return (0); fail: urtwn_free_list(sc, data, ndata); return (error); } static int urtwn_alloc_rx_list(struct urtwn_softc *sc) { int error, i; error = urtwn_alloc_list(sc, sc->sc_rx, URTWN_RX_LIST_COUNT, URTWN_RXBUFSZ); if (error != 0) return (error); STAILQ_INIT(&sc->sc_rx_active); STAILQ_INIT(&sc->sc_rx_inactive); for (i = 0; i < URTWN_RX_LIST_COUNT; i++) STAILQ_INSERT_HEAD(&sc->sc_rx_inactive, &sc->sc_rx[i], next); return (0); } static int urtwn_alloc_tx_list(struct urtwn_softc *sc) { int error, i; error = urtwn_alloc_list(sc, sc->sc_tx, URTWN_TX_LIST_COUNT, URTWN_TXBUFSZ); if (error != 0) return (error); STAILQ_INIT(&sc->sc_tx_active); STAILQ_INIT(&sc->sc_tx_inactive); STAILQ_INIT(&sc->sc_tx_pending); for (i = 0; i < URTWN_TX_LIST_COUNT; i++) STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, &sc->sc_tx[i], next); return (0); } static __inline int urtwn_power_on(struct urtwn_softc *sc) { return sc->sc_power_on(sc); } static int urtwn_r92c_power_on(struct urtwn_softc *sc) { uint32_t reg; int ntries; /* Wait for autoload done bit. */ for (ntries = 0; ntries < 1000; ntries++) { if (urtwn_read_1(sc, R92C_APS_FSMCO) & R92C_APS_FSMCO_PFM_ALDN) break; urtwn_ms_delay(sc); } if (ntries == 1000) { device_printf(sc->sc_dev, "timeout waiting for chip autoload\n"); return (ETIMEDOUT); } /* Unlock ISO/CLK/Power control register. */ urtwn_write_1(sc, R92C_RSV_CTRL, 0); /* Move SPS into PWM mode. */ urtwn_write_1(sc, R92C_SPS0_CTRL, 0x2b); urtwn_ms_delay(sc); reg = urtwn_read_1(sc, R92C_LDOV12D_CTRL); if (!(reg & R92C_LDOV12D_CTRL_LDV12_EN)) { urtwn_write_1(sc, R92C_LDOV12D_CTRL, reg | R92C_LDOV12D_CTRL_LDV12_EN); urtwn_ms_delay(sc); urtwn_write_1(sc, R92C_SYS_ISO_CTRL, urtwn_read_1(sc, R92C_SYS_ISO_CTRL) & ~R92C_SYS_ISO_CTRL_MD2PP); } /* Auto enable WLAN. */ urtwn_write_2(sc, R92C_APS_FSMCO, urtwn_read_2(sc, R92C_APS_FSMCO) | R92C_APS_FSMCO_APFM_ONMAC); for (ntries = 0; ntries < 1000; ntries++) { if (!(urtwn_read_2(sc, R92C_APS_FSMCO) & R92C_APS_FSMCO_APFM_ONMAC)) break; urtwn_ms_delay(sc); } if (ntries == 1000) { device_printf(sc->sc_dev, "timeout waiting for MAC auto ON\n"); return (ETIMEDOUT); } /* Enable radio, GPIO and LED functions. */ urtwn_write_2(sc, R92C_APS_FSMCO, R92C_APS_FSMCO_AFSM_HSUS | R92C_APS_FSMCO_PDN_EN | R92C_APS_FSMCO_PFM_ALDN); /* Release RF digital isolation. */ urtwn_write_2(sc, R92C_SYS_ISO_CTRL, urtwn_read_2(sc, R92C_SYS_ISO_CTRL) & ~R92C_SYS_ISO_CTRL_DIOR); /* Initialize MAC. */ urtwn_write_1(sc, R92C_APSD_CTRL, urtwn_read_1(sc, R92C_APSD_CTRL) & ~R92C_APSD_CTRL_OFF); for (ntries = 0; ntries < 200; ntries++) { if (!(urtwn_read_1(sc, R92C_APSD_CTRL) & R92C_APSD_CTRL_OFF_STATUS)) break; urtwn_ms_delay(sc); } if (ntries == 200) { device_printf(sc->sc_dev, "timeout waiting for MAC initialization\n"); return (ETIMEDOUT); } /* Enable MAC DMA/WMAC/SCHEDULE/SEC blocks. */ reg = urtwn_read_2(sc, R92C_CR); reg |= R92C_CR_HCI_TXDMA_EN | R92C_CR_HCI_RXDMA_EN | R92C_CR_TXDMA_EN | R92C_CR_RXDMA_EN | R92C_CR_PROTOCOL_EN | R92C_CR_SCHEDULE_EN | R92C_CR_MACTXEN | R92C_CR_MACRXEN | R92C_CR_ENSEC; urtwn_write_2(sc, R92C_CR, reg); urtwn_write_1(sc, 0xfe10, 0x19); return (0); } static int urtwn_r88e_power_on(struct urtwn_softc *sc) { uint8_t val; uint32_t reg; int ntries; /* Wait for power ready bit. */ for (ntries = 0; ntries < 5000; ntries++) { val = urtwn_read_1(sc, 0x6) & 0x2; if (val == 0x2) break; urtwn_ms_delay(sc); } if (ntries == 5000) { device_printf(sc->sc_dev, "timeout waiting for chip power up\n"); return (ETIMEDOUT); } /* Reset BB. */ urtwn_write_1(sc, R92C_SYS_FUNC_EN, urtwn_read_1(sc, R92C_SYS_FUNC_EN) & ~(R92C_SYS_FUNC_EN_BBRSTB | R92C_SYS_FUNC_EN_BB_GLB_RST)); urtwn_write_1(sc, 0x26, urtwn_read_1(sc, 0x26) | 0x80); /* Disable HWPDN. */ urtwn_write_1(sc, 0x5, urtwn_read_1(sc, 0x5) & ~0x80); /* Disable WL suspend. */ urtwn_write_1(sc, 0x5, urtwn_read_1(sc, 0x5) & ~0x18); urtwn_write_1(sc, 0x5, urtwn_read_1(sc, 0x5) | 0x1); for (ntries = 0; ntries < 5000; ntries++) { if (!(urtwn_read_1(sc, 0x5) & 0x1)) break; urtwn_ms_delay(sc); } if (ntries == 5000) return (ETIMEDOUT); /* Enable LDO normal mode. */ urtwn_write_1(sc, 0x23, urtwn_read_1(sc, 0x23) & ~0x10); /* Enable MAC DMA/WMAC/SCHEDULE/SEC blocks. */ urtwn_write_2(sc, R92C_CR, 0); reg = urtwn_read_2(sc, R92C_CR); reg |= R92C_CR_HCI_TXDMA_EN | R92C_CR_HCI_RXDMA_EN | R92C_CR_TXDMA_EN | R92C_CR_RXDMA_EN | R92C_CR_PROTOCOL_EN | R92C_CR_SCHEDULE_EN | R92C_CR_ENSEC | R92C_CR_CALTMR_EN; urtwn_write_2(sc, R92C_CR, reg); return (0); } static int urtwn_llt_init(struct urtwn_softc *sc) { int i, error, page_count, pktbuf_count; page_count = (sc->chip & URTWN_CHIP_88E) ? R88E_TX_PAGE_COUNT : R92C_TX_PAGE_COUNT; pktbuf_count = (sc->chip & URTWN_CHIP_88E) ? R88E_TXPKTBUF_COUNT : R92C_TXPKTBUF_COUNT; /* Reserve pages [0; page_count]. */ for (i = 0; i < page_count; i++) { if ((error = urtwn_llt_write(sc, i, i + 1)) != 0) return (error); } /* NB: 0xff indicates end-of-list. */ if ((error = urtwn_llt_write(sc, i, 0xff)) != 0) return (error); /* * Use pages [page_count + 1; pktbuf_count - 1] * as ring buffer. */ for (++i; i < pktbuf_count - 1; i++) { if ((error = urtwn_llt_write(sc, i, i + 1)) != 0) return (error); } /* Make the last page point to the beginning of the ring buffer. */ error = urtwn_llt_write(sc, i, page_count + 1); return (error); } static void urtwn_fw_reset(struct urtwn_softc *sc) { uint16_t reg; int ntries; /* Tell 8051 to reset itself. */ urtwn_write_1(sc, R92C_HMETFR + 3, 0x20); /* Wait until 8051 resets by itself. */ for (ntries = 0; ntries < 100; ntries++) { reg = urtwn_read_2(sc, R92C_SYS_FUNC_EN); if (!(reg & R92C_SYS_FUNC_EN_CPUEN)) return; urtwn_ms_delay(sc); } /* Force 8051 reset. */ urtwn_write_2(sc, R92C_SYS_FUNC_EN, reg & ~R92C_SYS_FUNC_EN_CPUEN); } static void urtwn_r88e_fw_reset(struct urtwn_softc *sc) { uint16_t reg; reg = urtwn_read_2(sc, R92C_SYS_FUNC_EN); urtwn_write_2(sc, R92C_SYS_FUNC_EN, reg & ~R92C_SYS_FUNC_EN_CPUEN); urtwn_write_2(sc, R92C_SYS_FUNC_EN, reg | R92C_SYS_FUNC_EN_CPUEN); } static int urtwn_fw_loadpage(struct urtwn_softc *sc, int page, const uint8_t *buf, int len) { uint32_t reg; int off, mlen, error = 0; reg = urtwn_read_4(sc, R92C_MCUFWDL); reg = RW(reg, R92C_MCUFWDL_PAGE, page); urtwn_write_4(sc, R92C_MCUFWDL, reg); off = R92C_FW_START_ADDR; while (len > 0) { if (len > 196) mlen = 196; else if (len > 4) mlen = 4; else mlen = 1; /* XXX fix this deconst */ error = urtwn_write_region_1(sc, off, __DECONST(uint8_t *, buf), mlen); if (error != 0) break; off += mlen; buf += mlen; len -= mlen; } return (error); } static int urtwn_load_firmware(struct urtwn_softc *sc) { const struct firmware *fw; const struct r92c_fw_hdr *hdr; const char *imagename; const u_char *ptr; size_t len; uint32_t reg; int mlen, ntries, page, error; URTWN_UNLOCK(sc); /* Read firmware image from the filesystem. */ if (sc->chip & URTWN_CHIP_88E) imagename = "urtwn-rtl8188eufw"; else if ((sc->chip & (URTWN_CHIP_UMC_A_CUT | URTWN_CHIP_92C)) == URTWN_CHIP_UMC_A_CUT) imagename = "urtwn-rtl8192cfwU"; else imagename = "urtwn-rtl8192cfwT"; fw = firmware_get(imagename); URTWN_LOCK(sc); if (fw == NULL) { device_printf(sc->sc_dev, "failed loadfirmware of file %s\n", imagename); return (ENOENT); } len = fw->datasize; if (len < sizeof(*hdr)) { device_printf(sc->sc_dev, "firmware too short\n"); error = EINVAL; goto fail; } ptr = fw->data; hdr = (const struct r92c_fw_hdr *)ptr; /* Check if there is a valid FW header and skip it. */ if ((le16toh(hdr->signature) >> 4) == 0x88c || (le16toh(hdr->signature) >> 4) == 0x88e || (le16toh(hdr->signature) >> 4) == 0x92c) { DPRINTF("FW V%d.%d %02d-%02d %02d:%02d\n", le16toh(hdr->version), le16toh(hdr->subversion), hdr->month, hdr->date, hdr->hour, hdr->minute); ptr += sizeof(*hdr); len -= sizeof(*hdr); } if (urtwn_read_1(sc, R92C_MCUFWDL) & R92C_MCUFWDL_RAM_DL_SEL) { if (sc->chip & URTWN_CHIP_88E) urtwn_r88e_fw_reset(sc); else urtwn_fw_reset(sc); urtwn_write_1(sc, R92C_MCUFWDL, 0); } if (!(sc->chip & URTWN_CHIP_88E)) { urtwn_write_2(sc, R92C_SYS_FUNC_EN, urtwn_read_2(sc, R92C_SYS_FUNC_EN) | R92C_SYS_FUNC_EN_CPUEN); } urtwn_write_1(sc, R92C_MCUFWDL, urtwn_read_1(sc, R92C_MCUFWDL) | R92C_MCUFWDL_EN); urtwn_write_1(sc, R92C_MCUFWDL + 2, urtwn_read_1(sc, R92C_MCUFWDL + 2) & ~0x08); /* Reset the FWDL checksum. */ urtwn_write_1(sc, R92C_MCUFWDL, urtwn_read_1(sc, R92C_MCUFWDL) | R92C_MCUFWDL_CHKSUM_RPT); for (page = 0; len > 0; page++) { mlen = min(len, R92C_FW_PAGE_SIZE); error = urtwn_fw_loadpage(sc, page, ptr, mlen); if (error != 0) { device_printf(sc->sc_dev, "could not load firmware page\n"); goto fail; } ptr += mlen; len -= mlen; } urtwn_write_1(sc, R92C_MCUFWDL, urtwn_read_1(sc, R92C_MCUFWDL) & ~R92C_MCUFWDL_EN); urtwn_write_1(sc, R92C_MCUFWDL + 1, 0); /* Wait for checksum report. */ for (ntries = 0; ntries < 1000; ntries++) { if (urtwn_read_4(sc, R92C_MCUFWDL) & R92C_MCUFWDL_CHKSUM_RPT) break; urtwn_ms_delay(sc); } if (ntries == 1000) { device_printf(sc->sc_dev, "timeout waiting for checksum report\n"); error = ETIMEDOUT; goto fail; } reg = urtwn_read_4(sc, R92C_MCUFWDL); reg = (reg & ~R92C_MCUFWDL_WINTINI_RDY) | R92C_MCUFWDL_RDY; urtwn_write_4(sc, R92C_MCUFWDL, reg); if (sc->chip & URTWN_CHIP_88E) urtwn_r88e_fw_reset(sc); /* Wait for firmware readiness. */ for (ntries = 0; ntries < 1000; ntries++) { if (urtwn_read_4(sc, R92C_MCUFWDL) & R92C_MCUFWDL_WINTINI_RDY) break; urtwn_ms_delay(sc); } if (ntries == 1000) { device_printf(sc->sc_dev, "timeout waiting for firmware readiness\n"); error = ETIMEDOUT; goto fail; } fail: firmware_put(fw, FIRMWARE_UNLOAD); return (error); } static __inline int urtwn_dma_init(struct urtwn_softc *sc) { return sc->sc_dma_init(sc); } static int urtwn_r92c_dma_init(struct urtwn_softc *sc) { int hashq, hasnq, haslq, nqueues, nqpages, nrempages; uint32_t reg; int error; /* Initialize LLT table. */ error = urtwn_llt_init(sc); if (error != 0) return (error); /* Get Tx queues to USB endpoints mapping. */ hashq = hasnq = haslq = 0; reg = urtwn_read_2(sc, R92C_USB_EP + 1); DPRINTFN(2, "USB endpoints mapping 0x%x\n", reg); if (MS(reg, R92C_USB_EP_HQ) != 0) hashq = 1; if (MS(reg, R92C_USB_EP_NQ) != 0) hasnq = 1; if (MS(reg, R92C_USB_EP_LQ) != 0) haslq = 1; nqueues = hashq + hasnq + haslq; if (nqueues == 0) return (EIO); /* Get the number of pages for each queue. */ nqpages = (R92C_TX_PAGE_COUNT - R92C_PUBQ_NPAGES) / nqueues; /* The remaining pages are assigned to the high priority queue. */ nrempages = (R92C_TX_PAGE_COUNT - R92C_PUBQ_NPAGES) % nqueues; /* Set number of pages for normal priority queue. */ urtwn_write_1(sc, R92C_RQPN_NPQ, hasnq ? nqpages : 0); urtwn_write_4(sc, R92C_RQPN, /* Set number of pages for public queue. */ SM(R92C_RQPN_PUBQ, R92C_PUBQ_NPAGES) | /* Set number of pages for high priority queue. */ SM(R92C_RQPN_HPQ, hashq ? nqpages + nrempages : 0) | /* Set number of pages for low priority queue. */ SM(R92C_RQPN_LPQ, haslq ? nqpages : 0) | /* Load values. */ R92C_RQPN_LD); urtwn_write_1(sc, R92C_TXPKTBUF_BCNQ_BDNY, R92C_TX_PAGE_BOUNDARY); urtwn_write_1(sc, R92C_TXPKTBUF_MGQ_BDNY, R92C_TX_PAGE_BOUNDARY); urtwn_write_1(sc, R92C_TXPKTBUF_WMAC_LBK_BF_HD, R92C_TX_PAGE_BOUNDARY); urtwn_write_1(sc, R92C_TRXFF_BNDY, R92C_TX_PAGE_BOUNDARY); urtwn_write_1(sc, R92C_TDECTRL + 1, R92C_TX_PAGE_BOUNDARY); /* Set queue to USB pipe mapping. */ reg = urtwn_read_2(sc, R92C_TRXDMA_CTRL); reg &= ~R92C_TRXDMA_CTRL_QMAP_M; if (nqueues == 1) { if (hashq) reg |= R92C_TRXDMA_CTRL_QMAP_HQ; else if (hasnq) reg |= R92C_TRXDMA_CTRL_QMAP_NQ; else reg |= R92C_TRXDMA_CTRL_QMAP_LQ; } else if (nqueues == 2) { /* All 2-endpoints configs have a high priority queue. */ if (!hashq) return (EIO); if (hasnq) reg |= R92C_TRXDMA_CTRL_QMAP_HQ_NQ; else reg |= R92C_TRXDMA_CTRL_QMAP_HQ_LQ; } else reg |= R92C_TRXDMA_CTRL_QMAP_3EP; urtwn_write_2(sc, R92C_TRXDMA_CTRL, reg); /* Set Tx/Rx transfer page boundary. */ urtwn_write_2(sc, R92C_TRXFF_BNDY + 2, 0x27ff); /* Set Tx/Rx transfer page size. */ urtwn_write_1(sc, R92C_PBP, SM(R92C_PBP_PSRX, R92C_PBP_128) | SM(R92C_PBP_PSTX, R92C_PBP_128)); return (0); } static int urtwn_r88e_dma_init(struct urtwn_softc *sc) { struct usb_interface *iface; uint32_t reg; int nqueues; int error; /* Initialize LLT table. */ error = urtwn_llt_init(sc); if (error != 0) return (error); /* Get Tx queues to USB endpoints mapping. */ iface = usbd_get_iface(sc->sc_udev, 0); nqueues = iface->idesc->bNumEndpoints - 1; if (nqueues == 0) return (EIO); /* Set number of pages for normal priority queue. */ urtwn_write_2(sc, R92C_RQPN_NPQ, 0); urtwn_write_2(sc, R92C_RQPN_NPQ, 0x000d); urtwn_write_4(sc, R92C_RQPN, 0x808e000d); urtwn_write_1(sc, R92C_TXPKTBUF_BCNQ_BDNY, R88E_TX_PAGE_BOUNDARY); urtwn_write_1(sc, R92C_TXPKTBUF_MGQ_BDNY, R88E_TX_PAGE_BOUNDARY); urtwn_write_1(sc, R92C_TXPKTBUF_WMAC_LBK_BF_HD, R88E_TX_PAGE_BOUNDARY); urtwn_write_1(sc, R92C_TRXFF_BNDY, R88E_TX_PAGE_BOUNDARY); urtwn_write_1(sc, R92C_TDECTRL + 1, R88E_TX_PAGE_BOUNDARY); /* Set queue to USB pipe mapping. */ reg = urtwn_read_2(sc, R92C_TRXDMA_CTRL); reg &= ~R92C_TRXDMA_CTRL_QMAP_M; if (nqueues == 1) reg |= R92C_TRXDMA_CTRL_QMAP_LQ; else if (nqueues == 2) reg |= R92C_TRXDMA_CTRL_QMAP_HQ_NQ; else reg |= R92C_TRXDMA_CTRL_QMAP_3EP; urtwn_write_2(sc, R92C_TRXDMA_CTRL, reg); /* Set Tx/Rx transfer page boundary. */ urtwn_write_2(sc, R92C_TRXFF_BNDY + 2, 0x23ff); /* Set Tx/Rx transfer page size. */ urtwn_write_1(sc, R92C_PBP, SM(R92C_PBP_PSRX, R92C_PBP_128) | SM(R92C_PBP_PSTX, R92C_PBP_128)); return (0); } static void urtwn_mac_init(struct urtwn_softc *sc) { int i; /* Write MAC initialization values. */ if (sc->chip & URTWN_CHIP_88E) { for (i = 0; i < nitems(rtl8188eu_mac); i++) { urtwn_write_1(sc, rtl8188eu_mac[i].reg, rtl8188eu_mac[i].val); } urtwn_write_1(sc, R92C_MAX_AGGR_NUM, 0x07); } else { for (i = 0; i < nitems(rtl8192cu_mac); i++) urtwn_write_1(sc, rtl8192cu_mac[i].reg, rtl8192cu_mac[i].val); } } static void urtwn_bb_init(struct urtwn_softc *sc) { const struct urtwn_bb_prog *prog; uint32_t reg; uint8_t crystalcap; int i; /* Enable BB and RF. */ urtwn_write_2(sc, R92C_SYS_FUNC_EN, urtwn_read_2(sc, R92C_SYS_FUNC_EN) | R92C_SYS_FUNC_EN_BBRSTB | R92C_SYS_FUNC_EN_BB_GLB_RST | R92C_SYS_FUNC_EN_DIO_RF); if (!(sc->chip & URTWN_CHIP_88E)) urtwn_write_2(sc, R92C_AFE_PLL_CTRL, 0xdb83); urtwn_write_1(sc, R92C_RF_CTRL, R92C_RF_CTRL_EN | R92C_RF_CTRL_RSTB | R92C_RF_CTRL_SDMRSTB); urtwn_write_1(sc, R92C_SYS_FUNC_EN, R92C_SYS_FUNC_EN_USBA | R92C_SYS_FUNC_EN_USBD | R92C_SYS_FUNC_EN_BB_GLB_RST | R92C_SYS_FUNC_EN_BBRSTB); if (!(sc->chip & URTWN_CHIP_88E)) { urtwn_write_1(sc, R92C_LDOHCI12_CTRL, 0x0f); urtwn_write_1(sc, 0x15, 0xe9); urtwn_write_1(sc, R92C_AFE_XTAL_CTRL + 1, 0x80); } /* Select BB programming based on board type. */ if (sc->chip & URTWN_CHIP_88E) prog = &rtl8188eu_bb_prog; else if (!(sc->chip & URTWN_CHIP_92C)) { if (sc->board_type == R92C_BOARD_TYPE_MINICARD) prog = &rtl8188ce_bb_prog; else if (sc->board_type == R92C_BOARD_TYPE_HIGHPA) prog = &rtl8188ru_bb_prog; else prog = &rtl8188cu_bb_prog; } else { if (sc->board_type == R92C_BOARD_TYPE_MINICARD) prog = &rtl8192ce_bb_prog; else prog = &rtl8192cu_bb_prog; } /* Write BB initialization values. */ for (i = 0; i < prog->count; i++) { urtwn_bb_write(sc, prog->regs[i], prog->vals[i]); urtwn_ms_delay(sc); } if (sc->chip & URTWN_CHIP_92C_1T2R) { /* 8192C 1T only configuration. */ reg = urtwn_bb_read(sc, R92C_FPGA0_TXINFO); reg = (reg & ~0x00000003) | 0x2; urtwn_bb_write(sc, R92C_FPGA0_TXINFO, reg); reg = urtwn_bb_read(sc, R92C_FPGA1_TXINFO); reg = (reg & ~0x00300033) | 0x00200022; urtwn_bb_write(sc, R92C_FPGA1_TXINFO, reg); reg = urtwn_bb_read(sc, R92C_CCK0_AFESETTING); reg = (reg & ~0xff000000) | 0x45 << 24; urtwn_bb_write(sc, R92C_CCK0_AFESETTING, reg); reg = urtwn_bb_read(sc, R92C_OFDM0_TRXPATHENA); reg = (reg & ~0x000000ff) | 0x23; urtwn_bb_write(sc, R92C_OFDM0_TRXPATHENA, reg); reg = urtwn_bb_read(sc, R92C_OFDM0_AGCPARAM1); reg = (reg & ~0x00000030) | 1 << 4; urtwn_bb_write(sc, R92C_OFDM0_AGCPARAM1, reg); reg = urtwn_bb_read(sc, 0xe74); reg = (reg & ~0x0c000000) | 2 << 26; urtwn_bb_write(sc, 0xe74, reg); reg = urtwn_bb_read(sc, 0xe78); reg = (reg & ~0x0c000000) | 2 << 26; urtwn_bb_write(sc, 0xe78, reg); reg = urtwn_bb_read(sc, 0xe7c); reg = (reg & ~0x0c000000) | 2 << 26; urtwn_bb_write(sc, 0xe7c, reg); reg = urtwn_bb_read(sc, 0xe80); reg = (reg & ~0x0c000000) | 2 << 26; urtwn_bb_write(sc, 0xe80, reg); reg = urtwn_bb_read(sc, 0xe88); reg = (reg & ~0x0c000000) | 2 << 26; urtwn_bb_write(sc, 0xe88, reg); } /* Write AGC values. */ for (i = 0; i < prog->agccount; i++) { urtwn_bb_write(sc, R92C_OFDM0_AGCRSSITABLE, prog->agcvals[i]); urtwn_ms_delay(sc); } if (sc->chip & URTWN_CHIP_88E) { urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), 0x69553422); urtwn_ms_delay(sc); urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), 0x69553420); urtwn_ms_delay(sc); crystalcap = sc->r88e_rom[0xb9]; if (crystalcap == 0xff) crystalcap = 0x20; crystalcap &= 0x3f; reg = urtwn_bb_read(sc, R92C_AFE_XTAL_CTRL); urtwn_bb_write(sc, R92C_AFE_XTAL_CTRL, RW(reg, R92C_AFE_XTAL_CTRL_ADDR, crystalcap | crystalcap << 6)); } else { if (urtwn_bb_read(sc, R92C_HSSI_PARAM2(0)) & R92C_HSSI_PARAM2_CCK_HIPWR) sc->sc_flags |= URTWN_FLAG_CCK_HIPWR; } } void urtwn_rf_init(struct urtwn_softc *sc) { const struct urtwn_rf_prog *prog; uint32_t reg, type; int i, j, idx, off; /* Select RF programming based on board type. */ if (sc->chip & URTWN_CHIP_88E) prog = rtl8188eu_rf_prog; else if (!(sc->chip & URTWN_CHIP_92C)) { if (sc->board_type == R92C_BOARD_TYPE_MINICARD) prog = rtl8188ce_rf_prog; else if (sc->board_type == R92C_BOARD_TYPE_HIGHPA) prog = rtl8188ru_rf_prog; else prog = rtl8188cu_rf_prog; } else prog = rtl8192ce_rf_prog; for (i = 0; i < sc->nrxchains; i++) { /* Save RF_ENV control type. */ idx = i / 2; off = (i % 2) * 16; reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACESW(idx)); type = (reg >> off) & 0x10; /* Set RF_ENV enable. */ reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACEOE(i)); reg |= 0x100000; urtwn_bb_write(sc, R92C_FPGA0_RFIFACEOE(i), reg); urtwn_ms_delay(sc); /* Set RF_ENV output high. */ reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACEOE(i)); reg |= 0x10; urtwn_bb_write(sc, R92C_FPGA0_RFIFACEOE(i), reg); urtwn_ms_delay(sc); /* Set address and data lengths of RF registers. */ reg = urtwn_bb_read(sc, R92C_HSSI_PARAM2(i)); reg &= ~R92C_HSSI_PARAM2_ADDR_LENGTH; urtwn_bb_write(sc, R92C_HSSI_PARAM2(i), reg); urtwn_ms_delay(sc); reg = urtwn_bb_read(sc, R92C_HSSI_PARAM2(i)); reg &= ~R92C_HSSI_PARAM2_DATA_LENGTH; urtwn_bb_write(sc, R92C_HSSI_PARAM2(i), reg); urtwn_ms_delay(sc); /* Write RF initialization values for this chain. */ for (j = 0; j < prog[i].count; j++) { if (prog[i].regs[j] >= 0xf9 && prog[i].regs[j] <= 0xfe) { /* * These are fake RF registers offsets that * indicate a delay is required. */ usb_pause_mtx(&sc->sc_mtx, hz / 20); /* 50ms */ continue; } urtwn_rf_write(sc, i, prog[i].regs[j], prog[i].vals[j]); urtwn_ms_delay(sc); } /* Restore RF_ENV control type. */ reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACESW(idx)); reg &= ~(0x10 << off) | (type << off); urtwn_bb_write(sc, R92C_FPGA0_RFIFACESW(idx), reg); /* Cache RF register CHNLBW. */ sc->rf_chnlbw[i] = urtwn_rf_read(sc, i, R92C_RF_CHNLBW); } if ((sc->chip & (URTWN_CHIP_UMC_A_CUT | URTWN_CHIP_92C)) == URTWN_CHIP_UMC_A_CUT) { urtwn_rf_write(sc, 0, R92C_RF_RX_G1, 0x30255); urtwn_rf_write(sc, 0, R92C_RF_RX_G2, 0x50a00); } } static void urtwn_cam_init(struct urtwn_softc *sc) { /* Invalidate all CAM entries. */ urtwn_write_4(sc, R92C_CAMCMD, R92C_CAMCMD_POLLING | R92C_CAMCMD_CLR); } static void urtwn_pa_bias_init(struct urtwn_softc *sc) { uint8_t reg; int i; for (i = 0; i < sc->nrxchains; i++) { if (sc->pa_setting & (1 << i)) continue; urtwn_rf_write(sc, i, R92C_RF_IPA, 0x0f406); urtwn_rf_write(sc, i, R92C_RF_IPA, 0x4f406); urtwn_rf_write(sc, i, R92C_RF_IPA, 0x8f406); urtwn_rf_write(sc, i, R92C_RF_IPA, 0xcf406); } if (!(sc->pa_setting & 0x10)) { reg = urtwn_read_1(sc, 0x16); reg = (reg & ~0xf0) | 0x90; urtwn_write_1(sc, 0x16, reg); } } static void urtwn_rxfilter_init(struct urtwn_softc *sc) { /* Initialize Rx filter. */ /* TODO: use better filter for monitor mode. */ urtwn_write_4(sc, R92C_RCR, R92C_RCR_AAP | R92C_RCR_APM | R92C_RCR_AM | R92C_RCR_AB | R92C_RCR_APP_ICV | R92C_RCR_AMF | R92C_RCR_HTC_LOC_CTRL | R92C_RCR_APP_MIC | R92C_RCR_APP_PHYSTS); /* Accept all multicast frames. */ urtwn_write_4(sc, R92C_MAR + 0, 0xffffffff); urtwn_write_4(sc, R92C_MAR + 4, 0xffffffff); /* Accept all management frames. */ urtwn_write_2(sc, R92C_RXFLTMAP0, 0xffff); /* Reject all control frames. */ urtwn_write_2(sc, R92C_RXFLTMAP1, 0x0000); /* Accept all data frames. */ urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff); } static void urtwn_edca_init(struct urtwn_softc *sc) { urtwn_write_2(sc, R92C_SPEC_SIFS, 0x100a); urtwn_write_2(sc, R92C_MAC_SPEC_SIFS, 0x100a); urtwn_write_2(sc, R92C_SIFS_CCK, 0x100a); urtwn_write_2(sc, R92C_SIFS_OFDM, 0x100a); urtwn_write_4(sc, R92C_EDCA_BE_PARAM, 0x005ea42b); urtwn_write_4(sc, R92C_EDCA_BK_PARAM, 0x0000a44f); urtwn_write_4(sc, R92C_EDCA_VI_PARAM, 0x005ea324); urtwn_write_4(sc, R92C_EDCA_VO_PARAM, 0x002fa226); } void urtwn_write_txpower(struct urtwn_softc *sc, int chain, uint16_t power[URTWN_RIDX_COUNT]) { uint32_t reg; /* Write per-CCK rate Tx power. */ if (chain == 0) { reg = urtwn_bb_read(sc, R92C_TXAGC_A_CCK1_MCS32); reg = RW(reg, R92C_TXAGC_A_CCK1, power[0]); urtwn_bb_write(sc, R92C_TXAGC_A_CCK1_MCS32, reg); reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK11_A_CCK2_11); reg = RW(reg, R92C_TXAGC_A_CCK2, power[1]); reg = RW(reg, R92C_TXAGC_A_CCK55, power[2]); reg = RW(reg, R92C_TXAGC_A_CCK11, power[3]); urtwn_bb_write(sc, R92C_TXAGC_B_CCK11_A_CCK2_11, reg); } else { reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK1_55_MCS32); reg = RW(reg, R92C_TXAGC_B_CCK1, power[0]); reg = RW(reg, R92C_TXAGC_B_CCK2, power[1]); reg = RW(reg, R92C_TXAGC_B_CCK55, power[2]); urtwn_bb_write(sc, R92C_TXAGC_B_CCK1_55_MCS32, reg); reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK11_A_CCK2_11); reg = RW(reg, R92C_TXAGC_B_CCK11, power[3]); urtwn_bb_write(sc, R92C_TXAGC_B_CCK11_A_CCK2_11, reg); } /* Write per-OFDM rate Tx power. */ urtwn_bb_write(sc, R92C_TXAGC_RATE18_06(chain), SM(R92C_TXAGC_RATE06, power[ 4]) | SM(R92C_TXAGC_RATE09, power[ 5]) | SM(R92C_TXAGC_RATE12, power[ 6]) | SM(R92C_TXAGC_RATE18, power[ 7])); urtwn_bb_write(sc, R92C_TXAGC_RATE54_24(chain), SM(R92C_TXAGC_RATE24, power[ 8]) | SM(R92C_TXAGC_RATE36, power[ 9]) | SM(R92C_TXAGC_RATE48, power[10]) | SM(R92C_TXAGC_RATE54, power[11])); /* Write per-MCS Tx power. */ urtwn_bb_write(sc, R92C_TXAGC_MCS03_MCS00(chain), SM(R92C_TXAGC_MCS00, power[12]) | SM(R92C_TXAGC_MCS01, power[13]) | SM(R92C_TXAGC_MCS02, power[14]) | SM(R92C_TXAGC_MCS03, power[15])); urtwn_bb_write(sc, R92C_TXAGC_MCS07_MCS04(chain), SM(R92C_TXAGC_MCS04, power[16]) | SM(R92C_TXAGC_MCS05, power[17]) | SM(R92C_TXAGC_MCS06, power[18]) | SM(R92C_TXAGC_MCS07, power[19])); urtwn_bb_write(sc, R92C_TXAGC_MCS11_MCS08(chain), SM(R92C_TXAGC_MCS08, power[20]) | SM(R92C_TXAGC_MCS09, power[21]) | SM(R92C_TXAGC_MCS10, power[22]) | SM(R92C_TXAGC_MCS11, power[23])); urtwn_bb_write(sc, R92C_TXAGC_MCS15_MCS12(chain), SM(R92C_TXAGC_MCS12, power[24]) | SM(R92C_TXAGC_MCS13, power[25]) | SM(R92C_TXAGC_MCS14, power[26]) | SM(R92C_TXAGC_MCS15, power[27])); } void urtwn_get_txpower(struct urtwn_softc *sc, int chain, struct ieee80211_channel *c, struct ieee80211_channel *extc, uint16_t power[URTWN_RIDX_COUNT]) { struct ieee80211com *ic = sc->sc_ifp->if_l2com; struct r92c_rom *rom = &sc->rom; uint16_t cckpow, ofdmpow, htpow, diff, max; const struct urtwn_txpwr *base; int ridx, chan, group; /* Determine channel group. */ chan = ieee80211_chan2ieee(ic, c); /* XXX center freq! */ if (chan <= 3) group = 0; else if (chan <= 9) group = 1; else group = 2; /* Get original Tx power based on board type and RF chain. */ if (!(sc->chip & URTWN_CHIP_92C)) { if (sc->board_type == R92C_BOARD_TYPE_HIGHPA) base = &rtl8188ru_txagc[chain]; else base = &rtl8192cu_txagc[chain]; } else base = &rtl8192cu_txagc[chain]; memset(power, 0, URTWN_RIDX_COUNT * sizeof(power[0])); if (sc->regulatory == 0) { for (ridx = 0; ridx <= 3; ridx++) power[ridx] = base->pwr[0][ridx]; } for (ridx = 4; ridx < URTWN_RIDX_COUNT; ridx++) { if (sc->regulatory == 3) { power[ridx] = base->pwr[0][ridx]; /* Apply vendor limits. */ if (extc != NULL) max = rom->ht40_max_pwr[group]; else max = rom->ht20_max_pwr[group]; max = (max >> (chain * 4)) & 0xf; if (power[ridx] > max) power[ridx] = max; } else if (sc->regulatory == 1) { if (extc == NULL) power[ridx] = base->pwr[group][ridx]; } else if (sc->regulatory != 2) power[ridx] = base->pwr[0][ridx]; } /* Compute per-CCK rate Tx power. */ cckpow = rom->cck_tx_pwr[chain][group]; for (ridx = 0; ridx <= 3; ridx++) { power[ridx] += cckpow; if (power[ridx] > R92C_MAX_TX_PWR) power[ridx] = R92C_MAX_TX_PWR; } htpow = rom->ht40_1s_tx_pwr[chain][group]; if (sc->ntxchains > 1) { /* Apply reduction for 2 spatial streams. */ diff = rom->ht40_2s_tx_pwr_diff[group]; diff = (diff >> (chain * 4)) & 0xf; htpow = (htpow > diff) ? htpow - diff : 0; } /* Compute per-OFDM rate Tx power. */ diff = rom->ofdm_tx_pwr_diff[group]; diff = (diff >> (chain * 4)) & 0xf; ofdmpow = htpow + diff; /* HT->OFDM correction. */ for (ridx = 4; ridx <= 11; ridx++) { power[ridx] += ofdmpow; if (power[ridx] > R92C_MAX_TX_PWR) power[ridx] = R92C_MAX_TX_PWR; } /* Compute per-MCS Tx power. */ if (extc == NULL) { diff = rom->ht20_tx_pwr_diff[group]; diff = (diff >> (chain * 4)) & 0xf; htpow += diff; /* HT40->HT20 correction. */ } for (ridx = 12; ridx <= 27; ridx++) { power[ridx] += htpow; if (power[ridx] > R92C_MAX_TX_PWR) power[ridx] = R92C_MAX_TX_PWR; } #ifdef URTWN_DEBUG if (urtwn_debug >= 4) { /* Dump per-rate Tx power values. */ printf("Tx power for chain %d:\n", chain); for (ridx = 0; ridx < URTWN_RIDX_COUNT; ridx++) printf("Rate %d = %u\n", ridx, power[ridx]); } #endif } void urtwn_r88e_get_txpower(struct urtwn_softc *sc, int chain, struct ieee80211_channel *c, struct ieee80211_channel *extc, uint16_t power[URTWN_RIDX_COUNT]) { struct ieee80211com *ic = sc->sc_ifp->if_l2com; uint16_t cckpow, ofdmpow, bw20pow, htpow; const struct urtwn_r88e_txpwr *base; int ridx, chan, group; /* Determine channel group. */ chan = ieee80211_chan2ieee(ic, c); /* XXX center freq! */ if (chan <= 2) group = 0; else if (chan <= 5) group = 1; else if (chan <= 8) group = 2; else if (chan <= 11) group = 3; else if (chan <= 13) group = 4; else group = 5; /* Get original Tx power based on board type and RF chain. */ base = &rtl8188eu_txagc[chain]; memset(power, 0, URTWN_RIDX_COUNT * sizeof(power[0])); if (sc->regulatory == 0) { for (ridx = 0; ridx <= 3; ridx++) power[ridx] = base->pwr[0][ridx]; } for (ridx = 4; ridx < URTWN_RIDX_COUNT; ridx++) { if (sc->regulatory == 3) power[ridx] = base->pwr[0][ridx]; else if (sc->regulatory == 1) { if (extc == NULL) power[ridx] = base->pwr[group][ridx]; } else if (sc->regulatory != 2) power[ridx] = base->pwr[0][ridx]; } /* Compute per-CCK rate Tx power. */ cckpow = sc->cck_tx_pwr[group]; for (ridx = 0; ridx <= 3; ridx++) { power[ridx] += cckpow; if (power[ridx] > R92C_MAX_TX_PWR) power[ridx] = R92C_MAX_TX_PWR; } htpow = sc->ht40_tx_pwr[group]; /* Compute per-OFDM rate Tx power. */ ofdmpow = htpow + sc->ofdm_tx_pwr_diff; for (ridx = 4; ridx <= 11; ridx++) { power[ridx] += ofdmpow; if (power[ridx] > R92C_MAX_TX_PWR) power[ridx] = R92C_MAX_TX_PWR; } bw20pow = htpow + sc->bw20_tx_pwr_diff; for (ridx = 12; ridx <= 27; ridx++) { power[ridx] += bw20pow; if (power[ridx] > R92C_MAX_TX_PWR) power[ridx] = R92C_MAX_TX_PWR; } } void urtwn_set_txpower(struct urtwn_softc *sc, struct ieee80211_channel *c, struct ieee80211_channel *extc) { uint16_t power[URTWN_RIDX_COUNT]; int i; for (i = 0; i < sc->ntxchains; i++) { /* Compute per-rate Tx power values. */ if (sc->chip & URTWN_CHIP_88E) urtwn_r88e_get_txpower(sc, i, c, extc, power); else urtwn_get_txpower(sc, i, c, extc, power); /* Write per-rate Tx power values to hardware. */ urtwn_write_txpower(sc, i, power); } } static void urtwn_scan_start(struct ieee80211com *ic) { /* XXX do nothing? */ } static void urtwn_scan_end(struct ieee80211com *ic) { /* XXX do nothing? */ } static void urtwn_set_channel(struct ieee80211com *ic) { struct urtwn_softc *sc = ic->ic_ifp->if_softc; URTWN_LOCK(sc); urtwn_set_chan(sc, ic->ic_curchan, NULL); URTWN_UNLOCK(sc); } static void urtwn_update_mcast(struct ifnet *ifp) { /* XXX do nothing? */ } static void urtwn_set_chan(struct urtwn_softc *sc, struct ieee80211_channel *c, struct ieee80211_channel *extc) { struct ieee80211com *ic = sc->sc_ifp->if_l2com; uint32_t reg; u_int chan; int i; chan = ieee80211_chan2ieee(ic, c); /* XXX center freq! */ if (chan == 0 || chan == IEEE80211_CHAN_ANY) { device_printf(sc->sc_dev, "%s: invalid channel %x\n", __func__, chan); return; } /* Set Tx power for this new channel. */ urtwn_set_txpower(sc, c, extc); for (i = 0; i < sc->nrxchains; i++) { urtwn_rf_write(sc, i, R92C_RF_CHNLBW, RW(sc->rf_chnlbw[i], R92C_RF_CHNLBW_CHNL, chan)); } #ifndef IEEE80211_NO_HT if (extc != NULL) { /* Is secondary channel below or above primary? */ int prichlo = c->ic_freq < extc->ic_freq; urtwn_write_1(sc, R92C_BWOPMODE, urtwn_read_1(sc, R92C_BWOPMODE) & ~R92C_BWOPMODE_20MHZ); reg = urtwn_read_1(sc, R92C_RRSR + 2); reg = (reg & ~0x6f) | (prichlo ? 1 : 2) << 5; urtwn_write_1(sc, R92C_RRSR + 2, reg); urtwn_bb_write(sc, R92C_FPGA0_RFMOD, urtwn_bb_read(sc, R92C_FPGA0_RFMOD) | R92C_RFMOD_40MHZ); urtwn_bb_write(sc, R92C_FPGA1_RFMOD, urtwn_bb_read(sc, R92C_FPGA1_RFMOD) | R92C_RFMOD_40MHZ); /* Set CCK side band. */ reg = urtwn_bb_read(sc, R92C_CCK0_SYSTEM); reg = (reg & ~0x00000010) | (prichlo ? 0 : 1) << 4; urtwn_bb_write(sc, R92C_CCK0_SYSTEM, reg); reg = urtwn_bb_read(sc, R92C_OFDM1_LSTF); reg = (reg & ~0x00000c00) | (prichlo ? 1 : 2) << 10; urtwn_bb_write(sc, R92C_OFDM1_LSTF, reg); urtwn_bb_write(sc, R92C_FPGA0_ANAPARAM2, urtwn_bb_read(sc, R92C_FPGA0_ANAPARAM2) & ~R92C_FPGA0_ANAPARAM2_CBW20); reg = urtwn_bb_read(sc, 0x818); reg = (reg & ~0x0c000000) | (prichlo ? 2 : 1) << 26; urtwn_bb_write(sc, 0x818, reg); /* Select 40MHz bandwidth. */ urtwn_rf_write(sc, 0, R92C_RF_CHNLBW, (sc->rf_chnlbw[0] & ~0xfff) | chan); } else #endif { urtwn_write_1(sc, R92C_BWOPMODE, urtwn_read_1(sc, R92C_BWOPMODE) | R92C_BWOPMODE_20MHZ); urtwn_bb_write(sc, R92C_FPGA0_RFMOD, urtwn_bb_read(sc, R92C_FPGA0_RFMOD) & ~R92C_RFMOD_40MHZ); urtwn_bb_write(sc, R92C_FPGA1_RFMOD, urtwn_bb_read(sc, R92C_FPGA1_RFMOD) & ~R92C_RFMOD_40MHZ); if (!(sc->chip & URTWN_CHIP_88E)) { urtwn_bb_write(sc, R92C_FPGA0_ANAPARAM2, urtwn_bb_read(sc, R92C_FPGA0_ANAPARAM2) | R92C_FPGA0_ANAPARAM2_CBW20); } /* Select 20MHz bandwidth. */ urtwn_rf_write(sc, 0, R92C_RF_CHNLBW, (sc->rf_chnlbw[0] & ~0xfff) | chan | ((sc->chip & URTWN_CHIP_88E) ? R88E_RF_CHNLBW_BW20 : R92C_RF_CHNLBW_BW20)); } } static void urtwn_iq_calib(struct urtwn_softc *sc) { /* TODO */ } static void urtwn_lc_calib(struct urtwn_softc *sc) { uint32_t rf_ac[2]; uint8_t txmode; int i; txmode = urtwn_read_1(sc, R92C_OFDM1_LSTF + 3); if ((txmode & 0x70) != 0) { /* Disable all continuous Tx. */ urtwn_write_1(sc, R92C_OFDM1_LSTF + 3, txmode & ~0x70); /* Set RF mode to standby mode. */ for (i = 0; i < sc->nrxchains; i++) { rf_ac[i] = urtwn_rf_read(sc, i, R92C_RF_AC); urtwn_rf_write(sc, i, R92C_RF_AC, RW(rf_ac[i], R92C_RF_AC_MODE, R92C_RF_AC_MODE_STANDBY)); } } else { /* Block all Tx queues. */ urtwn_write_1(sc, R92C_TXPAUSE, 0xff); } /* Start calibration. */ urtwn_rf_write(sc, 0, R92C_RF_CHNLBW, urtwn_rf_read(sc, 0, R92C_RF_CHNLBW) | R92C_RF_CHNLBW_LCSTART); /* Give calibration the time to complete. */ usb_pause_mtx(&sc->sc_mtx, hz / 10); /* 100ms */ /* Restore configuration. */ if ((txmode & 0x70) != 0) { /* Restore Tx mode. */ urtwn_write_1(sc, R92C_OFDM1_LSTF + 3, txmode); /* Restore RF mode. */ for (i = 0; i < sc->nrxchains; i++) urtwn_rf_write(sc, i, R92C_RF_AC, rf_ac[i]); } else { /* Unblock all Tx queues. */ urtwn_write_1(sc, R92C_TXPAUSE, 0x00); } } static void urtwn_init_locked(void *arg) { struct urtwn_softc *sc = arg; struct ifnet *ifp = sc->sc_ifp; uint32_t reg; int error; URTWN_ASSERT_LOCKED(sc); if (ifp->if_drv_flags & IFF_DRV_RUNNING) urtwn_stop_locked(ifp); /* Init firmware commands ring. */ sc->fwcur = 0; /* Allocate Tx/Rx buffers. */ error = urtwn_alloc_rx_list(sc); if (error != 0) goto fail; error = urtwn_alloc_tx_list(sc); if (error != 0) goto fail; /* Power on adapter. */ error = urtwn_power_on(sc); if (error != 0) goto fail; /* Initialize DMA. */ error = urtwn_dma_init(sc); if (error != 0) goto fail; /* Set info size in Rx descriptors (in 64-bit words). */ urtwn_write_1(sc, R92C_RX_DRVINFO_SZ, 4); /* Init interrupts. */ if (sc->chip & URTWN_CHIP_88E) { urtwn_write_4(sc, R88E_HISR, 0xffffffff); urtwn_write_4(sc, R88E_HIMR, R88E_HIMR_CPWM | R88E_HIMR_CPWM2 | R88E_HIMR_TBDER | R88E_HIMR_PSTIMEOUT); urtwn_write_4(sc, R88E_HIMRE, R88E_HIMRE_RXFOVW | R88E_HIMRE_TXFOVW | R88E_HIMRE_RXERR | R88E_HIMRE_TXERR); urtwn_write_1(sc, R92C_USB_SPECIAL_OPTION, urtwn_read_1(sc, R92C_USB_SPECIAL_OPTION) | R92C_USB_SPECIAL_OPTION_INT_BULK_SEL); } else { urtwn_write_4(sc, R92C_HISR, 0xffffffff); urtwn_write_4(sc, R92C_HIMR, 0xffffffff); } /* Set MAC address. */ urtwn_write_region_1(sc, R92C_MACID, IF_LLADDR(ifp), IEEE80211_ADDR_LEN); /* Set initial network type. */ reg = urtwn_read_4(sc, R92C_CR); reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_INFRA); urtwn_write_4(sc, R92C_CR, reg); urtwn_rxfilter_init(sc); reg = urtwn_read_4(sc, R92C_RRSR); reg = RW(reg, R92C_RRSR_RATE_BITMAP, R92C_RRSR_RATE_CCK_ONLY_1M); urtwn_write_4(sc, R92C_RRSR, reg); /* Set short/long retry limits. */ urtwn_write_2(sc, R92C_RL, SM(R92C_RL_SRL, 0x30) | SM(R92C_RL_LRL, 0x30)); /* Initialize EDCA parameters. */ urtwn_edca_init(sc); /* Setup rate fallback. */ if (!(sc->chip & URTWN_CHIP_88E)) { urtwn_write_4(sc, R92C_DARFRC + 0, 0x00000000); urtwn_write_4(sc, R92C_DARFRC + 4, 0x10080404); urtwn_write_4(sc, R92C_RARFRC + 0, 0x04030201); urtwn_write_4(sc, R92C_RARFRC + 4, 0x08070605); } urtwn_write_1(sc, R92C_FWHW_TXQ_CTRL, urtwn_read_1(sc, R92C_FWHW_TXQ_CTRL) | R92C_FWHW_TXQ_CTRL_AMPDU_RTY_NEW); /* Set ACK timeout. */ urtwn_write_1(sc, R92C_ACKTO, 0x40); /* Setup USB aggregation. */ reg = urtwn_read_4(sc, R92C_TDECTRL); reg = RW(reg, R92C_TDECTRL_BLK_DESC_NUM, 6); urtwn_write_4(sc, R92C_TDECTRL, reg); urtwn_write_1(sc, R92C_TRXDMA_CTRL, urtwn_read_1(sc, R92C_TRXDMA_CTRL) | R92C_TRXDMA_CTRL_RXDMA_AGG_EN); urtwn_write_1(sc, R92C_USB_SPECIAL_OPTION, urtwn_read_1(sc, R92C_USB_SPECIAL_OPTION) | R92C_USB_SPECIAL_OPTION_AGG_EN); urtwn_write_1(sc, R92C_RXDMA_AGG_PG_TH, 48); if (sc->chip & URTWN_CHIP_88E) urtwn_write_1(sc, R92C_RXDMA_AGG_PG_TH + 1, 4); else urtwn_write_1(sc, R92C_USB_DMA_AGG_TO, 4); urtwn_write_1(sc, R92C_USB_AGG_TH, 8); urtwn_write_1(sc, R92C_USB_AGG_TO, 6); /* Initialize beacon parameters. */ urtwn_write_2(sc, R92C_BCN_CTRL, 0x1010); urtwn_write_2(sc, R92C_TBTT_PROHIBIT, 0x6404); urtwn_write_1(sc, R92C_DRVERLYINT, 0x05); urtwn_write_1(sc, R92C_BCNDMATIM, 0x02); urtwn_write_2(sc, R92C_BCNTCFG, 0x660f); if (!(sc->chip & URTWN_CHIP_88E)) { /* Setup AMPDU aggregation. */ urtwn_write_4(sc, R92C_AGGLEN_LMT, 0x99997631); /* MCS7~0 */ urtwn_write_1(sc, R92C_AGGR_BREAK_TIME, 0x16); urtwn_write_2(sc, R92C_MAX_AGGR_NUM, 0x0708); urtwn_write_1(sc, R92C_BCN_MAX_ERR, 0xff); } /* Load 8051 microcode. */ error = urtwn_load_firmware(sc); if (error != 0) goto fail; /* Initialize MAC/BB/RF blocks. */ urtwn_mac_init(sc); urtwn_bb_init(sc); urtwn_rf_init(sc); if (sc->chip & URTWN_CHIP_88E) { urtwn_write_2(sc, R92C_CR, urtwn_read_2(sc, R92C_CR) | R92C_CR_MACTXEN | R92C_CR_MACRXEN); } /* Turn CCK and OFDM blocks on. */ reg = urtwn_bb_read(sc, R92C_FPGA0_RFMOD); reg |= R92C_RFMOD_CCK_EN; urtwn_bb_write(sc, R92C_FPGA0_RFMOD, reg); reg = urtwn_bb_read(sc, R92C_FPGA0_RFMOD); reg |= R92C_RFMOD_OFDM_EN; urtwn_bb_write(sc, R92C_FPGA0_RFMOD, reg); /* Clear per-station keys table. */ urtwn_cam_init(sc); /* Enable hardware sequence numbering. */ urtwn_write_1(sc, R92C_HWSEQ_CTRL, 0xff); /* Perform LO and IQ calibrations. */ urtwn_iq_calib(sc); /* Perform LC calibration. */ urtwn_lc_calib(sc); /* Fix USB interference issue. */ if (!(sc->chip & URTWN_CHIP_88E)) { urtwn_write_1(sc, 0xfe40, 0xe0); urtwn_write_1(sc, 0xfe41, 0x8d); urtwn_write_1(sc, 0xfe42, 0x80); urtwn_pa_bias_init(sc); } /* Initialize GPIO setting. */ urtwn_write_1(sc, R92C_GPIO_MUXCFG, urtwn_read_1(sc, R92C_GPIO_MUXCFG) & ~R92C_GPIO_MUXCFG_ENBT); /* Fix for lower temperature. */ if (!(sc->chip & URTWN_CHIP_88E)) urtwn_write_1(sc, 0x15, 0xe9); usbd_transfer_start(sc->sc_xfer[URTWN_BULK_RX]); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; ifp->if_drv_flags |= IFF_DRV_RUNNING; callout_reset(&sc->sc_watchdog_ch, hz, urtwn_watchdog, sc); fail: return; } static void urtwn_init(void *arg) { struct urtwn_softc *sc = arg; URTWN_LOCK(sc); urtwn_init_locked(arg); URTWN_UNLOCK(sc); } static void urtwn_stop_locked(struct ifnet *ifp) { struct urtwn_softc *sc = ifp->if_softc; URTWN_ASSERT_LOCKED(sc); ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); callout_stop(&sc->sc_watchdog_ch); urtwn_abort_xfers(sc); } static void urtwn_stop(struct ifnet *ifp) { struct urtwn_softc *sc = ifp->if_softc; URTWN_LOCK(sc); urtwn_stop_locked(ifp); URTWN_UNLOCK(sc); } static void urtwn_abort_xfers(struct urtwn_softc *sc) { int i; URTWN_ASSERT_LOCKED(sc); /* abort any pending transfers */ for (i = 0; i < URTWN_N_TRANSFER; i++) usbd_transfer_stop(sc->sc_xfer[i]); } static int urtwn_raw_xmit(struct ieee80211_node *ni, struct mbuf *m, const struct ieee80211_bpf_params *params) { struct ieee80211com *ic = ni->ni_ic; struct ifnet *ifp = ic->ic_ifp; struct urtwn_softc *sc = ifp->if_softc; struct urtwn_data *bf; /* prevent management frames from being sent if we're not ready */ if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) { m_freem(m); ieee80211_free_node(ni); return (ENETDOWN); } URTWN_LOCK(sc); bf = urtwn_getbuf(sc); if (bf == NULL) { ieee80211_free_node(ni); m_freem(m); URTWN_UNLOCK(sc); return (ENOBUFS); } if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); if (urtwn_tx_start(sc, ni, m, bf) != 0) { ieee80211_free_node(ni); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next); URTWN_UNLOCK(sc); return (EIO); } URTWN_UNLOCK(sc); sc->sc_txtimer = 5; return (0); } static void urtwn_ms_delay(struct urtwn_softc *sc) { usb_pause_mtx(&sc->sc_mtx, hz / 1000); } static device_method_t urtwn_methods[] = { /* Device interface */ DEVMETHOD(device_probe, urtwn_match), DEVMETHOD(device_attach, urtwn_attach), DEVMETHOD(device_detach, urtwn_detach), DEVMETHOD_END }; static driver_t urtwn_driver = { "urtwn", urtwn_methods, sizeof(struct urtwn_softc) }; static devclass_t urtwn_devclass; DRIVER_MODULE(urtwn, uhub, urtwn_driver, urtwn_devclass, NULL, NULL); MODULE_DEPEND(urtwn, usb, 1, 1, 1); MODULE_DEPEND(urtwn, wlan, 1, 1, 1); MODULE_DEPEND(urtwn, firmware, 1, 1, 1); MODULE_VERSION(urtwn, 1); Index: head/sys/dev/usb/wlan/if_zyd.c =================================================================== --- head/sys/dev/usb/wlan/if_zyd.c (revision 276700) +++ head/sys/dev/usb/wlan/if_zyd.c (revision 276701) @@ -1,2975 +1,2975 @@ /* $OpenBSD: if_zyd.c,v 1.52 2007/02/11 00:08:04 jsg Exp $ */ /* $NetBSD: if_zyd.c,v 1.7 2007/06/21 04:04:29 kiyohara Exp $ */ /* $FreeBSD$ */ /*- * Copyright (c) 2006 by Damien Bergamini * Copyright (c) 2006 by Florian Stoehr * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include __FBSDID("$FreeBSD$"); /* * ZyDAS ZD1211/ZD1211B USB WLAN driver. */ #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 #ifdef INET #include #include #include #include #include #endif #include #include #include #include #include #include #include #include "usbdevs.h" #include #include #ifdef USB_DEBUG static int zyd_debug = 0; static SYSCTL_NODE(_hw_usb, OID_AUTO, zyd, CTLFLAG_RW, 0, "USB zyd"); -SYSCTL_INT(_hw_usb_zyd, OID_AUTO, debug, CTLFLAG_RW, &zyd_debug, 0, +SYSCTL_INT(_hw_usb_zyd, OID_AUTO, debug, CTLFLAG_RWTUN, &zyd_debug, 0, "zyd debug level"); enum { ZYD_DEBUG_XMIT = 0x00000001, /* basic xmit operation */ ZYD_DEBUG_RECV = 0x00000002, /* basic recv operation */ ZYD_DEBUG_RESET = 0x00000004, /* reset processing */ ZYD_DEBUG_INIT = 0x00000008, /* device init */ ZYD_DEBUG_TX_PROC = 0x00000010, /* tx ISR proc */ ZYD_DEBUG_RX_PROC = 0x00000020, /* rx ISR proc */ ZYD_DEBUG_STATE = 0x00000040, /* 802.11 state transitions */ ZYD_DEBUG_STAT = 0x00000080, /* statistic */ ZYD_DEBUG_FW = 0x00000100, /* firmware */ ZYD_DEBUG_CMD = 0x00000200, /* fw commands */ ZYD_DEBUG_ANY = 0xffffffff }; #define DPRINTF(sc, m, fmt, ...) do { \ if (zyd_debug & (m)) \ printf("%s: " fmt, __func__, ## __VA_ARGS__); \ } while (0) #else #define DPRINTF(sc, m, fmt, ...) do { \ (void) sc; \ } while (0) #endif #define zyd_do_request(sc,req,data) \ usbd_do_request_flags((sc)->sc_udev, &(sc)->sc_mtx, req, data, 0, NULL, 5000) static device_probe_t zyd_match; static device_attach_t zyd_attach; static device_detach_t zyd_detach; static usb_callback_t zyd_intr_read_callback; static usb_callback_t zyd_intr_write_callback; static usb_callback_t zyd_bulk_read_callback; static usb_callback_t zyd_bulk_write_callback; static struct ieee80211vap *zyd_vap_create(struct ieee80211com *, const char [IFNAMSIZ], int, enum ieee80211_opmode, int, const uint8_t [IEEE80211_ADDR_LEN], const uint8_t [IEEE80211_ADDR_LEN]); static void zyd_vap_delete(struct ieee80211vap *); static void zyd_tx_free(struct zyd_tx_data *, int); static void zyd_setup_tx_list(struct zyd_softc *); static void zyd_unsetup_tx_list(struct zyd_softc *); static int zyd_newstate(struct ieee80211vap *, enum ieee80211_state, int); static int zyd_cmd(struct zyd_softc *, uint16_t, const void *, int, void *, int, int); static int zyd_read16(struct zyd_softc *, uint16_t, uint16_t *); static int zyd_read32(struct zyd_softc *, uint16_t, uint32_t *); static int zyd_write16(struct zyd_softc *, uint16_t, uint16_t); static int zyd_write32(struct zyd_softc *, uint16_t, uint32_t); static int zyd_rfwrite(struct zyd_softc *, uint32_t); static int zyd_lock_phy(struct zyd_softc *); static int zyd_unlock_phy(struct zyd_softc *); static int zyd_rf_attach(struct zyd_softc *, uint8_t); static const char *zyd_rf_name(uint8_t); static int zyd_hw_init(struct zyd_softc *); static int zyd_read_pod(struct zyd_softc *); static int zyd_read_eeprom(struct zyd_softc *); static int zyd_get_macaddr(struct zyd_softc *); static int zyd_set_macaddr(struct zyd_softc *, const uint8_t *); static int zyd_set_bssid(struct zyd_softc *, const uint8_t *); static int zyd_switch_radio(struct zyd_softc *, int); static int zyd_set_led(struct zyd_softc *, int, int); static void zyd_set_multi(struct zyd_softc *); static void zyd_update_mcast(struct ifnet *); static int zyd_set_rxfilter(struct zyd_softc *); static void zyd_set_chan(struct zyd_softc *, struct ieee80211_channel *); static int zyd_set_beacon_interval(struct zyd_softc *, int); static void zyd_rx_data(struct usb_xfer *, int, uint16_t); static int zyd_tx_start(struct zyd_softc *, struct mbuf *, struct ieee80211_node *); static void zyd_start(struct ifnet *); static int zyd_raw_xmit(struct ieee80211_node *, struct mbuf *, const struct ieee80211_bpf_params *); static int zyd_ioctl(struct ifnet *, u_long, caddr_t); static void zyd_init_locked(struct zyd_softc *); static void zyd_init(void *); static void zyd_stop(struct zyd_softc *); static int zyd_loadfirmware(struct zyd_softc *); static void zyd_scan_start(struct ieee80211com *); static void zyd_scan_end(struct ieee80211com *); static void zyd_set_channel(struct ieee80211com *); static int zyd_rfmd_init(struct zyd_rf *); static int zyd_rfmd_switch_radio(struct zyd_rf *, int); static int zyd_rfmd_set_channel(struct zyd_rf *, uint8_t); static int zyd_al2230_init(struct zyd_rf *); static int zyd_al2230_switch_radio(struct zyd_rf *, int); static int zyd_al2230_set_channel(struct zyd_rf *, uint8_t); static int zyd_al2230_set_channel_b(struct zyd_rf *, uint8_t); static int zyd_al2230_init_b(struct zyd_rf *); static int zyd_al7230B_init(struct zyd_rf *); static int zyd_al7230B_switch_radio(struct zyd_rf *, int); static int zyd_al7230B_set_channel(struct zyd_rf *, uint8_t); static int zyd_al2210_init(struct zyd_rf *); static int zyd_al2210_switch_radio(struct zyd_rf *, int); static int zyd_al2210_set_channel(struct zyd_rf *, uint8_t); static int zyd_gct_init(struct zyd_rf *); static int zyd_gct_switch_radio(struct zyd_rf *, int); static int zyd_gct_set_channel(struct zyd_rf *, uint8_t); static int zyd_gct_mode(struct zyd_rf *); static int zyd_gct_set_channel_synth(struct zyd_rf *, int, int); static int zyd_gct_write(struct zyd_rf *, uint16_t); static int zyd_gct_txgain(struct zyd_rf *, uint8_t); static int zyd_maxim2_init(struct zyd_rf *); static int zyd_maxim2_switch_radio(struct zyd_rf *, int); static int zyd_maxim2_set_channel(struct zyd_rf *, uint8_t); static const struct zyd_phy_pair zyd_def_phy[] = ZYD_DEF_PHY; static const struct zyd_phy_pair zyd_def_phyB[] = ZYD_DEF_PHYB; /* various supported device vendors/products */ #define ZYD_ZD1211 0 #define ZYD_ZD1211B 1 #define ZYD_ZD1211_DEV(v,p) \ { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, ZYD_ZD1211) } #define ZYD_ZD1211B_DEV(v,p) \ { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, ZYD_ZD1211B) } static const STRUCT_USB_HOST_ID zyd_devs[] = { /* ZYD_ZD1211 */ ZYD_ZD1211_DEV(3COM2, 3CRUSB10075), ZYD_ZD1211_DEV(ABOCOM, WL54), ZYD_ZD1211_DEV(ASUS, WL159G), ZYD_ZD1211_DEV(CYBERTAN, TG54USB), ZYD_ZD1211_DEV(DRAYTEK, VIGOR550), ZYD_ZD1211_DEV(PLANEX2, GWUS54GD), ZYD_ZD1211_DEV(PLANEX2, GWUS54GZL), ZYD_ZD1211_DEV(PLANEX3, GWUS54GZ), ZYD_ZD1211_DEV(PLANEX3, GWUS54MINI), ZYD_ZD1211_DEV(SAGEM, XG760A), ZYD_ZD1211_DEV(SENAO, NUB8301), ZYD_ZD1211_DEV(SITECOMEU, WL113), ZYD_ZD1211_DEV(SWEEX, ZD1211), ZYD_ZD1211_DEV(TEKRAM, QUICKWLAN), ZYD_ZD1211_DEV(TEKRAM, ZD1211_1), ZYD_ZD1211_DEV(TEKRAM, ZD1211_2), ZYD_ZD1211_DEV(TWINMOS, G240), ZYD_ZD1211_DEV(UMEDIA, ALL0298V2), ZYD_ZD1211_DEV(UMEDIA, TEW429UB_A), ZYD_ZD1211_DEV(UMEDIA, TEW429UB), ZYD_ZD1211_DEV(WISTRONNEWEB, UR055G), ZYD_ZD1211_DEV(ZCOM, ZD1211), ZYD_ZD1211_DEV(ZYDAS, ZD1211), ZYD_ZD1211_DEV(ZYXEL, AG225H), ZYD_ZD1211_DEV(ZYXEL, ZYAIRG220), ZYD_ZD1211_DEV(ZYXEL, G200V2), /* ZYD_ZD1211B */ ZYD_ZD1211B_DEV(ACCTON, SMCWUSBG_NF), ZYD_ZD1211B_DEV(ACCTON, SMCWUSBG), ZYD_ZD1211B_DEV(ACCTON, ZD1211B), ZYD_ZD1211B_DEV(ASUS, A9T_WIFI), ZYD_ZD1211B_DEV(BELKIN, F5D7050_V4000), ZYD_ZD1211B_DEV(BELKIN, ZD1211B), ZYD_ZD1211B_DEV(CISCOLINKSYS, WUSBF54G), ZYD_ZD1211B_DEV(FIBERLINE, WL430U), ZYD_ZD1211B_DEV(MELCO, KG54L), ZYD_ZD1211B_DEV(PHILIPS, SNU5600), ZYD_ZD1211B_DEV(PLANEX2, GW_US54GXS), ZYD_ZD1211B_DEV(SAGEM, XG76NA), ZYD_ZD1211B_DEV(SITECOMEU, ZD1211B), ZYD_ZD1211B_DEV(UMEDIA, TEW429UBC1), ZYD_ZD1211B_DEV(USR, USR5423), ZYD_ZD1211B_DEV(VTECH, ZD1211B), ZYD_ZD1211B_DEV(ZCOM, ZD1211B), ZYD_ZD1211B_DEV(ZYDAS, ZD1211B), ZYD_ZD1211B_DEV(ZYXEL, M202), ZYD_ZD1211B_DEV(ZYXEL, G202), ZYD_ZD1211B_DEV(ZYXEL, G220V2) }; static const struct usb_config zyd_config[ZYD_N_TRANSFER] = { [ZYD_BULK_WR] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = ZYD_MAX_TXBUFSZ, .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = zyd_bulk_write_callback, .ep_index = 0, .timeout = 10000, /* 10 seconds */ }, [ZYD_BULK_RD] = { .type = UE_BULK, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = ZYX_MAX_RXBUFSZ, .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = zyd_bulk_read_callback, .ep_index = 0, }, [ZYD_INTR_WR] = { .type = UE_BULK_INTR, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_OUT, .bufsize = sizeof(struct zyd_cmd), .flags = {.pipe_bof = 1,.force_short_xfer = 1,}, .callback = zyd_intr_write_callback, .timeout = 1000, /* 1 second */ .ep_index = 1, }, [ZYD_INTR_RD] = { .type = UE_INTERRUPT, .endpoint = UE_ADDR_ANY, .direction = UE_DIR_IN, .bufsize = sizeof(struct zyd_cmd), .flags = {.pipe_bof = 1,.short_xfer_ok = 1,}, .callback = zyd_intr_read_callback, }, }; #define zyd_read16_m(sc, val, data) do { \ error = zyd_read16(sc, val, data); \ if (error != 0) \ goto fail; \ } while (0) #define zyd_write16_m(sc, val, data) do { \ error = zyd_write16(sc, val, data); \ if (error != 0) \ goto fail; \ } while (0) #define zyd_read32_m(sc, val, data) do { \ error = zyd_read32(sc, val, data); \ if (error != 0) \ goto fail; \ } while (0) #define zyd_write32_m(sc, val, data) do { \ error = zyd_write32(sc, val, data); \ if (error != 0) \ goto fail; \ } while (0) static int zyd_match(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); if (uaa->usb_mode != USB_MODE_HOST) return (ENXIO); if (uaa->info.bConfigIndex != ZYD_CONFIG_INDEX) return (ENXIO); if (uaa->info.bIfaceIndex != ZYD_IFACE_INDEX) return (ENXIO); return (usbd_lookup_id_by_uaa(zyd_devs, sizeof(zyd_devs), uaa)); } static int zyd_attach(device_t dev) { struct usb_attach_arg *uaa = device_get_ivars(dev); struct zyd_softc *sc = device_get_softc(dev); struct ifnet *ifp; struct ieee80211com *ic; uint8_t iface_index, bands; int error; if (uaa->info.bcdDevice < 0x4330) { device_printf(dev, "device version mismatch: 0x%X " "(only >= 43.30 supported)\n", uaa->info.bcdDevice); return (EINVAL); } device_set_usb_desc(dev); sc->sc_dev = dev; sc->sc_udev = uaa->device; sc->sc_macrev = USB_GET_DRIVER_INFO(uaa); mtx_init(&sc->sc_mtx, device_get_nameunit(sc->sc_dev), MTX_NETWORK_LOCK, MTX_DEF); STAILQ_INIT(&sc->sc_rqh); iface_index = ZYD_IFACE_INDEX; error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer, zyd_config, ZYD_N_TRANSFER, sc, &sc->sc_mtx); if (error) { device_printf(dev, "could not allocate USB transfers, " "err=%s\n", usbd_errstr(error)); goto detach; } ZYD_LOCK(sc); if ((error = zyd_get_macaddr(sc)) != 0) { device_printf(sc->sc_dev, "could not read EEPROM\n"); ZYD_UNLOCK(sc); goto detach; } ZYD_UNLOCK(sc); ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211); if (ifp == NULL) { device_printf(sc->sc_dev, "can not if_alloc()\n"); goto detach; } ifp->if_softc = sc; if_initname(ifp, "zyd", device_get_unit(sc->sc_dev)); ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; ifp->if_init = zyd_init; ifp->if_ioctl = zyd_ioctl; ifp->if_start = zyd_start; IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen); IFQ_SET_READY(&ifp->if_snd); ic = ifp->if_l2com; ic->ic_ifp = ifp; ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */ ic->ic_opmode = IEEE80211_M_STA; /* set device capabilities */ ic->ic_caps = IEEE80211_C_STA /* station mode */ | IEEE80211_C_MONITOR /* monitor mode */ | IEEE80211_C_SHPREAMBLE /* short preamble supported */ | IEEE80211_C_SHSLOT /* short slot time supported */ | IEEE80211_C_BGSCAN /* capable of bg scanning */ | IEEE80211_C_WPA /* 802.11i */ ; bands = 0; setbit(&bands, IEEE80211_MODE_11B); setbit(&bands, IEEE80211_MODE_11G); ieee80211_init_channels(ic, NULL, &bands); ieee80211_ifattach(ic, sc->sc_bssid); ic->ic_raw_xmit = zyd_raw_xmit; ic->ic_scan_start = zyd_scan_start; ic->ic_scan_end = zyd_scan_end; ic->ic_set_channel = zyd_set_channel; ic->ic_vap_create = zyd_vap_create; ic->ic_vap_delete = zyd_vap_delete; ic->ic_update_mcast = zyd_update_mcast; ic->ic_update_promisc = zyd_update_mcast; ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap), ZYD_TX_RADIOTAP_PRESENT, &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap), ZYD_RX_RADIOTAP_PRESENT); if (bootverbose) ieee80211_announce(ic); return (0); detach: zyd_detach(dev); return (ENXIO); /* failure */ } static int zyd_detach(device_t dev) { struct zyd_softc *sc = device_get_softc(dev); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic; unsigned int x; /* * Prevent further allocations from RX/TX data * lists and ioctls: */ ZYD_LOCK(sc); sc->sc_flags |= ZYD_FLAG_DETACHED; STAILQ_INIT(&sc->tx_q); STAILQ_INIT(&sc->tx_free); ZYD_UNLOCK(sc); /* drain USB transfers */ for (x = 0; x != ZYD_N_TRANSFER; x++) usbd_transfer_drain(sc->sc_xfer[x]); /* free TX list, if any */ ZYD_LOCK(sc); zyd_unsetup_tx_list(sc); ZYD_UNLOCK(sc); /* free USB transfers and some data buffers */ usbd_transfer_unsetup(sc->sc_xfer, ZYD_N_TRANSFER); if (ifp) { ic = ifp->if_l2com; ieee80211_ifdetach(ic); if_free(ifp); } mtx_destroy(&sc->sc_mtx); return (0); } static struct ieee80211vap * zyd_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit, enum ieee80211_opmode opmode, int flags, const uint8_t bssid[IEEE80211_ADDR_LEN], const uint8_t mac[IEEE80211_ADDR_LEN]) { struct zyd_vap *zvp; struct ieee80211vap *vap; if (!TAILQ_EMPTY(&ic->ic_vaps)) /* only one at a time */ return (NULL); zvp = (struct zyd_vap *) malloc(sizeof(struct zyd_vap), M_80211_VAP, M_NOWAIT | M_ZERO); if (zvp == NULL) return (NULL); vap = &zvp->vap; /* enable s/w bmiss handling for sta mode */ if (ieee80211_vap_setup(ic, vap, name, unit, opmode, flags | IEEE80211_CLONE_NOBEACONS, bssid, mac) != 0) { /* out of memory */ free(zvp, M_80211_VAP); return (NULL); } /* override state transition machine */ zvp->newstate = vap->iv_newstate; vap->iv_newstate = zyd_newstate; ieee80211_ratectl_init(vap); ieee80211_ratectl_setinterval(vap, 1000 /* 1 sec */); /* complete setup */ ieee80211_vap_attach(vap, ieee80211_media_change, ieee80211_media_status); ic->ic_opmode = opmode; return (vap); } static void zyd_vap_delete(struct ieee80211vap *vap) { struct zyd_vap *zvp = ZYD_VAP(vap); ieee80211_ratectl_deinit(vap); ieee80211_vap_detach(vap); free(zvp, M_80211_VAP); } static void zyd_tx_free(struct zyd_tx_data *data, int txerr) { struct zyd_softc *sc = data->sc; if (data->m != NULL) { if (data->m->m_flags & M_TXCB) ieee80211_process_callback(data->ni, data->m, txerr ? ETIMEDOUT : 0); m_freem(data->m); data->m = NULL; ieee80211_free_node(data->ni); data->ni = NULL; } STAILQ_INSERT_TAIL(&sc->tx_free, data, next); sc->tx_nfree++; } static void zyd_setup_tx_list(struct zyd_softc *sc) { struct zyd_tx_data *data; int i; sc->tx_nfree = 0; STAILQ_INIT(&sc->tx_q); STAILQ_INIT(&sc->tx_free); for (i = 0; i < ZYD_TX_LIST_CNT; i++) { data = &sc->tx_data[i]; data->sc = sc; STAILQ_INSERT_TAIL(&sc->tx_free, data, next); sc->tx_nfree++; } } static void zyd_unsetup_tx_list(struct zyd_softc *sc) { struct zyd_tx_data *data; int i; /* make sure any subsequent use of the queues will fail */ sc->tx_nfree = 0; STAILQ_INIT(&sc->tx_q); STAILQ_INIT(&sc->tx_free); /* free up all node references and mbufs */ for (i = 0; i < ZYD_TX_LIST_CNT; i++) { data = &sc->tx_data[i]; if (data->m != NULL) { m_freem(data->m); data->m = NULL; } if (data->ni != NULL) { ieee80211_free_node(data->ni); data->ni = NULL; } } } static int zyd_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg) { struct zyd_vap *zvp = ZYD_VAP(vap); struct ieee80211com *ic = vap->iv_ic; struct zyd_softc *sc = ic->ic_ifp->if_softc; int error; DPRINTF(sc, ZYD_DEBUG_STATE, "%s: %s -> %s\n", __func__, ieee80211_state_name[vap->iv_state], ieee80211_state_name[nstate]); IEEE80211_UNLOCK(ic); ZYD_LOCK(sc); switch (nstate) { case IEEE80211_S_AUTH: zyd_set_chan(sc, ic->ic_curchan); break; case IEEE80211_S_RUN: if (vap->iv_opmode == IEEE80211_M_MONITOR) break; /* turn link LED on */ error = zyd_set_led(sc, ZYD_LED1, 1); if (error != 0) break; /* make data LED blink upon Tx */ zyd_write32_m(sc, sc->sc_fwbase + ZYD_FW_LINK_STATUS, 1); IEEE80211_ADDR_COPY(sc->sc_bssid, vap->iv_bss->ni_bssid); zyd_set_bssid(sc, sc->sc_bssid); break; default: break; } fail: ZYD_UNLOCK(sc); IEEE80211_LOCK(ic); return (zvp->newstate(vap, nstate, arg)); } /* * Callback handler for interrupt transfer */ static void zyd_intr_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct zyd_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps); struct ieee80211_node *ni; struct zyd_cmd *cmd = &sc->sc_ibuf; struct usb_page_cache *pc; int datalen; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, 0, cmd, sizeof(*cmd)); switch (le16toh(cmd->code)) { case ZYD_NOTIF_RETRYSTATUS: { struct zyd_notif_retry *retry = (struct zyd_notif_retry *)cmd->data; DPRINTF(sc, ZYD_DEBUG_TX_PROC, "retry intr: rate=0x%x addr=%s count=%d (0x%x)\n", le16toh(retry->rate), ether_sprintf(retry->macaddr), le16toh(retry->count)&0xff, le16toh(retry->count)); /* * Find the node to which the packet was sent and * update its retry statistics. In BSS mode, this node * is the AP we're associated to so no lookup is * actually needed. */ ni = ieee80211_find_txnode(vap, retry->macaddr); if (ni != NULL) { int retrycnt = (int)(le16toh(retry->count) & 0xff); ieee80211_ratectl_tx_complete(vap, ni, IEEE80211_RATECTL_TX_FAILURE, &retrycnt, NULL); ieee80211_free_node(ni); } if (le16toh(retry->count) & 0x100) if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); /* too many retries */ break; } case ZYD_NOTIF_IORD: { struct zyd_rq *rqp; if (le16toh(*(uint16_t *)cmd->data) == ZYD_CR_INTERRUPT) break; /* HMAC interrupt */ datalen = actlen - sizeof(cmd->code); datalen -= 2; /* XXX: padding? */ STAILQ_FOREACH(rqp, &sc->sc_rqh, rq) { int i; int count; if (rqp->olen != datalen) continue; count = rqp->olen / sizeof(struct zyd_pair); for (i = 0; i < count; i++) { if (*(((const uint16_t *)rqp->idata) + i) != (((struct zyd_pair *)cmd->data) + i)->reg) break; } if (i != count) continue; /* copy answer into caller-supplied buffer */ memcpy(rqp->odata, cmd->data, rqp->olen); DPRINTF(sc, ZYD_DEBUG_CMD, "command %p complete, data = %*D \n", rqp, rqp->olen, (char *)rqp->odata, ":"); wakeup(rqp); /* wakeup caller */ break; } if (rqp == NULL) { device_printf(sc->sc_dev, "unexpected IORD notification %*D\n", datalen, cmd->data, ":"); } break; } default: device_printf(sc->sc_dev, "unknown notification %x\n", le16toh(cmd->code)); } /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); break; default: /* Error */ DPRINTF(sc, ZYD_DEBUG_CMD, "error = %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static void zyd_intr_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct zyd_softc *sc = usbd_xfer_softc(xfer); struct zyd_rq *rqp, *cmd; struct usb_page_cache *pc; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: cmd = usbd_xfer_get_priv(xfer); DPRINTF(sc, ZYD_DEBUG_CMD, "command %p transferred\n", cmd); STAILQ_FOREACH(rqp, &sc->sc_rqh, rq) { /* Ensure the cached rq pointer is still valid */ if (rqp == cmd && (rqp->flags & ZYD_CMD_FLAG_READ) == 0) wakeup(rqp); /* wakeup caller */ } /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: STAILQ_FOREACH(rqp, &sc->sc_rqh, rq) { if (rqp->flags & ZYD_CMD_FLAG_SENT) continue; pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, rqp->cmd, rqp->ilen); usbd_xfer_set_frame_len(xfer, 0, rqp->ilen); usbd_xfer_set_priv(xfer, rqp); rqp->flags |= ZYD_CMD_FLAG_SENT; usbd_transfer_submit(xfer); break; } break; default: /* Error */ DPRINTF(sc, ZYD_DEBUG_ANY, "error = %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static int zyd_cmd(struct zyd_softc *sc, uint16_t code, const void *idata, int ilen, void *odata, int olen, int flags) { struct zyd_cmd cmd; struct zyd_rq rq; int error; if (ilen > (int)sizeof(cmd.data)) return (EINVAL); cmd.code = htole16(code); memcpy(cmd.data, idata, ilen); DPRINTF(sc, ZYD_DEBUG_CMD, "sending cmd %p = %*D\n", &rq, ilen, idata, ":"); rq.cmd = &cmd; rq.idata = idata; rq.odata = odata; rq.ilen = sizeof(uint16_t) + ilen; rq.olen = olen; rq.flags = flags; STAILQ_INSERT_TAIL(&sc->sc_rqh, &rq, rq); usbd_transfer_start(sc->sc_xfer[ZYD_INTR_RD]); usbd_transfer_start(sc->sc_xfer[ZYD_INTR_WR]); /* wait at most one second for command reply */ error = mtx_sleep(&rq, &sc->sc_mtx, 0 , "zydcmd", hz); if (error) device_printf(sc->sc_dev, "command timeout\n"); STAILQ_REMOVE(&sc->sc_rqh, &rq, zyd_rq, rq); DPRINTF(sc, ZYD_DEBUG_CMD, "finsihed cmd %p, error = %d \n", &rq, error); return (error); } static int zyd_read16(struct zyd_softc *sc, uint16_t reg, uint16_t *val) { struct zyd_pair tmp; int error; reg = htole16(reg); error = zyd_cmd(sc, ZYD_CMD_IORD, ®, sizeof(reg), &tmp, sizeof(tmp), ZYD_CMD_FLAG_READ); if (error == 0) *val = le16toh(tmp.val); return (error); } static int zyd_read32(struct zyd_softc *sc, uint16_t reg, uint32_t *val) { struct zyd_pair tmp[2]; uint16_t regs[2]; int error; regs[0] = htole16(ZYD_REG32_HI(reg)); regs[1] = htole16(ZYD_REG32_LO(reg)); error = zyd_cmd(sc, ZYD_CMD_IORD, regs, sizeof(regs), tmp, sizeof(tmp), ZYD_CMD_FLAG_READ); if (error == 0) *val = le16toh(tmp[0].val) << 16 | le16toh(tmp[1].val); return (error); } static int zyd_write16(struct zyd_softc *sc, uint16_t reg, uint16_t val) { struct zyd_pair pair; pair.reg = htole16(reg); pair.val = htole16(val); return zyd_cmd(sc, ZYD_CMD_IOWR, &pair, sizeof(pair), NULL, 0, 0); } static int zyd_write32(struct zyd_softc *sc, uint16_t reg, uint32_t val) { struct zyd_pair pair[2]; pair[0].reg = htole16(ZYD_REG32_HI(reg)); pair[0].val = htole16(val >> 16); pair[1].reg = htole16(ZYD_REG32_LO(reg)); pair[1].val = htole16(val & 0xffff); return zyd_cmd(sc, ZYD_CMD_IOWR, pair, sizeof(pair), NULL, 0, 0); } static int zyd_rfwrite(struct zyd_softc *sc, uint32_t val) { struct zyd_rf *rf = &sc->sc_rf; struct zyd_rfwrite_cmd req; uint16_t cr203; int error, i; zyd_read16_m(sc, ZYD_CR203, &cr203); cr203 &= ~(ZYD_RF_IF_LE | ZYD_RF_CLK | ZYD_RF_DATA); req.code = htole16(2); req.width = htole16(rf->width); for (i = 0; i < rf->width; i++) { req.bit[i] = htole16(cr203); if (val & (1 << (rf->width - 1 - i))) req.bit[i] |= htole16(ZYD_RF_DATA); } error = zyd_cmd(sc, ZYD_CMD_RFCFG, &req, 4 + 2 * rf->width, NULL, 0, 0); fail: return (error); } static int zyd_rfwrite_cr(struct zyd_softc *sc, uint32_t val) { int error; zyd_write16_m(sc, ZYD_CR244, (val >> 16) & 0xff); zyd_write16_m(sc, ZYD_CR243, (val >> 8) & 0xff); zyd_write16_m(sc, ZYD_CR242, (val >> 0) & 0xff); fail: return (error); } static int zyd_lock_phy(struct zyd_softc *sc) { int error; uint32_t tmp; zyd_read32_m(sc, ZYD_MAC_MISC, &tmp); tmp &= ~ZYD_UNLOCK_PHY_REGS; zyd_write32_m(sc, ZYD_MAC_MISC, tmp); fail: return (error); } static int zyd_unlock_phy(struct zyd_softc *sc) { int error; uint32_t tmp; zyd_read32_m(sc, ZYD_MAC_MISC, &tmp); tmp |= ZYD_UNLOCK_PHY_REGS; zyd_write32_m(sc, ZYD_MAC_MISC, tmp); fail: return (error); } /* * RFMD RF methods. */ static int zyd_rfmd_init(struct zyd_rf *rf) { #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) struct zyd_softc *sc = rf->rf_sc; static const struct zyd_phy_pair phyini[] = ZYD_RFMD_PHY; static const uint32_t rfini[] = ZYD_RFMD_RF; int i, error; /* init RF-dependent PHY registers */ for (i = 0; i < N(phyini); i++) { zyd_write16_m(sc, phyini[i].reg, phyini[i].val); } /* init RFMD radio */ for (i = 0; i < N(rfini); i++) { if ((error = zyd_rfwrite(sc, rfini[i])) != 0) return (error); } fail: return (error); #undef N } static int zyd_rfmd_switch_radio(struct zyd_rf *rf, int on) { int error; struct zyd_softc *sc = rf->rf_sc; zyd_write16_m(sc, ZYD_CR10, on ? 0x89 : 0x15); zyd_write16_m(sc, ZYD_CR11, on ? 0x00 : 0x81); fail: return (error); } static int zyd_rfmd_set_channel(struct zyd_rf *rf, uint8_t chan) { int error; struct zyd_softc *sc = rf->rf_sc; static const struct { uint32_t r1, r2; } rfprog[] = ZYD_RFMD_CHANTABLE; error = zyd_rfwrite(sc, rfprog[chan - 1].r1); if (error != 0) goto fail; error = zyd_rfwrite(sc, rfprog[chan - 1].r2); if (error != 0) goto fail; fail: return (error); } /* * AL2230 RF methods. */ static int zyd_al2230_init(struct zyd_rf *rf) { #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) struct zyd_softc *sc = rf->rf_sc; static const struct zyd_phy_pair phyini[] = ZYD_AL2230_PHY; static const struct zyd_phy_pair phy2230s[] = ZYD_AL2230S_PHY_INIT; static const struct zyd_phy_pair phypll[] = { { ZYD_CR251, 0x2f }, { ZYD_CR251, 0x3f }, { ZYD_CR138, 0x28 }, { ZYD_CR203, 0x06 } }; static const uint32_t rfini1[] = ZYD_AL2230_RF_PART1; static const uint32_t rfini2[] = ZYD_AL2230_RF_PART2; static const uint32_t rfini3[] = ZYD_AL2230_RF_PART3; int i, error; /* init RF-dependent PHY registers */ for (i = 0; i < N(phyini); i++) zyd_write16_m(sc, phyini[i].reg, phyini[i].val); if (sc->sc_rfrev == ZYD_RF_AL2230S || sc->sc_al2230s != 0) { for (i = 0; i < N(phy2230s); i++) zyd_write16_m(sc, phy2230s[i].reg, phy2230s[i].val); } /* init AL2230 radio */ for (i = 0; i < N(rfini1); i++) { error = zyd_rfwrite(sc, rfini1[i]); if (error != 0) goto fail; } if (sc->sc_rfrev == ZYD_RF_AL2230S || sc->sc_al2230s != 0) error = zyd_rfwrite(sc, 0x000824); else error = zyd_rfwrite(sc, 0x0005a4); if (error != 0) goto fail; for (i = 0; i < N(rfini2); i++) { error = zyd_rfwrite(sc, rfini2[i]); if (error != 0) goto fail; } for (i = 0; i < N(phypll); i++) zyd_write16_m(sc, phypll[i].reg, phypll[i].val); for (i = 0; i < N(rfini3); i++) { error = zyd_rfwrite(sc, rfini3[i]); if (error != 0) goto fail; } fail: return (error); #undef N } static int zyd_al2230_fini(struct zyd_rf *rf) { #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) int error, i; struct zyd_softc *sc = rf->rf_sc; static const struct zyd_phy_pair phy[] = ZYD_AL2230_PHY_FINI_PART1; for (i = 0; i < N(phy); i++) zyd_write16_m(sc, phy[i].reg, phy[i].val); if (sc->sc_newphy != 0) zyd_write16_m(sc, ZYD_CR9, 0xe1); zyd_write16_m(sc, ZYD_CR203, 0x6); fail: return (error); #undef N } static int zyd_al2230_init_b(struct zyd_rf *rf) { #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) struct zyd_softc *sc = rf->rf_sc; static const struct zyd_phy_pair phy1[] = ZYD_AL2230_PHY_PART1; static const struct zyd_phy_pair phy2[] = ZYD_AL2230_PHY_PART2; static const struct zyd_phy_pair phy3[] = ZYD_AL2230_PHY_PART3; static const struct zyd_phy_pair phy2230s[] = ZYD_AL2230S_PHY_INIT; static const struct zyd_phy_pair phyini[] = ZYD_AL2230_PHY_B; static const uint32_t rfini_part1[] = ZYD_AL2230_RF_B_PART1; static const uint32_t rfini_part2[] = ZYD_AL2230_RF_B_PART2; static const uint32_t rfini_part3[] = ZYD_AL2230_RF_B_PART3; static const uint32_t zyd_al2230_chtable[][3] = ZYD_AL2230_CHANTABLE; int i, error; for (i = 0; i < N(phy1); i++) zyd_write16_m(sc, phy1[i].reg, phy1[i].val); /* init RF-dependent PHY registers */ for (i = 0; i < N(phyini); i++) zyd_write16_m(sc, phyini[i].reg, phyini[i].val); if (sc->sc_rfrev == ZYD_RF_AL2230S || sc->sc_al2230s != 0) { for (i = 0; i < N(phy2230s); i++) zyd_write16_m(sc, phy2230s[i].reg, phy2230s[i].val); } for (i = 0; i < 3; i++) { error = zyd_rfwrite_cr(sc, zyd_al2230_chtable[0][i]); if (error != 0) return (error); } for (i = 0; i < N(rfini_part1); i++) { error = zyd_rfwrite_cr(sc, rfini_part1[i]); if (error != 0) return (error); } if (sc->sc_rfrev == ZYD_RF_AL2230S || sc->sc_al2230s != 0) error = zyd_rfwrite(sc, 0x241000); else error = zyd_rfwrite(sc, 0x25a000); if (error != 0) goto fail; for (i = 0; i < N(rfini_part2); i++) { error = zyd_rfwrite_cr(sc, rfini_part2[i]); if (error != 0) return (error); } for (i = 0; i < N(phy2); i++) zyd_write16_m(sc, phy2[i].reg, phy2[i].val); for (i = 0; i < N(rfini_part3); i++) { error = zyd_rfwrite_cr(sc, rfini_part3[i]); if (error != 0) return (error); } for (i = 0; i < N(phy3); i++) zyd_write16_m(sc, phy3[i].reg, phy3[i].val); error = zyd_al2230_fini(rf); fail: return (error); #undef N } static int zyd_al2230_switch_radio(struct zyd_rf *rf, int on) { struct zyd_softc *sc = rf->rf_sc; int error, on251 = (sc->sc_macrev == ZYD_ZD1211) ? 0x3f : 0x7f; zyd_write16_m(sc, ZYD_CR11, on ? 0x00 : 0x04); zyd_write16_m(sc, ZYD_CR251, on ? on251 : 0x2f); fail: return (error); } static int zyd_al2230_set_channel(struct zyd_rf *rf, uint8_t chan) { #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) int error, i; struct zyd_softc *sc = rf->rf_sc; static const struct zyd_phy_pair phy1[] = { { ZYD_CR138, 0x28 }, { ZYD_CR203, 0x06 }, }; static const struct { uint32_t r1, r2, r3; } rfprog[] = ZYD_AL2230_CHANTABLE; error = zyd_rfwrite(sc, rfprog[chan - 1].r1); if (error != 0) goto fail; error = zyd_rfwrite(sc, rfprog[chan - 1].r2); if (error != 0) goto fail; error = zyd_rfwrite(sc, rfprog[chan - 1].r3); if (error != 0) goto fail; for (i = 0; i < N(phy1); i++) zyd_write16_m(sc, phy1[i].reg, phy1[i].val); fail: return (error); #undef N } static int zyd_al2230_set_channel_b(struct zyd_rf *rf, uint8_t chan) { #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) int error, i; struct zyd_softc *sc = rf->rf_sc; static const struct zyd_phy_pair phy1[] = ZYD_AL2230_PHY_PART1; static const struct { uint32_t r1, r2, r3; } rfprog[] = ZYD_AL2230_CHANTABLE_B; for (i = 0; i < N(phy1); i++) zyd_write16_m(sc, phy1[i].reg, phy1[i].val); error = zyd_rfwrite_cr(sc, rfprog[chan - 1].r1); if (error != 0) goto fail; error = zyd_rfwrite_cr(sc, rfprog[chan - 1].r2); if (error != 0) goto fail; error = zyd_rfwrite_cr(sc, rfprog[chan - 1].r3); if (error != 0) goto fail; error = zyd_al2230_fini(rf); fail: return (error); #undef N } #define ZYD_AL2230_PHY_BANDEDGE6 \ { \ { ZYD_CR128, 0x14 }, { ZYD_CR129, 0x12 }, { ZYD_CR130, 0x10 }, \ { ZYD_CR47, 0x1e } \ } static int zyd_al2230_bandedge6(struct zyd_rf *rf, struct ieee80211_channel *c) { #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) int error = 0, i; struct zyd_softc *sc = rf->rf_sc; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct zyd_phy_pair r[] = ZYD_AL2230_PHY_BANDEDGE6; int chan = ieee80211_chan2ieee(ic, c); if (chan == 1 || chan == 11) r[0].val = 0x12; for (i = 0; i < N(r); i++) zyd_write16_m(sc, r[i].reg, r[i].val); fail: return (error); #undef N } /* * AL7230B RF methods. */ static int zyd_al7230B_init(struct zyd_rf *rf) { #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) struct zyd_softc *sc = rf->rf_sc; static const struct zyd_phy_pair phyini_1[] = ZYD_AL7230B_PHY_1; static const struct zyd_phy_pair phyini_2[] = ZYD_AL7230B_PHY_2; static const struct zyd_phy_pair phyini_3[] = ZYD_AL7230B_PHY_3; static const uint32_t rfini_1[] = ZYD_AL7230B_RF_1; static const uint32_t rfini_2[] = ZYD_AL7230B_RF_2; int i, error; /* for AL7230B, PHY and RF need to be initialized in "phases" */ /* init RF-dependent PHY registers, part one */ for (i = 0; i < N(phyini_1); i++) zyd_write16_m(sc, phyini_1[i].reg, phyini_1[i].val); /* init AL7230B radio, part one */ for (i = 0; i < N(rfini_1); i++) { if ((error = zyd_rfwrite(sc, rfini_1[i])) != 0) return (error); } /* init RF-dependent PHY registers, part two */ for (i = 0; i < N(phyini_2); i++) zyd_write16_m(sc, phyini_2[i].reg, phyini_2[i].val); /* init AL7230B radio, part two */ for (i = 0; i < N(rfini_2); i++) { if ((error = zyd_rfwrite(sc, rfini_2[i])) != 0) return (error); } /* init RF-dependent PHY registers, part three */ for (i = 0; i < N(phyini_3); i++) zyd_write16_m(sc, phyini_3[i].reg, phyini_3[i].val); fail: return (error); #undef N } static int zyd_al7230B_switch_radio(struct zyd_rf *rf, int on) { int error; struct zyd_softc *sc = rf->rf_sc; zyd_write16_m(sc, ZYD_CR11, on ? 0x00 : 0x04); zyd_write16_m(sc, ZYD_CR251, on ? 0x3f : 0x2f); fail: return (error); } static int zyd_al7230B_set_channel(struct zyd_rf *rf, uint8_t chan) { #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) struct zyd_softc *sc = rf->rf_sc; static const struct { uint32_t r1, r2; } rfprog[] = ZYD_AL7230B_CHANTABLE; static const uint32_t rfsc[] = ZYD_AL7230B_RF_SETCHANNEL; int i, error; zyd_write16_m(sc, ZYD_CR240, 0x57); zyd_write16_m(sc, ZYD_CR251, 0x2f); for (i = 0; i < N(rfsc); i++) { if ((error = zyd_rfwrite(sc, rfsc[i])) != 0) return (error); } zyd_write16_m(sc, ZYD_CR128, 0x14); zyd_write16_m(sc, ZYD_CR129, 0x12); zyd_write16_m(sc, ZYD_CR130, 0x10); zyd_write16_m(sc, ZYD_CR38, 0x38); zyd_write16_m(sc, ZYD_CR136, 0xdf); error = zyd_rfwrite(sc, rfprog[chan - 1].r1); if (error != 0) goto fail; error = zyd_rfwrite(sc, rfprog[chan - 1].r2); if (error != 0) goto fail; error = zyd_rfwrite(sc, 0x3c9000); if (error != 0) goto fail; zyd_write16_m(sc, ZYD_CR251, 0x3f); zyd_write16_m(sc, ZYD_CR203, 0x06); zyd_write16_m(sc, ZYD_CR240, 0x08); fail: return (error); #undef N } /* * AL2210 RF methods. */ static int zyd_al2210_init(struct zyd_rf *rf) { #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) struct zyd_softc *sc = rf->rf_sc; static const struct zyd_phy_pair phyini[] = ZYD_AL2210_PHY; static const uint32_t rfini[] = ZYD_AL2210_RF; uint32_t tmp; int i, error; zyd_write32_m(sc, ZYD_CR18, 2); /* init RF-dependent PHY registers */ for (i = 0; i < N(phyini); i++) zyd_write16_m(sc, phyini[i].reg, phyini[i].val); /* init AL2210 radio */ for (i = 0; i < N(rfini); i++) { if ((error = zyd_rfwrite(sc, rfini[i])) != 0) return (error); } zyd_write16_m(sc, ZYD_CR47, 0x1e); zyd_read32_m(sc, ZYD_CR_RADIO_PD, &tmp); zyd_write32_m(sc, ZYD_CR_RADIO_PD, tmp & ~1); zyd_write32_m(sc, ZYD_CR_RADIO_PD, tmp | 1); zyd_write32_m(sc, ZYD_CR_RFCFG, 0x05); zyd_write32_m(sc, ZYD_CR_RFCFG, 0x00); zyd_write16_m(sc, ZYD_CR47, 0x1e); zyd_write32_m(sc, ZYD_CR18, 3); fail: return (error); #undef N } static int zyd_al2210_switch_radio(struct zyd_rf *rf, int on) { /* vendor driver does nothing for this RF chip */ return (0); } static int zyd_al2210_set_channel(struct zyd_rf *rf, uint8_t chan) { int error; struct zyd_softc *sc = rf->rf_sc; static const uint32_t rfprog[] = ZYD_AL2210_CHANTABLE; uint32_t tmp; zyd_write32_m(sc, ZYD_CR18, 2); zyd_write16_m(sc, ZYD_CR47, 0x1e); zyd_read32_m(sc, ZYD_CR_RADIO_PD, &tmp); zyd_write32_m(sc, ZYD_CR_RADIO_PD, tmp & ~1); zyd_write32_m(sc, ZYD_CR_RADIO_PD, tmp | 1); zyd_write32_m(sc, ZYD_CR_RFCFG, 0x05); zyd_write32_m(sc, ZYD_CR_RFCFG, 0x00); zyd_write16_m(sc, ZYD_CR47, 0x1e); /* actually set the channel */ error = zyd_rfwrite(sc, rfprog[chan - 1]); if (error != 0) goto fail; zyd_write32_m(sc, ZYD_CR18, 3); fail: return (error); } /* * GCT RF methods. */ static int zyd_gct_init(struct zyd_rf *rf) { #define ZYD_GCT_INTR_REG 0x85c1 #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) struct zyd_softc *sc = rf->rf_sc; static const struct zyd_phy_pair phyini[] = ZYD_GCT_PHY; static const uint32_t rfini[] = ZYD_GCT_RF; static const uint16_t vco[11][7] = ZYD_GCT_VCO; int i, idx = -1, error; uint16_t data; /* init RF-dependent PHY registers */ for (i = 0; i < N(phyini); i++) zyd_write16_m(sc, phyini[i].reg, phyini[i].val); /* init cgt radio */ for (i = 0; i < N(rfini); i++) { if ((error = zyd_rfwrite(sc, rfini[i])) != 0) return (error); } error = zyd_gct_mode(rf); if (error != 0) return (error); for (i = 0; i < (int)(N(vco) - 1); i++) { error = zyd_gct_set_channel_synth(rf, 1, 0); if (error != 0) goto fail; error = zyd_gct_write(rf, vco[i][0]); if (error != 0) goto fail; zyd_write16_m(sc, ZYD_GCT_INTR_REG, 0xf); zyd_read16_m(sc, ZYD_GCT_INTR_REG, &data); if ((data & 0xf) == 0) { idx = i; break; } } if (idx == -1) { error = zyd_gct_set_channel_synth(rf, 1, 1); if (error != 0) goto fail; error = zyd_gct_write(rf, 0x6662); if (error != 0) goto fail; } rf->idx = idx; zyd_write16_m(sc, ZYD_CR203, 0x6); fail: return (error); #undef N #undef ZYD_GCT_INTR_REG } static int zyd_gct_mode(struct zyd_rf *rf) { #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) struct zyd_softc *sc = rf->rf_sc; static const uint32_t mode[] = { 0x25f98, 0x25f9a, 0x25f94, 0x27fd4 }; int i, error; for (i = 0; i < N(mode); i++) { if ((error = zyd_rfwrite(sc, mode[i])) != 0) break; } return (error); #undef N } static int zyd_gct_set_channel_synth(struct zyd_rf *rf, int chan, int acal) { int error, idx = chan - 1; struct zyd_softc *sc = rf->rf_sc; static uint32_t acal_synth[] = ZYD_GCT_CHANNEL_ACAL; static uint32_t std_synth[] = ZYD_GCT_CHANNEL_STD; static uint32_t div_synth[] = ZYD_GCT_CHANNEL_DIV; error = zyd_rfwrite(sc, (acal == 1) ? acal_synth[idx] : std_synth[idx]); if (error != 0) return (error); return zyd_rfwrite(sc, div_synth[idx]); } static int zyd_gct_write(struct zyd_rf *rf, uint16_t value) { struct zyd_softc *sc = rf->rf_sc; return zyd_rfwrite(sc, 0x300000 | 0x40000 | value); } static int zyd_gct_switch_radio(struct zyd_rf *rf, int on) { int error; struct zyd_softc *sc = rf->rf_sc; error = zyd_rfwrite(sc, on ? 0x25f94 : 0x25f90); if (error != 0) return (error); zyd_write16_m(sc, ZYD_CR11, on ? 0x00 : 0x04); zyd_write16_m(sc, ZYD_CR251, on ? ((sc->sc_macrev == ZYD_ZD1211B) ? 0x7f : 0x3f) : 0x2f); fail: return (error); } static int zyd_gct_set_channel(struct zyd_rf *rf, uint8_t chan) { #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) int error, i; struct zyd_softc *sc = rf->rf_sc; static const struct zyd_phy_pair cmd[] = { { ZYD_CR80, 0x30 }, { ZYD_CR81, 0x30 }, { ZYD_CR79, 0x58 }, { ZYD_CR12, 0xf0 }, { ZYD_CR77, 0x1b }, { ZYD_CR78, 0x58 }, }; static const uint16_t vco[11][7] = ZYD_GCT_VCO; error = zyd_gct_set_channel_synth(rf, chan, 0); if (error != 0) goto fail; error = zyd_gct_write(rf, (rf->idx == -1) ? 0x6662 : vco[rf->idx][((chan - 1) / 2)]); if (error != 0) goto fail; error = zyd_gct_mode(rf); if (error != 0) return (error); for (i = 0; i < N(cmd); i++) zyd_write16_m(sc, cmd[i].reg, cmd[i].val); error = zyd_gct_txgain(rf, chan); if (error != 0) return (error); zyd_write16_m(sc, ZYD_CR203, 0x6); fail: return (error); #undef N } static int zyd_gct_txgain(struct zyd_rf *rf, uint8_t chan) { #define N(a) (sizeof(a) / sizeof((a)[0])) struct zyd_softc *sc = rf->rf_sc; static uint32_t txgain[] = ZYD_GCT_TXGAIN; uint8_t idx = sc->sc_pwrint[chan - 1]; if (idx >= N(txgain)) { device_printf(sc->sc_dev, "could not set TX gain (%d %#x)\n", chan, idx); return 0; } return zyd_rfwrite(sc, 0x700000 | txgain[idx]); #undef N } /* * Maxim2 RF methods. */ static int zyd_maxim2_init(struct zyd_rf *rf) { #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) struct zyd_softc *sc = rf->rf_sc; static const struct zyd_phy_pair phyini[] = ZYD_MAXIM2_PHY; static const uint32_t rfini[] = ZYD_MAXIM2_RF; uint16_t tmp; int i, error; /* init RF-dependent PHY registers */ for (i = 0; i < N(phyini); i++) zyd_write16_m(sc, phyini[i].reg, phyini[i].val); zyd_read16_m(sc, ZYD_CR203, &tmp); zyd_write16_m(sc, ZYD_CR203, tmp & ~(1 << 4)); /* init maxim2 radio */ for (i = 0; i < N(rfini); i++) { if ((error = zyd_rfwrite(sc, rfini[i])) != 0) return (error); } zyd_read16_m(sc, ZYD_CR203, &tmp); zyd_write16_m(sc, ZYD_CR203, tmp | (1 << 4)); fail: return (error); #undef N } static int zyd_maxim2_switch_radio(struct zyd_rf *rf, int on) { /* vendor driver does nothing for this RF chip */ return (0); } static int zyd_maxim2_set_channel(struct zyd_rf *rf, uint8_t chan) { #define N(a) ((int)(sizeof(a) / sizeof((a)[0]))) struct zyd_softc *sc = rf->rf_sc; static const struct zyd_phy_pair phyini[] = ZYD_MAXIM2_PHY; static const uint32_t rfini[] = ZYD_MAXIM2_RF; static const struct { uint32_t r1, r2; } rfprog[] = ZYD_MAXIM2_CHANTABLE; uint16_t tmp; int i, error; /* * Do the same as we do when initializing it, except for the channel * values coming from the two channel tables. */ /* init RF-dependent PHY registers */ for (i = 0; i < N(phyini); i++) zyd_write16_m(sc, phyini[i].reg, phyini[i].val); zyd_read16_m(sc, ZYD_CR203, &tmp); zyd_write16_m(sc, ZYD_CR203, tmp & ~(1 << 4)); /* first two values taken from the chantables */ error = zyd_rfwrite(sc, rfprog[chan - 1].r1); if (error != 0) goto fail; error = zyd_rfwrite(sc, rfprog[chan - 1].r2); if (error != 0) goto fail; /* init maxim2 radio - skipping the two first values */ for (i = 2; i < N(rfini); i++) { if ((error = zyd_rfwrite(sc, rfini[i])) != 0) return (error); } zyd_read16_m(sc, ZYD_CR203, &tmp); zyd_write16_m(sc, ZYD_CR203, tmp | (1 << 4)); fail: return (error); #undef N } static int zyd_rf_attach(struct zyd_softc *sc, uint8_t type) { struct zyd_rf *rf = &sc->sc_rf; rf->rf_sc = sc; rf->update_pwr = 1; switch (type) { case ZYD_RF_RFMD: rf->init = zyd_rfmd_init; rf->switch_radio = zyd_rfmd_switch_radio; rf->set_channel = zyd_rfmd_set_channel; rf->width = 24; /* 24-bit RF values */ break; case ZYD_RF_AL2230: case ZYD_RF_AL2230S: if (sc->sc_macrev == ZYD_ZD1211B) { rf->init = zyd_al2230_init_b; rf->set_channel = zyd_al2230_set_channel_b; } else { rf->init = zyd_al2230_init; rf->set_channel = zyd_al2230_set_channel; } rf->switch_radio = zyd_al2230_switch_radio; rf->bandedge6 = zyd_al2230_bandedge6; rf->width = 24; /* 24-bit RF values */ break; case ZYD_RF_AL7230B: rf->init = zyd_al7230B_init; rf->switch_radio = zyd_al7230B_switch_radio; rf->set_channel = zyd_al7230B_set_channel; rf->width = 24; /* 24-bit RF values */ break; case ZYD_RF_AL2210: rf->init = zyd_al2210_init; rf->switch_radio = zyd_al2210_switch_radio; rf->set_channel = zyd_al2210_set_channel; rf->width = 24; /* 24-bit RF values */ break; case ZYD_RF_MAXIM_NEW: case ZYD_RF_GCT: rf->init = zyd_gct_init; rf->switch_radio = zyd_gct_switch_radio; rf->set_channel = zyd_gct_set_channel; rf->width = 24; /* 24-bit RF values */ rf->update_pwr = 0; break; case ZYD_RF_MAXIM_NEW2: rf->init = zyd_maxim2_init; rf->switch_radio = zyd_maxim2_switch_radio; rf->set_channel = zyd_maxim2_set_channel; rf->width = 18; /* 18-bit RF values */ break; default: device_printf(sc->sc_dev, "sorry, radio \"%s\" is not supported yet\n", zyd_rf_name(type)); return (EINVAL); } return (0); } static const char * zyd_rf_name(uint8_t type) { static const char * const zyd_rfs[] = { "unknown", "unknown", "UW2451", "UCHIP", "AL2230", "AL7230B", "THETA", "AL2210", "MAXIM_NEW", "GCT", "AL2230S", "RALINK", "INTERSIL", "RFMD", "MAXIM_NEW2", "PHILIPS" }; return zyd_rfs[(type > 15) ? 0 : type]; } static int zyd_hw_init(struct zyd_softc *sc) { int error; const struct zyd_phy_pair *phyp; struct zyd_rf *rf = &sc->sc_rf; uint16_t val; /* specify that the plug and play is finished */ zyd_write32_m(sc, ZYD_MAC_AFTER_PNP, 1); zyd_read16_m(sc, ZYD_FIRMWARE_BASE_ADDR, &sc->sc_fwbase); DPRINTF(sc, ZYD_DEBUG_FW, "firmware base address=0x%04x\n", sc->sc_fwbase); /* retrieve firmware revision number */ zyd_read16_m(sc, sc->sc_fwbase + ZYD_FW_FIRMWARE_REV, &sc->sc_fwrev); zyd_write32_m(sc, ZYD_CR_GPI_EN, 0); zyd_write32_m(sc, ZYD_MAC_CONT_WIN_LIMIT, 0x7f043f); /* set mandatory rates - XXX assumes 802.11b/g */ zyd_write32_m(sc, ZYD_MAC_MAN_RATE, 0x150f); /* disable interrupts */ zyd_write32_m(sc, ZYD_CR_INTERRUPT, 0); if ((error = zyd_read_pod(sc)) != 0) { device_printf(sc->sc_dev, "could not read EEPROM\n"); goto fail; } /* PHY init (resetting) */ error = zyd_lock_phy(sc); if (error != 0) goto fail; phyp = (sc->sc_macrev == ZYD_ZD1211B) ? zyd_def_phyB : zyd_def_phy; for (; phyp->reg != 0; phyp++) zyd_write16_m(sc, phyp->reg, phyp->val); if (sc->sc_macrev == ZYD_ZD1211 && sc->sc_fix_cr157 != 0) { zyd_read16_m(sc, ZYD_EEPROM_PHY_REG, &val); zyd_write32_m(sc, ZYD_CR157, val >> 8); } error = zyd_unlock_phy(sc); if (error != 0) goto fail; /* HMAC init */ zyd_write32_m(sc, ZYD_MAC_ACK_EXT, 0x00000020); zyd_write32_m(sc, ZYD_CR_ADDA_MBIAS_WT, 0x30000808); zyd_write32_m(sc, ZYD_MAC_SNIFFER, 0x00000000); zyd_write32_m(sc, ZYD_MAC_RXFILTER, 0x00000000); zyd_write32_m(sc, ZYD_MAC_GHTBL, 0x00000000); zyd_write32_m(sc, ZYD_MAC_GHTBH, 0x80000000); zyd_write32_m(sc, ZYD_MAC_MISC, 0x000000a4); zyd_write32_m(sc, ZYD_CR_ADDA_PWR_DWN, 0x0000007f); zyd_write32_m(sc, ZYD_MAC_BCNCFG, 0x00f00401); zyd_write32_m(sc, ZYD_MAC_PHY_DELAY2, 0x00000000); zyd_write32_m(sc, ZYD_MAC_ACK_EXT, 0x00000080); zyd_write32_m(sc, ZYD_CR_ADDA_PWR_DWN, 0x00000000); zyd_write32_m(sc, ZYD_MAC_SIFS_ACK_TIME, 0x00000100); zyd_write32_m(sc, ZYD_CR_RX_PE_DELAY, 0x00000070); zyd_write32_m(sc, ZYD_CR_PS_CTRL, 0x10000000); zyd_write32_m(sc, ZYD_MAC_RTSCTSRATE, 0x02030203); zyd_write32_m(sc, ZYD_MAC_AFTER_PNP, 1); zyd_write32_m(sc, ZYD_MAC_BACKOFF_PROTECT, 0x00000114); zyd_write32_m(sc, ZYD_MAC_DIFS_EIFS_SIFS, 0x0a47c032); zyd_write32_m(sc, ZYD_MAC_CAM_MODE, 0x3); if (sc->sc_macrev == ZYD_ZD1211) { zyd_write32_m(sc, ZYD_MAC_RETRY, 0x00000002); zyd_write32_m(sc, ZYD_MAC_RX_THRESHOLD, 0x000c0640); } else { zyd_write32_m(sc, ZYD_MACB_MAX_RETRY, 0x02020202); zyd_write32_m(sc, ZYD_MACB_TXPWR_CTL4, 0x007f003f); zyd_write32_m(sc, ZYD_MACB_TXPWR_CTL3, 0x007f003f); zyd_write32_m(sc, ZYD_MACB_TXPWR_CTL2, 0x003f001f); zyd_write32_m(sc, ZYD_MACB_TXPWR_CTL1, 0x001f000f); zyd_write32_m(sc, ZYD_MACB_AIFS_CTL1, 0x00280028); zyd_write32_m(sc, ZYD_MACB_AIFS_CTL2, 0x008C003C); zyd_write32_m(sc, ZYD_MACB_TXOP, 0x01800824); zyd_write32_m(sc, ZYD_MAC_RX_THRESHOLD, 0x000c0eff); } /* init beacon interval to 100ms */ if ((error = zyd_set_beacon_interval(sc, 100)) != 0) goto fail; if ((error = zyd_rf_attach(sc, sc->sc_rfrev)) != 0) { device_printf(sc->sc_dev, "could not attach RF, rev 0x%x\n", sc->sc_rfrev); goto fail; } /* RF chip init */ error = zyd_lock_phy(sc); if (error != 0) goto fail; error = (*rf->init)(rf); if (error != 0) { device_printf(sc->sc_dev, "radio initialization failed, error %d\n", error); goto fail; } error = zyd_unlock_phy(sc); if (error != 0) goto fail; if ((error = zyd_read_eeprom(sc)) != 0) { device_printf(sc->sc_dev, "could not read EEPROM\n"); goto fail; } fail: return (error); } static int zyd_read_pod(struct zyd_softc *sc) { int error; uint32_t tmp; zyd_read32_m(sc, ZYD_EEPROM_POD, &tmp); sc->sc_rfrev = tmp & 0x0f; sc->sc_ledtype = (tmp >> 4) & 0x01; sc->sc_al2230s = (tmp >> 7) & 0x01; sc->sc_cckgain = (tmp >> 8) & 0x01; sc->sc_fix_cr157 = (tmp >> 13) & 0x01; sc->sc_parev = (tmp >> 16) & 0x0f; sc->sc_bandedge6 = (tmp >> 21) & 0x01; sc->sc_newphy = (tmp >> 31) & 0x01; sc->sc_txled = ((tmp & (1 << 24)) && (tmp & (1 << 29))) ? 0 : 1; fail: return (error); } static int zyd_read_eeprom(struct zyd_softc *sc) { uint16_t val; int error, i; /* read Tx power calibration tables */ for (i = 0; i < 7; i++) { zyd_read16_m(sc, ZYD_EEPROM_PWR_CAL + i, &val); sc->sc_pwrcal[i * 2] = val >> 8; sc->sc_pwrcal[i * 2 + 1] = val & 0xff; zyd_read16_m(sc, ZYD_EEPROM_PWR_INT + i, &val); sc->sc_pwrint[i * 2] = val >> 8; sc->sc_pwrint[i * 2 + 1] = val & 0xff; zyd_read16_m(sc, ZYD_EEPROM_36M_CAL + i, &val); sc->sc_ofdm36_cal[i * 2] = val >> 8; sc->sc_ofdm36_cal[i * 2 + 1] = val & 0xff; zyd_read16_m(sc, ZYD_EEPROM_48M_CAL + i, &val); sc->sc_ofdm48_cal[i * 2] = val >> 8; sc->sc_ofdm48_cal[i * 2 + 1] = val & 0xff; zyd_read16_m(sc, ZYD_EEPROM_54M_CAL + i, &val); sc->sc_ofdm54_cal[i * 2] = val >> 8; sc->sc_ofdm54_cal[i * 2 + 1] = val & 0xff; } fail: return (error); } static int zyd_get_macaddr(struct zyd_softc *sc) { struct usb_device_request req; usb_error_t error; req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = ZYD_READFWDATAREQ; USETW(req.wValue, ZYD_EEPROM_MAC_ADDR_P1); USETW(req.wIndex, 0); USETW(req.wLength, IEEE80211_ADDR_LEN); error = zyd_do_request(sc, &req, sc->sc_bssid); if (error != 0) { device_printf(sc->sc_dev, "could not read EEPROM: %s\n", usbd_errstr(error)); } return (error); } static int zyd_set_macaddr(struct zyd_softc *sc, const uint8_t *addr) { int error; uint32_t tmp; tmp = addr[3] << 24 | addr[2] << 16 | addr[1] << 8 | addr[0]; zyd_write32_m(sc, ZYD_MAC_MACADRL, tmp); tmp = addr[5] << 8 | addr[4]; zyd_write32_m(sc, ZYD_MAC_MACADRH, tmp); fail: return (error); } static int zyd_set_bssid(struct zyd_softc *sc, const uint8_t *addr) { int error; uint32_t tmp; tmp = addr[3] << 24 | addr[2] << 16 | addr[1] << 8 | addr[0]; zyd_write32_m(sc, ZYD_MAC_BSSADRL, tmp); tmp = addr[5] << 8 | addr[4]; zyd_write32_m(sc, ZYD_MAC_BSSADRH, tmp); fail: return (error); } static int zyd_switch_radio(struct zyd_softc *sc, int on) { struct zyd_rf *rf = &sc->sc_rf; int error; error = zyd_lock_phy(sc); if (error != 0) goto fail; error = (*rf->switch_radio)(rf, on); if (error != 0) goto fail; error = zyd_unlock_phy(sc); fail: return (error); } static int zyd_set_led(struct zyd_softc *sc, int which, int on) { int error; uint32_t tmp; zyd_read32_m(sc, ZYD_MAC_TX_PE_CONTROL, &tmp); tmp &= ~which; if (on) tmp |= which; zyd_write32_m(sc, ZYD_MAC_TX_PE_CONTROL, tmp); fail: return (error); } static void zyd_set_multi(struct zyd_softc *sc) { int error; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ifmultiaddr *ifma; uint32_t low, high; uint8_t v; if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) return; low = 0x00000000; high = 0x80000000; if (ic->ic_opmode == IEEE80211_M_MONITOR || (ifp->if_flags & (IFF_ALLMULTI | IFF_PROMISC))) { low = 0xffffffff; high = 0xffffffff; } else { if_maddr_rlock(ifp); TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) { if (ifma->ifma_addr->sa_family != AF_LINK) continue; v = ((uint8_t *)LLADDR((struct sockaddr_dl *) ifma->ifma_addr))[5] >> 2; if (v < 32) low |= 1 << v; else high |= 1 << (v - 32); } if_maddr_runlock(ifp); } /* reprogram multicast global hash table */ zyd_write32_m(sc, ZYD_MAC_GHTBL, low); zyd_write32_m(sc, ZYD_MAC_GHTBH, high); fail: if (error != 0) device_printf(sc->sc_dev, "could not set multicast hash table\n"); } static void zyd_update_mcast(struct ifnet *ifp) { struct zyd_softc *sc = ifp->if_softc; if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) return; ZYD_LOCK(sc); zyd_set_multi(sc); ZYD_UNLOCK(sc); } static int zyd_set_rxfilter(struct zyd_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; uint32_t rxfilter; switch (ic->ic_opmode) { case IEEE80211_M_STA: rxfilter = ZYD_FILTER_BSS; break; case IEEE80211_M_IBSS: case IEEE80211_M_HOSTAP: rxfilter = ZYD_FILTER_HOSTAP; break; case IEEE80211_M_MONITOR: rxfilter = ZYD_FILTER_MONITOR; break; default: /* should not get there */ return (EINVAL); } return zyd_write32(sc, ZYD_MAC_RXFILTER, rxfilter); } static void zyd_set_chan(struct zyd_softc *sc, struct ieee80211_channel *c) { int error; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct zyd_rf *rf = &sc->sc_rf; uint32_t tmp; int chan; chan = ieee80211_chan2ieee(ic, c); if (chan == 0 || chan == IEEE80211_CHAN_ANY) { /* XXX should NEVER happen */ device_printf(sc->sc_dev, "%s: invalid channel %x\n", __func__, chan); return; } error = zyd_lock_phy(sc); if (error != 0) goto fail; error = (*rf->set_channel)(rf, chan); if (error != 0) goto fail; if (rf->update_pwr) { /* update Tx power */ zyd_write16_m(sc, ZYD_CR31, sc->sc_pwrint[chan - 1]); if (sc->sc_macrev == ZYD_ZD1211B) { zyd_write16_m(sc, ZYD_CR67, sc->sc_ofdm36_cal[chan - 1]); zyd_write16_m(sc, ZYD_CR66, sc->sc_ofdm48_cal[chan - 1]); zyd_write16_m(sc, ZYD_CR65, sc->sc_ofdm54_cal[chan - 1]); zyd_write16_m(sc, ZYD_CR68, sc->sc_pwrcal[chan - 1]); zyd_write16_m(sc, ZYD_CR69, 0x28); zyd_write16_m(sc, ZYD_CR69, 0x2a); } } if (sc->sc_cckgain) { /* set CCK baseband gain from EEPROM */ if (zyd_read32(sc, ZYD_EEPROM_PHY_REG, &tmp) == 0) zyd_write16_m(sc, ZYD_CR47, tmp & 0xff); } if (sc->sc_bandedge6 && rf->bandedge6 != NULL) { error = (*rf->bandedge6)(rf, c); if (error != 0) goto fail; } zyd_write32_m(sc, ZYD_CR_CONFIG_PHILIPS, 0); error = zyd_unlock_phy(sc); if (error != 0) goto fail; sc->sc_rxtap.wr_chan_freq = sc->sc_txtap.wt_chan_freq = htole16(c->ic_freq); sc->sc_rxtap.wr_chan_flags = sc->sc_txtap.wt_chan_flags = htole16(c->ic_flags); fail: return; } static int zyd_set_beacon_interval(struct zyd_softc *sc, int bintval) { int error; uint32_t val; zyd_read32_m(sc, ZYD_CR_ATIM_WND_PERIOD, &val); sc->sc_atim_wnd = val; zyd_read32_m(sc, ZYD_CR_PRE_TBTT, &val); sc->sc_pre_tbtt = val; sc->sc_bcn_int = bintval; if (sc->sc_bcn_int <= 5) sc->sc_bcn_int = 5; if (sc->sc_pre_tbtt < 4 || sc->sc_pre_tbtt >= sc->sc_bcn_int) sc->sc_pre_tbtt = sc->sc_bcn_int - 1; if (sc->sc_atim_wnd >= sc->sc_pre_tbtt) sc->sc_atim_wnd = sc->sc_pre_tbtt - 1; zyd_write32_m(sc, ZYD_CR_ATIM_WND_PERIOD, sc->sc_atim_wnd); zyd_write32_m(sc, ZYD_CR_PRE_TBTT, sc->sc_pre_tbtt); zyd_write32_m(sc, ZYD_CR_BCN_INTERVAL, sc->sc_bcn_int); fail: return (error); } static void zyd_rx_data(struct usb_xfer *xfer, int offset, uint16_t len) { struct zyd_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct zyd_plcphdr plcp; struct zyd_rx_stat stat; struct usb_page_cache *pc; struct mbuf *m; int rlen, rssi; if (len < ZYD_MIN_FRAGSZ) { DPRINTF(sc, ZYD_DEBUG_RECV, "%s: frame too short (length=%d)\n", device_get_nameunit(sc->sc_dev), len); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); return; } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, offset, &plcp, sizeof(plcp)); usbd_copy_out(pc, offset + len - sizeof(stat), &stat, sizeof(stat)); if (stat.flags & ZYD_RX_ERROR) { DPRINTF(sc, ZYD_DEBUG_RECV, "%s: RX status indicated error (%x)\n", device_get_nameunit(sc->sc_dev), stat.flags); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); return; } /* compute actual frame length */ rlen = len - sizeof(struct zyd_plcphdr) - sizeof(struct zyd_rx_stat) - IEEE80211_CRC_LEN; /* allocate a mbuf to store the frame */ if (rlen > (int)MCLBYTES) { DPRINTF(sc, ZYD_DEBUG_RECV, "%s: frame too long (length=%d)\n", device_get_nameunit(sc->sc_dev), rlen); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); return; } else if (rlen > (int)MHLEN) m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); else m = m_gethdr(M_NOWAIT, MT_DATA); if (m == NULL) { DPRINTF(sc, ZYD_DEBUG_RECV, "%s: could not allocate rx mbuf\n", device_get_nameunit(sc->sc_dev)); if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); return; } m->m_pkthdr.rcvif = ifp; m->m_pkthdr.len = m->m_len = rlen; usbd_copy_out(pc, offset + sizeof(plcp), mtod(m, uint8_t *), rlen); if (ieee80211_radiotap_active(ic)) { struct zyd_rx_radiotap_header *tap = &sc->sc_rxtap; tap->wr_flags = 0; if (stat.flags & (ZYD_RX_BADCRC16 | ZYD_RX_BADCRC32)) tap->wr_flags |= IEEE80211_RADIOTAP_F_BADFCS; /* XXX toss, no way to express errors */ if (stat.flags & ZYD_RX_DECRYPTERR) tap->wr_flags |= IEEE80211_RADIOTAP_F_BADFCS; tap->wr_rate = ieee80211_plcp2rate(plcp.signal, (stat.flags & ZYD_RX_OFDM) ? IEEE80211_T_OFDM : IEEE80211_T_CCK); tap->wr_antsignal = stat.rssi + -95; tap->wr_antnoise = -95; /* XXX */ } rssi = (stat.rssi > 63) ? 127 : 2 * stat.rssi; sc->sc_rx_data[sc->sc_rx_count].rssi = rssi; sc->sc_rx_data[sc->sc_rx_count].m = m; sc->sc_rx_count++; } static void zyd_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error) { struct zyd_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct ieee80211_node *ni; struct zyd_rx_desc desc; struct mbuf *m; struct usb_page_cache *pc; uint32_t offset; uint8_t rssi; int8_t nf; int i; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); sc->sc_rx_count = 0; switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_out(pc, actlen - sizeof(desc), &desc, sizeof(desc)); offset = 0; if (UGETW(desc.tag) == ZYD_TAG_MULTIFRAME) { DPRINTF(sc, ZYD_DEBUG_RECV, "%s: received multi-frame transfer\n", __func__); for (i = 0; i < ZYD_MAX_RXFRAMECNT; i++) { uint16_t len16 = UGETW(desc.len[i]); if (len16 == 0 || len16 > actlen) break; zyd_rx_data(xfer, offset, len16); /* next frame is aligned on a 32-bit boundary */ len16 = (len16 + 3) & ~3; offset += len16; if (len16 > actlen) break; actlen -= len16; } } else { DPRINTF(sc, ZYD_DEBUG_RECV, "%s: received single-frame transfer\n", __func__); zyd_rx_data(xfer, 0, actlen); } /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer)); usbd_transfer_submit(xfer); /* * At the end of a USB callback it is always safe to unlock * the private mutex of a device! That is why we do the * "ieee80211_input" here, and not some lines up! */ ZYD_UNLOCK(sc); for (i = 0; i < sc->sc_rx_count; i++) { rssi = sc->sc_rx_data[i].rssi; m = sc->sc_rx_data[i].m; sc->sc_rx_data[i].m = NULL; nf = -95; /* XXX */ ni = ieee80211_find_rxnode(ic, mtod(m, struct ieee80211_frame_min *)); if (ni != NULL) { (void)ieee80211_input(ni, m, rssi, nf); ieee80211_free_node(ni); } else (void)ieee80211_input_all(ic, m, rssi, nf); } if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0 && !IFQ_IS_EMPTY(&ifp->if_snd)) zyd_start(ifp); ZYD_LOCK(sc); break; default: /* Error */ DPRINTF(sc, ZYD_DEBUG_ANY, "frame error: %s\n", usbd_errstr(error)); if (error != USB_ERR_CANCELLED) { /* try to clear stall first */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static uint8_t zyd_plcp_signal(struct zyd_softc *sc, int rate) { switch (rate) { /* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */ case 12: return (0xb); case 18: return (0xf); case 24: return (0xa); case 36: return (0xe); case 48: return (0x9); case 72: return (0xd); case 96: return (0x8); case 108: return (0xc); /* CCK rates (NB: not IEEE std, device-specific) */ case 2: return (0x0); case 4: return (0x1); case 11: return (0x2); case 22: return (0x3); } device_printf(sc->sc_dev, "unsupported rate %d\n", rate); return (0x0); } static void zyd_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error) { struct zyd_softc *sc = usbd_xfer_softc(xfer); struct ifnet *ifp = sc->sc_ifp; struct ieee80211vap *vap; struct zyd_tx_data *data; struct mbuf *m; struct usb_page_cache *pc; int actlen; usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL); switch (USB_GET_STATE(xfer)) { case USB_ST_TRANSFERRED: DPRINTF(sc, ZYD_DEBUG_ANY, "transfer complete, %u bytes\n", actlen); /* free resources */ data = usbd_xfer_get_priv(xfer); zyd_tx_free(data, 0); usbd_xfer_set_priv(xfer, NULL); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; /* FALLTHROUGH */ case USB_ST_SETUP: tr_setup: data = STAILQ_FIRST(&sc->tx_q); if (data) { STAILQ_REMOVE_HEAD(&sc->tx_q, next); m = data->m; if (m->m_pkthdr.len > (int)ZYD_MAX_TXBUFSZ) { DPRINTF(sc, ZYD_DEBUG_ANY, "data overflow, %u bytes\n", m->m_pkthdr.len); m->m_pkthdr.len = ZYD_MAX_TXBUFSZ; } pc = usbd_xfer_get_frame(xfer, 0); usbd_copy_in(pc, 0, &data->desc, ZYD_TX_DESC_SIZE); usbd_m_copy_in(pc, ZYD_TX_DESC_SIZE, m, 0, m->m_pkthdr.len); vap = data->ni->ni_vap; if (ieee80211_radiotap_active_vap(vap)) { struct zyd_tx_radiotap_header *tap = &sc->sc_txtap; tap->wt_flags = 0; tap->wt_rate = data->rate; ieee80211_radiotap_tx(vap, m); } usbd_xfer_set_frame_len(xfer, 0, ZYD_TX_DESC_SIZE + m->m_pkthdr.len); usbd_xfer_set_priv(xfer, data); usbd_transfer_submit(xfer); } ZYD_UNLOCK(sc); zyd_start(ifp); ZYD_LOCK(sc); break; default: /* Error */ DPRINTF(sc, ZYD_DEBUG_ANY, "transfer error, %s\n", usbd_errstr(error)); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); data = usbd_xfer_get_priv(xfer); usbd_xfer_set_priv(xfer, NULL); if (data != NULL) zyd_tx_free(data, error); if (error != USB_ERR_CANCELLED) { if (error == USB_ERR_TIMEOUT) device_printf(sc->sc_dev, "device timeout\n"); /* * Try to clear stall first, also if other * errors occur, hence clearing stall * introduces a 50 ms delay: */ usbd_xfer_set_stall(xfer); goto tr_setup; } break; } } static int zyd_tx_start(struct zyd_softc *sc, struct mbuf *m0, struct ieee80211_node *ni) { struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = ni->ni_ic; struct zyd_tx_desc *desc; struct zyd_tx_data *data; struct ieee80211_frame *wh; const struct ieee80211_txparam *tp; struct ieee80211_key *k; int rate, totlen; static const uint8_t ratediv[] = ZYD_TX_RATEDIV; uint8_t phy; uint16_t pktlen; uint32_t bits; wh = mtod(m0, struct ieee80211_frame *); data = STAILQ_FIRST(&sc->tx_free); STAILQ_REMOVE_HEAD(&sc->tx_free, next); sc->tx_nfree--; if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_MGT || (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL) { tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)]; rate = tp->mgmtrate; } else { tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)]; /* for data frames */ if (IEEE80211_IS_MULTICAST(wh->i_addr1)) rate = tp->mcastrate; else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) rate = tp->ucastrate; else { (void) ieee80211_ratectl_rate(ni, NULL, 0); rate = ni->ni_txrate; } } if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) { k = ieee80211_crypto_encap(ni, m0); if (k == NULL) { m_freem(m0); return (ENOBUFS); } /* packet header may have moved, reset our local pointer */ wh = mtod(m0, struct ieee80211_frame *); } data->ni = ni; data->m = m0; data->rate = rate; /* fill Tx descriptor */ desc = &data->desc; phy = zyd_plcp_signal(sc, rate); desc->phy = phy; if (ZYD_RATE_IS_OFDM(rate)) { desc->phy |= ZYD_TX_PHY_OFDM; if (IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan)) desc->phy |= ZYD_TX_PHY_5GHZ; } else if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE)) desc->phy |= ZYD_TX_PHY_SHPREAMBLE; totlen = m0->m_pkthdr.len + IEEE80211_CRC_LEN; desc->len = htole16(totlen); desc->flags = ZYD_TX_FLAG_BACKOFF; if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) { /* multicast frames are not sent at OFDM rates in 802.11b/g */ if (totlen > vap->iv_rtsthreshold) { desc->flags |= ZYD_TX_FLAG_RTS; } else if (ZYD_RATE_IS_OFDM(rate) && (ic->ic_flags & IEEE80211_F_USEPROT)) { if (ic->ic_protmode == IEEE80211_PROT_CTSONLY) desc->flags |= ZYD_TX_FLAG_CTS_TO_SELF; else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS) desc->flags |= ZYD_TX_FLAG_RTS; } } else desc->flags |= ZYD_TX_FLAG_MULTICAST; if ((wh->i_fc[0] & (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) == (IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_PS_POLL)) desc->flags |= ZYD_TX_FLAG_TYPE(ZYD_TX_TYPE_PS_POLL); /* actual transmit length (XXX why +10?) */ pktlen = ZYD_TX_DESC_SIZE + 10; if (sc->sc_macrev == ZYD_ZD1211) pktlen += totlen; desc->pktlen = htole16(pktlen); bits = (rate == 11) ? (totlen * 16) + 10 : ((rate == 22) ? (totlen * 8) + 10 : (totlen * 8)); desc->plcp_length = htole16(bits / ratediv[phy]); desc->plcp_service = 0; if (rate == 22 && (bits % 11) > 0 && (bits % 11) <= 3) desc->plcp_service |= ZYD_PLCP_LENGEXT; desc->nextlen = 0; if (ieee80211_radiotap_active_vap(vap)) { struct zyd_tx_radiotap_header *tap = &sc->sc_txtap; tap->wt_flags = 0; tap->wt_rate = rate; ieee80211_radiotap_tx(vap, m0); } DPRINTF(sc, ZYD_DEBUG_XMIT, "%s: sending data frame len=%zu rate=%u\n", device_get_nameunit(sc->sc_dev), (size_t)m0->m_pkthdr.len, rate); STAILQ_INSERT_TAIL(&sc->tx_q, data, next); usbd_transfer_start(sc->sc_xfer[ZYD_BULK_WR]); return (0); } static void zyd_start(struct ifnet *ifp) { struct zyd_softc *sc = ifp->if_softc; struct ieee80211_node *ni; struct mbuf *m; ZYD_LOCK(sc); for (;;) { IFQ_DRV_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; if (sc->tx_nfree == 0) { IFQ_DRV_PREPEND(&ifp->if_snd, m); ifp->if_drv_flags |= IFF_DRV_OACTIVE; break; } ni = (struct ieee80211_node *)m->m_pkthdr.rcvif; if (zyd_tx_start(sc, m, ni) != 0) { ieee80211_free_node(ni); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); break; } } ZYD_UNLOCK(sc); } static int zyd_raw_xmit(struct ieee80211_node *ni, struct mbuf *m, const struct ieee80211_bpf_params *params) { struct ieee80211com *ic = ni->ni_ic; struct ifnet *ifp = ic->ic_ifp; struct zyd_softc *sc = ifp->if_softc; ZYD_LOCK(sc); /* prevent management frames from being sent if we're not ready */ if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) { ZYD_UNLOCK(sc); m_freem(m); ieee80211_free_node(ni); return (ENETDOWN); } if (sc->tx_nfree == 0) { ifp->if_drv_flags |= IFF_DRV_OACTIVE; ZYD_UNLOCK(sc); m_freem(m); ieee80211_free_node(ni); return (ENOBUFS); /* XXX */ } /* * Legacy path; interpret frame contents to decide * precisely how to send the frame. * XXX raw path */ if (zyd_tx_start(sc, m, ni) != 0) { ZYD_UNLOCK(sc); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); ieee80211_free_node(ni); return (EIO); } ZYD_UNLOCK(sc); return (0); } static int zyd_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data) { struct zyd_softc *sc = ifp->if_softc; struct ieee80211com *ic = ifp->if_l2com; struct ifreq *ifr = (struct ifreq *) data; int error; int startall = 0; ZYD_LOCK(sc); error = (sc->sc_flags & ZYD_FLAG_DETACHED) ? ENXIO : 0; ZYD_UNLOCK(sc); if (error) return (error); switch (cmd) { case SIOCSIFFLAGS: ZYD_LOCK(sc); if (ifp->if_flags & IFF_UP) { if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) { zyd_init_locked(sc); startall = 1; } else zyd_set_multi(sc); } else { if (ifp->if_drv_flags & IFF_DRV_RUNNING) zyd_stop(sc); } ZYD_UNLOCK(sc); if (startall) ieee80211_start_all(ic); break; case SIOCGIFMEDIA: error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd); break; case SIOCGIFADDR: error = ether_ioctl(ifp, cmd, data); break; default: error = EINVAL; break; } return (error); } static void zyd_init_locked(struct zyd_softc *sc) { struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; struct usb_config_descriptor *cd; int error; uint32_t val; ZYD_LOCK_ASSERT(sc, MA_OWNED); if (!(sc->sc_flags & ZYD_FLAG_INITONCE)) { error = zyd_loadfirmware(sc); if (error != 0) { device_printf(sc->sc_dev, "could not load firmware (error=%d)\n", error); goto fail; } /* reset device */ cd = usbd_get_config_descriptor(sc->sc_udev); error = usbd_req_set_config(sc->sc_udev, &sc->sc_mtx, cd->bConfigurationValue); if (error) device_printf(sc->sc_dev, "reset failed, continuing\n"); error = zyd_hw_init(sc); if (error) { device_printf(sc->sc_dev, "hardware initialization failed\n"); goto fail; } device_printf(sc->sc_dev, "HMAC ZD1211%s, FW %02x.%02x, RF %s S%x, PA%x LED %x " "BE%x NP%x Gain%x F%x\n", (sc->sc_macrev == ZYD_ZD1211) ? "": "B", sc->sc_fwrev >> 8, sc->sc_fwrev & 0xff, zyd_rf_name(sc->sc_rfrev), sc->sc_al2230s, sc->sc_parev, sc->sc_ledtype, sc->sc_bandedge6, sc->sc_newphy, sc->sc_cckgain, sc->sc_fix_cr157); /* read regulatory domain (currently unused) */ zyd_read32_m(sc, ZYD_EEPROM_SUBID, &val); sc->sc_regdomain = val >> 16; DPRINTF(sc, ZYD_DEBUG_INIT, "regulatory domain %x\n", sc->sc_regdomain); /* we'll do software WEP decryption for now */ DPRINTF(sc, ZYD_DEBUG_INIT, "%s: setting encryption type\n", __func__); zyd_write32_m(sc, ZYD_MAC_ENCRYPTION_TYPE, ZYD_ENC_SNIFFER); sc->sc_flags |= ZYD_FLAG_INITONCE; } if (ifp->if_drv_flags & IFF_DRV_RUNNING) zyd_stop(sc); DPRINTF(sc, ZYD_DEBUG_INIT, "setting MAC address to %6D\n", IF_LLADDR(ifp), ":"); error = zyd_set_macaddr(sc, IF_LLADDR(ifp)); if (error != 0) return; /* set basic rates */ if (ic->ic_curmode == IEEE80211_MODE_11B) zyd_write32_m(sc, ZYD_MAC_BAS_RATE, 0x0003); else if (ic->ic_curmode == IEEE80211_MODE_11A) zyd_write32_m(sc, ZYD_MAC_BAS_RATE, 0x1500); else /* assumes 802.11b/g */ zyd_write32_m(sc, ZYD_MAC_BAS_RATE, 0xff0f); /* promiscuous mode */ zyd_write32_m(sc, ZYD_MAC_SNIFFER, 0); /* multicast setup */ zyd_set_multi(sc); /* set RX filter */ error = zyd_set_rxfilter(sc); if (error != 0) goto fail; /* switch radio transmitter ON */ error = zyd_switch_radio(sc, 1); if (error != 0) goto fail; /* set default BSS channel */ zyd_set_chan(sc, ic->ic_curchan); /* * Allocate Tx and Rx xfer queues. */ zyd_setup_tx_list(sc); /* enable interrupts */ zyd_write32_m(sc, ZYD_CR_INTERRUPT, ZYD_HWINT_MASK); ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; ifp->if_drv_flags |= IFF_DRV_RUNNING; usbd_xfer_set_stall(sc->sc_xfer[ZYD_BULK_WR]); usbd_transfer_start(sc->sc_xfer[ZYD_BULK_RD]); usbd_transfer_start(sc->sc_xfer[ZYD_INTR_RD]); return; fail: zyd_stop(sc); return; } static void zyd_init(void *priv) { struct zyd_softc *sc = priv; struct ifnet *ifp = sc->sc_ifp; struct ieee80211com *ic = ifp->if_l2com; ZYD_LOCK(sc); zyd_init_locked(sc); ZYD_UNLOCK(sc); if (ifp->if_drv_flags & IFF_DRV_RUNNING) ieee80211_start_all(ic); /* start all vap's */ } static void zyd_stop(struct zyd_softc *sc) { struct ifnet *ifp = sc->sc_ifp; int error; ZYD_LOCK_ASSERT(sc, MA_OWNED); ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); /* * Drain all the transfers, if not already drained: */ ZYD_UNLOCK(sc); usbd_transfer_drain(sc->sc_xfer[ZYD_BULK_WR]); usbd_transfer_drain(sc->sc_xfer[ZYD_BULK_RD]); ZYD_LOCK(sc); zyd_unsetup_tx_list(sc); /* Stop now if the device was never set up */ if (!(sc->sc_flags & ZYD_FLAG_INITONCE)) return; /* switch radio transmitter OFF */ error = zyd_switch_radio(sc, 0); if (error != 0) goto fail; /* disable Rx */ zyd_write32_m(sc, ZYD_MAC_RXFILTER, 0); /* disable interrupts */ zyd_write32_m(sc, ZYD_CR_INTERRUPT, 0); fail: return; } static int zyd_loadfirmware(struct zyd_softc *sc) { struct usb_device_request req; size_t size; u_char *fw; uint8_t stat; uint16_t addr; if (sc->sc_flags & ZYD_FLAG_FWLOADED) return (0); if (sc->sc_macrev == ZYD_ZD1211) { fw = (u_char *)zd1211_firmware; size = sizeof(zd1211_firmware); } else { fw = (u_char *)zd1211b_firmware; size = sizeof(zd1211b_firmware); } req.bmRequestType = UT_WRITE_VENDOR_DEVICE; req.bRequest = ZYD_DOWNLOADREQ; USETW(req.wIndex, 0); addr = ZYD_FIRMWARE_START_ADDR; while (size > 0) { /* * When the transfer size is 4096 bytes, it is not * likely to be able to transfer it. * The cause is port or machine or chip? */ const int mlen = min(size, 64); DPRINTF(sc, ZYD_DEBUG_FW, "loading firmware block: len=%d, addr=0x%x\n", mlen, addr); USETW(req.wValue, addr); USETW(req.wLength, mlen); if (zyd_do_request(sc, &req, fw) != 0) return (EIO); addr += mlen / 2; fw += mlen; size -= mlen; } /* check whether the upload succeeded */ req.bmRequestType = UT_READ_VENDOR_DEVICE; req.bRequest = ZYD_DOWNLOADSTS; USETW(req.wValue, 0); USETW(req.wIndex, 0); USETW(req.wLength, sizeof(stat)); if (zyd_do_request(sc, &req, &stat) != 0) return (EIO); sc->sc_flags |= ZYD_FLAG_FWLOADED; return (stat & 0x80) ? (EIO) : (0); } static void zyd_scan_start(struct ieee80211com *ic) { struct ifnet *ifp = ic->ic_ifp; struct zyd_softc *sc = ifp->if_softc; ZYD_LOCK(sc); /* want broadcast address while scanning */ zyd_set_bssid(sc, ifp->if_broadcastaddr); ZYD_UNLOCK(sc); } static void zyd_scan_end(struct ieee80211com *ic) { struct zyd_softc *sc = ic->ic_ifp->if_softc; ZYD_LOCK(sc); /* restore previous bssid */ zyd_set_bssid(sc, sc->sc_bssid); ZYD_UNLOCK(sc); } static void zyd_set_channel(struct ieee80211com *ic) { struct zyd_softc *sc = ic->ic_ifp->if_softc; ZYD_LOCK(sc); zyd_set_chan(sc, ic->ic_curchan); ZYD_UNLOCK(sc); } static device_method_t zyd_methods[] = { /* Device interface */ DEVMETHOD(device_probe, zyd_match), DEVMETHOD(device_attach, zyd_attach), DEVMETHOD(device_detach, zyd_detach), DEVMETHOD_END }; static driver_t zyd_driver = { .name = "zyd", .methods = zyd_methods, .size = sizeof(struct zyd_softc) }; static devclass_t zyd_devclass; DRIVER_MODULE(zyd, uhub, zyd_driver, zyd_devclass, NULL, 0); MODULE_DEPEND(zyd, usb, 1, 1, 1); MODULE_DEPEND(zyd, wlan, 1, 1, 1); MODULE_VERSION(zyd, 1);