iPXE
net80211.c
Go to the documentation of this file.
00001 /*
00002  * The iPXE 802.11 MAC layer.
00003  *
00004  * Copyright (c) 2009 Joshua Oreman <oremanj@rwcr.net>.
00005  *
00006  * This program is free software; you can redistribute it and/or
00007  * modify it under the terms of the GNU General Public License as
00008  * published by the Free Software Foundation; either version 2 of the
00009  * License, or any later version.
00010  *
00011  * This program is distributed in the hope that it will be useful, but
00012  * WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014  * General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU General Public License
00017  * along with this program; if not, write to the Free Software
00018  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
00019  * 02110-1301, USA.
00020  */
00021 
00022 FILE_LICENCE ( GPL2_OR_LATER );
00023 
00024 #include <string.h>
00025 #include <byteswap.h>
00026 #include <stdlib.h>
00027 #include <unistd.h>
00028 #include <errno.h>
00029 #include <ipxe/settings.h>
00030 #include <ipxe/if_arp.h>
00031 #include <ipxe/ethernet.h>
00032 #include <ipxe/ieee80211.h>
00033 #include <ipxe/netdevice.h>
00034 #include <ipxe/net80211.h>
00035 #include <ipxe/sec80211.h>
00036 #include <ipxe/timer.h>
00037 #include <ipxe/nap.h>
00038 #include <ipxe/errortab.h>
00039 #include <ipxe/net80211_err.h>
00040 
00041 /** @file
00042  *
00043  * 802.11 device management
00044  */
00045 
00046 /** List of 802.11 devices */
00047 static struct list_head net80211_devices = LIST_HEAD_INIT ( net80211_devices );
00048 
00049 /** Set of device operations that does nothing */
00050 static struct net80211_device_operations net80211_null_ops;
00051 
00052 /** Information associated with a received management packet
00053  *
00054  * This is used to keep beacon signal strengths in a parallel queue to
00055  * the beacons themselves.
00056  */
00057 struct net80211_rx_info {
00058         int signal;
00059         struct list_head list;
00060 };
00061 
00062 /** Context for a probe operation */
00063 struct net80211_probe_ctx {
00064         /** 802.11 device to probe on */
00065         struct net80211_device *dev;
00066 
00067         /** Value of keep_mgmt before probe was started */
00068         int old_keep_mgmt;
00069 
00070         /** If scanning actively, pointer to probe packet to send */
00071         struct io_buffer *probe;
00072 
00073         /** If non-"", the ESSID to limit ourselves to */
00074         const char *essid;
00075 
00076         /** Time probe was started */
00077         u32 ticks_start;
00078 
00079         /** Time last useful beacon was received */
00080         u32 ticks_beacon;
00081 
00082         /** Time channel was last changed */
00083         u32 ticks_channel;
00084 
00085         /** Time to stay on each channel */
00086         u32 hop_time;
00087 
00088         /** Channels to hop by when changing channel */
00089         int hop_step;
00090 
00091         /** List of best beacons for each network found so far */
00092         struct list_head *beacons;
00093 };
00094 
00095 /** Context for the association task */
00096 struct net80211_assoc_ctx {
00097         /** Next authentication method to try using */
00098         int method;
00099 
00100         /** Time (in ticks) of the last sent association-related packet */
00101         int last_packet;
00102 
00103         /** Number of times we have tried sending it */
00104         int times_tried;
00105 };
00106 
00107 /**
00108  * Detect secure 802.11 network when security support is not available
00109  *
00110  * @return -ENOTSUP, always.
00111  */
00112 __weak int sec80211_detect ( struct io_buffer *iob __unused,
00113                              enum net80211_security_proto *secprot __unused,
00114                              enum net80211_crypto_alg *crypt __unused ) {
00115         return -ENOTSUP;
00116 }
00117 
00118 /**
00119  * @defgroup net80211_netdev Network device interface functions
00120  * @{
00121  */
00122 static int net80211_netdev_open ( struct net_device *netdev );
00123 static void net80211_netdev_close ( struct net_device *netdev );
00124 static int net80211_netdev_transmit ( struct net_device *netdev,
00125                                       struct io_buffer *iobuf );
00126 static void net80211_netdev_poll ( struct net_device *netdev );
00127 static void net80211_netdev_irq ( struct net_device *netdev, int enable );
00128 /** @} */
00129 
00130 /**
00131  * @defgroup net80211_linklayer 802.11 link-layer protocol functions
00132  * @{
00133  */
00134 static int net80211_ll_push ( struct net_device *netdev,
00135                               struct io_buffer *iobuf, const void *ll_dest,
00136                               const void *ll_source, uint16_t net_proto );
00137 static int net80211_ll_pull ( struct net_device *netdev,
00138                               struct io_buffer *iobuf, const void **ll_dest,
00139                               const void **ll_source, uint16_t * net_proto,
00140                               unsigned int *flags );
00141 /** @} */
00142 
00143 /**
00144  * @defgroup net80211_help 802.11 helper functions
00145  * @{
00146  */
00147 static void net80211_add_channels ( struct net80211_device *dev, int start,
00148                                     int len, int txpower );
00149 static void net80211_filter_hw_channels ( struct net80211_device *dev );
00150 static void net80211_set_rtscts_rate ( struct net80211_device *dev );
00151 static int net80211_process_capab ( struct net80211_device *dev,
00152                                     u16 capab );
00153 static int net80211_process_ie ( struct net80211_device *dev,
00154                                  union ieee80211_ie *ie, void *ie_end );
00155 static union ieee80211_ie *
00156 net80211_marshal_request_info ( struct net80211_device *dev,
00157                                 union ieee80211_ie *ie );
00158 /** @} */
00159 
00160 /**
00161  * @defgroup net80211_assoc_ll 802.11 association handling functions
00162  * @{
00163  */
00164 static void net80211_step_associate ( struct net80211_device *dev );
00165 static void net80211_handle_auth ( struct net80211_device *dev,
00166                                    struct io_buffer *iob );
00167 static void net80211_handle_assoc_reply ( struct net80211_device *dev,
00168                                           struct io_buffer *iob );
00169 static int net80211_send_disassoc ( struct net80211_device *dev, int reason,
00170                                     int deauth );
00171 static void net80211_handle_mgmt ( struct net80211_device *dev,
00172                                    struct io_buffer *iob, int signal );
00173 /** @} */
00174 
00175 /**
00176  * @defgroup net80211_frag 802.11 fragment handling functions
00177  * @{
00178  */
00179 static void net80211_free_frags ( struct net80211_device *dev, int fcid );
00180 static struct io_buffer *net80211_accum_frags ( struct net80211_device *dev,
00181                                                 int fcid, int nfrags, int size );
00182 static void net80211_rx_frag ( struct net80211_device *dev,
00183                                struct io_buffer *iob, int signal );
00184 /** @} */
00185 
00186 /**
00187  * @defgroup net80211_settings 802.11 settings handlers
00188  * @{
00189  */
00190 static int net80211_check_settings_update ( void );
00191 
00192 /** 802.11 settings applicator
00193  *
00194  * When the SSID is changed, this will cause any open devices to
00195  * re-associate; when the encryption key is changed, we similarly
00196  * update their state.
00197  */
00198 struct settings_applicator net80211_applicator __settings_applicator = {
00199         .apply = net80211_check_settings_update,
00200 };
00201 
00202 /** The network name to associate with
00203  *
00204  * If this is blank, we scan for all networks and use the one with the
00205  * greatest signal strength.
00206  */
00207 const struct setting net80211_ssid_setting __setting ( SETTING_NETDEV_EXTRA,
00208                                                        ssid ) = {
00209         .name = "ssid",
00210         .description = "Wireless SSID",
00211         .type = &setting_type_string,
00212 };
00213 
00214 /** Whether to use active scanning
00215  *
00216  * In order to associate with a hidden SSID, it's necessary to use an
00217  * active scan (send probe packets). If this setting is nonzero, an
00218  * active scan on the 2.4GHz band will be used to associate.
00219  */
00220 const struct setting net80211_active_setting __setting ( SETTING_NETDEV_EXTRA,
00221                                                          active-scan ) = {
00222         .name = "active-scan",
00223         .description = "Actively scan for wireless networks",
00224         .type = &setting_type_int8,
00225 };
00226 
00227 /** The cryptographic key to use
00228  *
00229  * For hex WEP keys, as is common, this must be entered using the
00230  * normal iPXE method for entering hex settings; an ASCII string of
00231  * hex characters will not behave as expected.
00232  */
00233 const struct setting net80211_key_setting __setting ( SETTING_NETDEV_EXTRA,
00234                                                       key ) = {
00235         .name = "key",
00236         .description = "Wireless encryption key",
00237         .type = &setting_type_string,
00238 };
00239 
00240 /** @} */
00241 
00242 
00243 /* ---------- net_device wrapper ---------- */
00244 
00245 /**
00246  * Open 802.11 device and start association
00247  *
00248  * @v netdev    Wrapping network device
00249  * @ret rc      Return status code
00250  *
00251  * This sets up a default conservative set of channels for probing,
00252  * and starts the auto-association task unless the @c
00253  * NET80211_NO_ASSOC flag is set in the wrapped 802.11 device's @c
00254  * state field.
00255  */
00256 static int net80211_netdev_open ( struct net_device *netdev )
00257 {
00258         struct net80211_device *dev = netdev->priv;
00259         int rc = 0;
00260 
00261         if ( dev->op == &net80211_null_ops )
00262                 return -EFAULT;
00263 
00264         if ( dev->op->open )
00265                 rc = dev->op->open ( dev );
00266 
00267         if ( rc < 0 )
00268                 return rc;
00269 
00270         if ( ! ( dev->state & NET80211_NO_ASSOC ) )
00271                 net80211_autoassociate ( dev );
00272 
00273         return 0;
00274 }
00275 
00276 /**
00277  * Close 802.11 device
00278  *
00279  * @v netdev    Wrapping network device.
00280  *
00281  * If the association task is running, this will stop it.
00282  */
00283 static void net80211_netdev_close ( struct net_device *netdev )
00284 {
00285         struct net80211_device *dev = netdev->priv;
00286 
00287         if ( dev->state & NET80211_WORKING )
00288                 process_del ( &dev->proc_assoc );
00289 
00290         /* Send disassociation frame to AP, to be polite */
00291         if ( dev->state & NET80211_ASSOCIATED )
00292                 net80211_send_disassoc ( dev, IEEE80211_REASON_LEAVING, 0 );
00293 
00294         if ( dev->handshaker && dev->handshaker->stop &&
00295              dev->handshaker->started )
00296                 dev->handshaker->stop ( dev );
00297 
00298         free ( dev->crypto );
00299         free ( dev->handshaker );
00300         dev->crypto = NULL;
00301         dev->handshaker = NULL;
00302 
00303         netdev_link_down ( netdev );
00304         dev->state = 0;
00305 
00306         if ( dev->op->close )
00307                 dev->op->close ( dev );
00308 }
00309 
00310 /**
00311  * Transmit packet on 802.11 device
00312  *
00313  * @v netdev    Wrapping network device
00314  * @v iobuf     I/O buffer
00315  * @ret rc      Return status code
00316  *
00317  * If encryption is enabled for the currently associated network, the
00318  * packet will be encrypted prior to transmission.
00319  */
00320 static int net80211_netdev_transmit ( struct net_device *netdev,
00321                                       struct io_buffer *iobuf )
00322 {
00323         struct net80211_device *dev = netdev->priv;
00324         struct ieee80211_frame *hdr = iobuf->data;
00325         int rc = -ENOSYS;
00326 
00327         if ( dev->crypto && ! ( hdr->fc & IEEE80211_FC_PROTECTED ) &&
00328              ( ( hdr->fc & IEEE80211_FC_TYPE ) == IEEE80211_TYPE_DATA ) ) {
00329                 struct io_buffer *niob = dev->crypto->encrypt ( dev->crypto,
00330                                                                 iobuf );
00331                 if ( ! niob )
00332                         return -ENOMEM; /* only reason encryption could fail */
00333 
00334                 /* Free the non-encrypted iob */
00335                 netdev_tx_complete ( netdev, iobuf );
00336 
00337                 /* Transmit the encrypted iob; the Protected flag is
00338                    set, so we won't recurse into here again */
00339                 netdev_tx ( netdev, niob );
00340 
00341                 /* Don't transmit the freed packet */
00342                 return 0;
00343         }
00344 
00345         if ( dev->op->transmit )
00346                 rc = dev->op->transmit ( dev, iobuf );
00347 
00348         return rc;
00349 }
00350 
00351 /**
00352  * Poll 802.11 device for received packets and completed transmissions
00353  *
00354  * @v netdev    Wrapping network device
00355  */
00356 static void net80211_netdev_poll ( struct net_device *netdev )
00357 {
00358         struct net80211_device *dev = netdev->priv;
00359 
00360         if ( dev->op->poll )
00361                 dev->op->poll ( dev );
00362 }
00363 
00364 /**
00365  * Enable or disable interrupts for 802.11 device
00366  *
00367  * @v netdev    Wrapping network device
00368  * @v enable    Whether to enable interrupts
00369  */
00370 static void net80211_netdev_irq ( struct net_device *netdev, int enable )
00371 {
00372         struct net80211_device *dev = netdev->priv;
00373 
00374         if ( dev->op->irq )
00375                 dev->op->irq ( dev, enable );
00376 }
00377 
00378 /** Network device operations for a wrapped 802.11 device */
00379 static struct net_device_operations net80211_netdev_ops = {
00380         .open = net80211_netdev_open,
00381         .close = net80211_netdev_close,
00382         .transmit = net80211_netdev_transmit,
00383         .poll = net80211_netdev_poll,
00384         .irq = net80211_netdev_irq,
00385 };
00386 
00387 
00388 /* ---------- 802.11 link-layer protocol ---------- */
00389 
00390 /**
00391  * Determine whether a transmission rate uses ERP/OFDM
00392  *
00393  * @v rate      Rate in 100 kbps units
00394  * @ret is_erp  TRUE if the rate is an ERP/OFDM rate
00395  *
00396  * 802.11b supports rates of 1.0, 2.0, 5.5, and 11.0 Mbps; any other
00397  * rate than these on the 2.4GHz spectrum is an ERP (802.11g) rate.
00398  */
00399 static inline int net80211_rate_is_erp ( u16 rate )
00400 {
00401         if ( rate == 10 || rate == 20 || rate == 55 || rate == 110 )
00402                 return 0;
00403         return 1;
00404 }
00405 
00406 
00407 /**
00408  * Calculate one frame's contribution to 802.11 duration field
00409  *
00410  * @v dev       802.11 device
00411  * @v bytes     Amount of data to calculate duration for
00412  * @ret dur     Duration field in microseconds
00413  *
00414  * To avoid multiple stations attempting to transmit at once, 802.11
00415  * provides that every packet shall include a duration field
00416  * specifying a length of time for which the wireless medium will be
00417  * reserved after it is transmitted. The duration is measured in
00418  * microseconds and is calculated with respect to the current
00419  * physical-layer parameters of the 802.11 device.
00420  *
00421  * For an unfragmented data or management frame, or the last fragment
00422  * of a fragmented frame, the duration captures only the 10 data bytes
00423  * of one ACK; call once with bytes = 10.
00424  *
00425  * For a fragment of a data or management rame that will be followed
00426  * by more fragments, the duration captures an ACK, the following
00427  * fragment, and its ACK; add the results of three calls, two with
00428  * bytes = 10 and one with bytes set to the next fragment's size.
00429  *
00430  * For an RTS control frame, the duration captures the responding CTS,
00431  * the frame being sent, and its ACK; add the results of three calls,
00432  * two with bytes = 10 and one with bytes set to the next frame's size
00433  * (assuming unfragmented).
00434  *
00435  * For a CTS-to-self control frame, the duration captures the frame
00436  * being protected and its ACK; add the results of two calls, one with
00437  * bytes = 10 and one with bytes set to the next frame's size.
00438  *
00439  * No other frame types are currently supported by iPXE.
00440  */
00441 u16 net80211_duration ( struct net80211_device *dev, int bytes, u16 rate )
00442 {
00443         struct net80211_channel *chan = &dev->channels[dev->channel];
00444         u32 kbps = rate * 100;
00445 
00446         if ( chan->band == NET80211_BAND_5GHZ || net80211_rate_is_erp ( rate ) ) {
00447                 /* OFDM encoding (802.11a/g) */
00448                 int bits_per_symbol = ( kbps * 4 ) / 1000;      /* 4us/symbol */
00449                 int bits = 22 + ( bytes << 3 ); /* 22-bit PLCP */
00450                 int symbols = ( bits + bits_per_symbol - 1 ) / bits_per_symbol;
00451 
00452                 return 16 + 20 + ( symbols * 4 ); /* 16us SIFS, 20us preamble */
00453         } else {
00454                 /* CCK encoding (802.11b) */
00455                 int phy_time = 144 + 48;        /* preamble + PLCP */
00456                 int bits = bytes << 3;
00457                 int data_time = ( bits * 1000 + kbps - 1 ) / kbps;
00458 
00459                 if ( dev->phy_flags & NET80211_PHY_USE_SHORT_PREAMBLE )
00460                         phy_time >>= 1;
00461 
00462                 return 10 + phy_time + data_time; /* 10us SIFS */
00463         }
00464 }
00465 
00466 /**
00467  * Add 802.11 link-layer header
00468  *
00469  * @v netdev            Wrapping network device
00470  * @v iobuf             I/O buffer
00471  * @v ll_dest           Link-layer destination address
00472  * @v ll_source         Link-layer source address
00473  * @v net_proto         Network-layer protocol, in network byte order
00474  * @ret rc              Return status code
00475  *
00476  * This adds both the 802.11 frame header and the 802.2 LLC/SNAP
00477  * header used on data packets.
00478  *
00479  * We also check here for state of the link that would make it invalid
00480  * to send a data packet; every data packet must pass through here,
00481  * and no non-data packet (e.g. management frame) should.
00482  */
00483 static int net80211_ll_push ( struct net_device *netdev,
00484                               struct io_buffer *iobuf, const void *ll_dest,
00485                               const void *ll_source, uint16_t net_proto )
00486 {
00487         struct net80211_device *dev = netdev->priv;
00488         struct ieee80211_frame *hdr = iob_push ( iobuf,
00489                                                  IEEE80211_LLC_HEADER_LEN +
00490                                                  IEEE80211_TYP_FRAME_HEADER_LEN );
00491         struct ieee80211_llc_snap_header *lhdr =
00492                 ( void * ) hdr + IEEE80211_TYP_FRAME_HEADER_LEN;
00493 
00494         /* We can't send data packets if we're not associated. */
00495         if ( ! ( dev->state & NET80211_ASSOCIATED ) ) {
00496                 if ( dev->assoc_rc )
00497                         return dev->assoc_rc;
00498                 return -ENETUNREACH;
00499         }
00500 
00501         hdr->fc = IEEE80211_THIS_VERSION | IEEE80211_TYPE_DATA |
00502             IEEE80211_STYPE_DATA | IEEE80211_FC_TODS;
00503 
00504         /* We don't send fragmented frames, so duration is the time
00505            for an SIFS + 10-byte ACK. */
00506         hdr->duration = net80211_duration ( dev, 10, dev->rates[dev->rate] );
00507 
00508         memcpy ( hdr->addr1, dev->bssid, ETH_ALEN );
00509         memcpy ( hdr->addr2, ll_source, ETH_ALEN );
00510         memcpy ( hdr->addr3, ll_dest, ETH_ALEN );
00511 
00512         hdr->seq = IEEE80211_MAKESEQ ( ++dev->last_tx_seqnr, 0 );
00513 
00514         lhdr->dsap = IEEE80211_LLC_DSAP;
00515         lhdr->ssap = IEEE80211_LLC_SSAP;
00516         lhdr->ctrl = IEEE80211_LLC_CTRL;
00517         memset ( lhdr->oui, 0x00, 3 );
00518         lhdr->ethertype = net_proto;
00519 
00520         return 0;
00521 }
00522 
00523 /**
00524  * Remove 802.11 link-layer header
00525  *
00526  * @v netdev            Wrapping network device
00527  * @v iobuf             I/O buffer
00528  * @ret ll_dest         Link-layer destination address
00529  * @ret ll_source       Link-layer source
00530  * @ret net_proto       Network-layer protocol, in network byte order
00531  * @ret flags           Packet flags
00532  * @ret rc              Return status code
00533  *
00534  * This expects and removes both the 802.11 frame header and the 802.2
00535  * LLC/SNAP header that are used on data packets.
00536  */
00537 static int net80211_ll_pull ( struct net_device *netdev __unused,
00538                               struct io_buffer *iobuf,
00539                               const void **ll_dest, const void **ll_source,
00540                               uint16_t * net_proto, unsigned int *flags )
00541 {
00542         struct ieee80211_frame *hdr = iobuf->data;
00543         struct ieee80211_llc_snap_header *lhdr =
00544                 ( void * ) hdr + IEEE80211_TYP_FRAME_HEADER_LEN;
00545 
00546         /* Bunch of sanity checks */
00547         if ( iob_len ( iobuf ) < IEEE80211_TYP_FRAME_HEADER_LEN +
00548              IEEE80211_LLC_HEADER_LEN ) {
00549                 DBGC ( netdev->priv, "802.11 %p packet too short (%zd bytes)\n",
00550                        netdev->priv, iob_len ( iobuf ) );
00551                 return -EINVAL_PKT_TOO_SHORT;
00552         }
00553 
00554         if ( ( hdr->fc & IEEE80211_FC_VERSION ) != IEEE80211_THIS_VERSION ) {
00555                 DBGC ( netdev->priv, "802.11 %p packet invalid version %04x\n",
00556                        netdev->priv, hdr->fc & IEEE80211_FC_VERSION );
00557                 return -EINVAL_PKT_VERSION;
00558         }
00559 
00560         if ( ( hdr->fc & IEEE80211_FC_TYPE ) != IEEE80211_TYPE_DATA ||
00561              ( hdr->fc & IEEE80211_FC_SUBTYPE ) != IEEE80211_STYPE_DATA ) {
00562                 DBGC ( netdev->priv, "802.11 %p packet not data/data (fc=%04x)\n",
00563                        netdev->priv, hdr->fc );
00564                 return -EINVAL_PKT_NOT_DATA;
00565         }
00566 
00567         if ( ( hdr->fc & ( IEEE80211_FC_TODS | IEEE80211_FC_FROMDS ) ) !=
00568              IEEE80211_FC_FROMDS ) {
00569                 DBGC ( netdev->priv, "802.11 %p packet not from DS (fc=%04x)\n",
00570                        netdev->priv, hdr->fc );
00571                 return -EINVAL_PKT_NOT_FROMDS;
00572         }
00573 
00574         if ( lhdr->dsap != IEEE80211_LLC_DSAP || lhdr->ssap != IEEE80211_LLC_SSAP ||
00575              lhdr->ctrl != IEEE80211_LLC_CTRL || lhdr->oui[0] || lhdr->oui[1] ||
00576              lhdr->oui[2] ) {
00577                 DBGC ( netdev->priv, "802.11 %p LLC header is not plain EtherType "
00578                        "encapsulator: %02x->%02x [%02x] %02x:%02x:%02x %04x\n",
00579                        netdev->priv, lhdr->dsap, lhdr->ssap, lhdr->ctrl,
00580                        lhdr->oui[0], lhdr->oui[1], lhdr->oui[2], lhdr->ethertype );
00581                 return -EINVAL_PKT_LLC_HEADER;
00582         }
00583 
00584         iob_pull ( iobuf, sizeof ( *hdr ) + sizeof ( *lhdr ) );
00585 
00586         *ll_dest = hdr->addr1;
00587         *ll_source = hdr->addr3;
00588         *net_proto = lhdr->ethertype;
00589         *flags = ( ( is_multicast_ether_addr ( hdr->addr1 ) ?
00590                      LL_MULTICAST : 0 ) |
00591                    ( is_broadcast_ether_addr ( hdr->addr1 ) ?
00592                      LL_BROADCAST : 0 ) );
00593         return 0;
00594 }
00595 
00596 /** 802.11 link-layer protocol */
00597 static struct ll_protocol net80211_ll_protocol __ll_protocol = {
00598         .name = "802.11",
00599         .push = net80211_ll_push,
00600         .pull = net80211_ll_pull,
00601         .init_addr = eth_init_addr,
00602         .ntoa = eth_ntoa,
00603         .mc_hash = eth_mc_hash,
00604         .eth_addr = eth_eth_addr,
00605         .eui64 = eth_eui64,
00606         .ll_proto = htons ( ARPHRD_ETHER ),     /* "encapsulated Ethernet" */
00607         .hw_addr_len = ETH_ALEN,
00608         .ll_addr_len = ETH_ALEN,
00609         .ll_header_len = IEEE80211_TYP_FRAME_HEADER_LEN +
00610                                 IEEE80211_LLC_HEADER_LEN,
00611 };
00612 
00613 
00614 /* ---------- 802.11 network management API ---------- */
00615 
00616 /**
00617  * Get 802.11 device from wrapping network device
00618  *
00619  * @v netdev    Wrapping network device
00620  * @ret dev     802.11 device wrapped by network device, or NULL
00621  *
00622  * Returns NULL if the network device does not wrap an 802.11 device.
00623  */
00624 struct net80211_device * net80211_get ( struct net_device *netdev )
00625 {
00626         struct net80211_device *dev;
00627 
00628         list_for_each_entry ( dev, &net80211_devices, list ) {
00629                 if ( netdev->priv == dev )
00630                         return netdev->priv;
00631         }
00632 
00633         return NULL;
00634 }
00635 
00636 /**
00637  * Set state of 802.11 device keeping management frames
00638  *
00639  * @v dev       802.11 device
00640  * @v enable    Whether to keep management frames
00641  * @ret oldenab Whether management frames were enabled before this call
00642  *
00643  * If enable is TRUE, beacon, probe, and action frames will be kept
00644  * and may be retrieved by calling net80211_mgmt_dequeue().
00645  */
00646 int net80211_keep_mgmt ( struct net80211_device *dev, int enable )
00647 {
00648         int oldenab = dev->keep_mgmt;
00649 
00650         dev->keep_mgmt = enable;
00651         return oldenab;
00652 }
00653 
00654 /**
00655  * Get 802.11 management frame
00656  *
00657  * @v dev       802.11 device
00658  * @ret signal  Signal strength of returned management frame
00659  * @ret iob     I/O buffer, or NULL if no management frame is queued
00660  *
00661  * Frames will only be returned by this function if
00662  * net80211_keep_mgmt() has been previously called with enable set to
00663  * TRUE.
00664  *
00665  * The calling function takes ownership of the returned I/O buffer.
00666  */
00667 struct io_buffer * net80211_mgmt_dequeue ( struct net80211_device *dev,
00668                                            int *signal )
00669 {
00670         struct io_buffer *iobuf;
00671         struct net80211_rx_info *rxi;
00672 
00673         list_for_each_entry ( rxi, &dev->mgmt_info_queue, list ) {
00674                 list_del ( &rxi->list );
00675                 if ( signal )
00676                         *signal = rxi->signal;
00677                 free ( rxi );
00678 
00679                 assert ( ! list_empty ( &dev->mgmt_queue ) );
00680                 iobuf = list_first_entry ( &dev->mgmt_queue, struct io_buffer,
00681                                            list );
00682                 list_del ( &iobuf->list );
00683                 return iobuf;
00684         }
00685 
00686         return NULL;
00687 }
00688 
00689 /**
00690  * Transmit 802.11 management frame
00691  *
00692  * @v dev       802.11 device
00693  * @v fc        Frame Control flags for management frame
00694  * @v dest      Destination access point
00695  * @v iob       I/O buffer
00696  * @ret rc      Return status code
00697  *
00698  * The @a fc argument must contain at least an IEEE 802.11 management
00699  * subtype number (e.g. IEEE80211_STYPE_PROBE_REQ). If it contains
00700  * IEEE80211_FC_PROTECTED, the frame will be encrypted prior to
00701  * transmission.
00702  *
00703  * It is required that @a iob have at least 24 bytes of headroom
00704  * reserved before its data start.
00705  */
00706 int net80211_tx_mgmt ( struct net80211_device *dev, u16 fc, u8 dest[6],
00707                        struct io_buffer *iob )
00708 {
00709         struct ieee80211_frame *hdr = iob_push ( iob,
00710                                                  IEEE80211_TYP_FRAME_HEADER_LEN );
00711 
00712         hdr->fc = IEEE80211_THIS_VERSION | IEEE80211_TYPE_MGMT |
00713             ( fc & ~IEEE80211_FC_PROTECTED );
00714         hdr->duration = net80211_duration ( dev, 10, dev->rates[dev->rate] );
00715         hdr->seq = IEEE80211_MAKESEQ ( ++dev->last_tx_seqnr, 0 );
00716 
00717         memcpy ( hdr->addr1, dest, ETH_ALEN );  /* DA = RA */
00718         memcpy ( hdr->addr2, dev->netdev->ll_addr, ETH_ALEN );  /* SA = TA */
00719         memcpy ( hdr->addr3, dest, ETH_ALEN );  /* BSSID */
00720 
00721         if ( fc & IEEE80211_FC_PROTECTED ) {
00722                 if ( ! dev->crypto )
00723                         return -EINVAL_CRYPTO_REQUEST;
00724 
00725                 struct io_buffer *eiob = dev->crypto->encrypt ( dev->crypto,
00726                                                                 iob );
00727                 free_iob ( iob );
00728                 iob = eiob;
00729         }
00730 
00731         return netdev_tx ( dev->netdev, iob );
00732 }
00733 
00734 
00735 /* ---------- Driver API ---------- */
00736 
00737 /** 802.11 association process descriptor */
00738 static struct process_descriptor net80211_process_desc =
00739         PROC_DESC ( struct net80211_device, proc_assoc,
00740                     net80211_step_associate );
00741 
00742 /**
00743  * Allocate 802.11 device
00744  *
00745  * @v priv_size         Size of driver-private allocation area
00746  * @ret dev             Newly allocated 802.11 device
00747  *
00748  * This function allocates a net_device with space in its private area
00749  * for both the net80211_device it will wrap and the driver-private
00750  * data space requested. It initializes the link-layer-specific parts
00751  * of the net_device, and links the net80211_device to the net_device
00752  * appropriately.
00753  */
00754 struct net80211_device * net80211_alloc ( size_t priv_size )
00755 {
00756         struct net80211_device *dev;
00757         struct net_device *netdev =
00758                 alloc_netdev ( sizeof ( *dev ) + priv_size );
00759 
00760         if ( ! netdev )
00761                 return NULL;
00762 
00763         netdev->ll_protocol = &net80211_ll_protocol;
00764         netdev->ll_broadcast = eth_broadcast;
00765         netdev->max_pkt_len = IEEE80211_MAX_DATA_LEN;
00766         netdev_init ( netdev, &net80211_netdev_ops );
00767 
00768         dev = netdev->priv;
00769         dev->netdev = netdev;
00770         dev->priv = ( u8 * ) dev + sizeof ( *dev );
00771         dev->op = &net80211_null_ops;
00772 
00773         process_init_stopped ( &dev->proc_assoc, &net80211_process_desc,
00774                                &netdev->refcnt );
00775         INIT_LIST_HEAD ( &dev->mgmt_queue );
00776         INIT_LIST_HEAD ( &dev->mgmt_info_queue );
00777 
00778         return dev;
00779 }
00780 
00781 /**
00782  * Register 802.11 device with network stack
00783  *
00784  * @v dev       802.11 device
00785  * @v ops       802.11 device operations
00786  * @v hw        802.11 hardware information
00787  *
00788  * This also registers the wrapping net_device with the higher network
00789  * layers.
00790  */
00791 int net80211_register ( struct net80211_device *dev,
00792                         struct net80211_device_operations *ops,
00793                         struct net80211_hw_info *hw )
00794 {
00795         dev->op = ops;
00796         dev->hw = malloc ( sizeof ( *hw ) );
00797         if ( ! dev->hw )
00798                 return -ENOMEM;
00799 
00800         memcpy ( dev->hw, hw, sizeof ( *hw ) );
00801         memcpy ( dev->netdev->hw_addr, hw->hwaddr, ETH_ALEN );
00802 
00803         /* Set some sensible channel defaults for driver's open() function */
00804         memcpy ( dev->channels, dev->hw->channels,
00805                  NET80211_MAX_CHANNELS * sizeof ( dev->channels[0] ) );
00806         dev->channel = 0;
00807 
00808         /* Mark device as not supporting interrupts, if applicable */
00809         if ( ! ops->irq )
00810                 dev->netdev->state |= NETDEV_IRQ_UNSUPPORTED;
00811 
00812         list_add_tail ( &dev->list, &net80211_devices );
00813         return register_netdev ( dev->netdev );
00814 }
00815 
00816 /**
00817  * Unregister 802.11 device from network stack
00818  *
00819  * @v dev       802.11 device
00820  *
00821  * After this call, the device operations are cleared so that they
00822  * will not be called.
00823  */
00824 void net80211_unregister ( struct net80211_device *dev )
00825 {
00826         unregister_netdev ( dev->netdev );
00827         list_del ( &dev->list );
00828         dev->op = &net80211_null_ops;
00829 }
00830 
00831 /**
00832  * Free 802.11 device
00833  *
00834  * @v dev       802.11 device
00835  *
00836  * The device should be unregistered before this function is called.
00837  */
00838 void net80211_free ( struct net80211_device *dev )
00839 {
00840         free ( dev->hw );
00841         rc80211_free ( dev->rctl );
00842         netdev_nullify ( dev->netdev );
00843         netdev_put ( dev->netdev );
00844 }
00845 
00846 
00847 /* ---------- 802.11 network management workhorse code ---------- */
00848 
00849 /**
00850  * Set state of 802.11 device
00851  *
00852  * @v dev       802.11 device
00853  * @v clear     Bitmask of flags to clear
00854  * @v set       Bitmask of flags to set
00855  * @v status    Status or reason code for most recent operation
00856  *
00857  * If @a status represents a reason code, it should be OR'ed with
00858  * NET80211_IS_REASON.
00859  *
00860  * Clearing authentication also clears association; clearing
00861  * association also clears security handshaking state. Clearing
00862  * association removes the link-up flag from the wrapping net_device,
00863  * but setting it does not automatically set the flag; that is left to
00864  * the judgment of higher-level code.
00865  */
00866 static inline void net80211_set_state ( struct net80211_device *dev,
00867                                         short clear, short set,
00868                                         u16 status )
00869 {
00870         /* The conditions in this function are deliberately formulated
00871            to be decidable at compile-time in most cases. Since clear
00872            and set are generally passed as constants, the body of this
00873            function can be reduced down to a few statements by the
00874            compiler. */
00875 
00876         const int statmsk = NET80211_STATUS_MASK | NET80211_IS_REASON;
00877 
00878         if ( clear & NET80211_PROBED )
00879                 clear |= NET80211_AUTHENTICATED;
00880 
00881         if ( clear & NET80211_AUTHENTICATED )
00882                 clear |= NET80211_ASSOCIATED;
00883 
00884         if ( clear & NET80211_ASSOCIATED )
00885                 clear |= NET80211_CRYPTO_SYNCED;
00886 
00887         dev->state = ( dev->state & ~clear ) | set;
00888         dev->state = ( dev->state & ~statmsk ) | ( status & statmsk );
00889 
00890         if ( clear & NET80211_ASSOCIATED )
00891                 netdev_link_down ( dev->netdev );
00892 
00893         if ( ( clear | set ) & NET80211_ASSOCIATED )
00894                 dev->op->config ( dev, NET80211_CFG_ASSOC );
00895 
00896         if ( status != 0 ) {
00897                 if ( status & NET80211_IS_REASON )
00898                         dev->assoc_rc = -E80211_REASON ( status );
00899                 else
00900                         dev->assoc_rc = -E80211_STATUS ( status );
00901                 netdev_link_err ( dev->netdev, dev->assoc_rc );
00902         }
00903 }
00904 
00905 /**
00906  * Add channels to 802.11 device
00907  *
00908  * @v dev       802.11 device
00909  * @v start     First channel number to add
00910  * @v len       Number of channels to add
00911  * @v txpower   TX power (dBm) to allow on added channels
00912  *
00913  * To replace the current list of channels instead of adding to it,
00914  * set the nr_channels field of the 802.11 device to 0 before calling
00915  * this function.
00916  */
00917 static void net80211_add_channels ( struct net80211_device *dev, int start,
00918                                     int len, int txpower )
00919 {
00920         int i, chan = start;
00921 
00922         for ( i = dev->nr_channels; len-- && i < NET80211_MAX_CHANNELS; i++ ) {
00923                 dev->channels[i].channel_nr = chan;
00924                 dev->channels[i].maxpower = txpower;
00925                 dev->channels[i].hw_value = 0;
00926 
00927                 if ( chan >= 1 && chan <= 14 ) {
00928                         dev->channels[i].band = NET80211_BAND_2GHZ;
00929                         if ( chan == 14 )
00930                                 dev->channels[i].center_freq = 2484;
00931                         else
00932                                 dev->channels[i].center_freq = 2407 + 5 * chan;
00933                         chan++;
00934                 } else {
00935                         dev->channels[i].band = NET80211_BAND_5GHZ;
00936                         dev->channels[i].center_freq = 5000 + 5 * chan;
00937                         chan += 4;
00938                 }
00939         }
00940 
00941         dev->nr_channels = i;
00942 }
00943 
00944 /**
00945  * Filter 802.11 device channels for hardware capabilities
00946  *
00947  * @v dev       802.11 device
00948  *
00949  * Hardware may support fewer channels than regulatory restrictions
00950  * allow; this function filters out channels in dev->channels that are
00951  * not supported by the hardware list in dev->hwinfo. It also copies
00952  * over the net80211_channel::hw_value and limits maximum TX power
00953  * appropriately.
00954  *
00955  * Channels are matched based on center frequency, ignoring band and
00956  * channel number.
00957  *
00958  * If the driver specifies no supported channels, the effect will be
00959  * as though all were supported.
00960  */
00961 static void net80211_filter_hw_channels ( struct net80211_device *dev )
00962 {
00963         int delta = 0, i = 0;
00964         int old_freq = dev->channels[dev->channel].center_freq;
00965         struct net80211_channel *chan, *hwchan;
00966 
00967         if ( ! dev->hw->nr_channels )
00968                 return;
00969 
00970         dev->channel = 0;
00971         for ( chan = dev->channels; chan < dev->channels + dev->nr_channels;
00972               chan++, i++ ) {
00973                 int ok = 0;
00974                 for ( hwchan = dev->hw->channels;
00975                       hwchan < dev->hw->channels + dev->hw->nr_channels;
00976                       hwchan++ ) {
00977                         if ( hwchan->center_freq == chan->center_freq ) {
00978                                 ok = 1;
00979                                 break;
00980                         }
00981                 }
00982 
00983                 if ( ! ok )
00984                         delta++;
00985                 else {
00986                         chan->hw_value = hwchan->hw_value;
00987                         if ( hwchan->maxpower != 0 &&
00988                              chan->maxpower > hwchan->maxpower )
00989                                 chan->maxpower = hwchan->maxpower;
00990                         if ( old_freq == chan->center_freq )
00991                                 dev->channel = i - delta;
00992                         if ( delta )
00993                                 chan[-delta] = *chan;
00994                 }
00995         }
00996 
00997         dev->nr_channels -= delta;
00998 
00999         if ( dev->channels[dev->channel].center_freq != old_freq )
01000                 dev->op->config ( dev, NET80211_CFG_CHANNEL );
01001 }
01002 
01003 /**
01004  * Update 802.11 device state to reflect received capabilities field
01005  *
01006  * @v dev       802.11 device
01007  * @v capab     Capabilities field in beacon, probe, or association frame
01008  * @ret rc      Return status code
01009  */
01010 static int net80211_process_capab ( struct net80211_device *dev,
01011                                     u16 capab )
01012 {
01013         u16 old_phy = dev->phy_flags;
01014 
01015         if ( ( capab & ( IEEE80211_CAPAB_MANAGED | IEEE80211_CAPAB_ADHOC ) ) !=
01016              IEEE80211_CAPAB_MANAGED ) {
01017                 DBGC ( dev, "802.11 %p cannot handle IBSS network\n", dev );
01018                 return -ENOSYS;
01019         }
01020 
01021         dev->phy_flags &= ~( NET80211_PHY_USE_SHORT_PREAMBLE |
01022                              NET80211_PHY_USE_SHORT_SLOT );
01023 
01024         if ( capab & IEEE80211_CAPAB_SHORT_PMBL )
01025                 dev->phy_flags |= NET80211_PHY_USE_SHORT_PREAMBLE;
01026 
01027         if ( capab & IEEE80211_CAPAB_SHORT_SLOT )
01028                 dev->phy_flags |= NET80211_PHY_USE_SHORT_SLOT;
01029 
01030         if ( old_phy != dev->phy_flags )
01031                 dev->op->config ( dev, NET80211_CFG_PHY_PARAMS );
01032 
01033         return 0;
01034 }
01035 
01036 /**
01037  * Update 802.11 device state to reflect received information elements
01038  *
01039  * @v dev       802.11 device
01040  * @v ie        Pointer to first information element
01041  * @v ie_end    Pointer to tail of packet I/O buffer
01042  * @ret rc      Return status code
01043  */
01044 static int net80211_process_ie ( struct net80211_device *dev,
01045                                  union ieee80211_ie *ie, void *ie_end )
01046 {
01047         u16 old_rate = dev->rates[dev->rate];
01048         u16 old_phy = dev->phy_flags;
01049         int have_rates = 0, i;
01050         int ds_channel = 0;
01051         int changed = 0;
01052         int band = dev->channels[dev->channel].band;
01053 
01054         if ( ! ieee80211_ie_bound ( ie, ie_end ) )
01055                 return 0;
01056 
01057         for ( ; ie; ie = ieee80211_next_ie ( ie, ie_end ) ) {
01058                 switch ( ie->id ) {
01059                 case IEEE80211_IE_SSID:
01060                         if ( ie->len <= 32 ) {
01061                                 memcpy ( dev->essid, ie->ssid, ie->len );
01062                                 dev->essid[ie->len] = 0;
01063                         }
01064                         break;
01065 
01066                 case IEEE80211_IE_RATES:
01067                 case IEEE80211_IE_EXT_RATES:
01068                         if ( ! have_rates ) {
01069                                 dev->nr_rates = 0;
01070                                 dev->basic_rates = 0;
01071                                 have_rates = 1;
01072                         }
01073                         for ( i = 0; i < ie->len &&
01074                               dev->nr_rates < NET80211_MAX_RATES; i++ ) {
01075                                 u8 rid = ie->rates[i];
01076                                 u16 rate = ( rid & 0x7f ) * 5;
01077 
01078                                 if ( rid & 0x80 )
01079                                         dev->basic_rates |=
01080                                                 ( 1 << dev->nr_rates );
01081 
01082                                 dev->rates[dev->nr_rates++] = rate;
01083                         }
01084 
01085                         break;
01086 
01087                 case IEEE80211_IE_DS_PARAM:
01088                         if ( dev->channel < dev->nr_channels && ds_channel ==
01089                              dev->channels[dev->channel].channel_nr )
01090                                 break;
01091                         ds_channel = ie->ds_param.current_channel;
01092                         net80211_change_channel ( dev, ds_channel );
01093                         break;
01094 
01095                 case IEEE80211_IE_COUNTRY:
01096                         dev->nr_channels = 0;
01097 
01098                         DBGC ( dev, "802.11 %p setting country regulations "
01099                                "for %c%c\n", dev, ie->country.name[0],
01100                                ie->country.name[1] );
01101                         for ( i = 0; i < ( ie->len - 3 ) / 3; i++ ) {
01102                                 union ieee80211_ie_country_triplet *t =
01103                                         &ie->country.triplet[i];
01104                                 if ( t->first > 200 ) {
01105                                         DBGC ( dev, "802.11 %p ignoring regulatory "
01106                                                "extension information\n", dev );
01107                                 } else {
01108                                         net80211_add_channels ( dev,
01109                                                         t->band.first_channel,
01110                                                         t->band.nr_channels,
01111                                                         t->band.max_txpower );
01112                                 }
01113                         }
01114                         net80211_filter_hw_channels ( dev );
01115                         break;
01116 
01117                 case IEEE80211_IE_ERP_INFO:
01118                         dev->phy_flags &= ~( NET80211_PHY_USE_PROTECTION |
01119                                              NET80211_PHY_USE_SHORT_PREAMBLE );
01120                         if ( ie->erp_info & IEEE80211_ERP_USE_PROTECTION )
01121                                 dev->phy_flags |= NET80211_PHY_USE_PROTECTION;
01122                         if ( ! ( ie->erp_info & IEEE80211_ERP_BARKER_LONG ) )
01123                                 dev->phy_flags |= NET80211_PHY_USE_SHORT_PREAMBLE;
01124                         break;
01125                 }
01126         }
01127 
01128         if ( have_rates ) {
01129                 /* Allow only those rates that are also supported by
01130                    the hardware. */
01131                 int delta = 0, j;
01132 
01133                 dev->rate = 0;
01134                 for ( i = 0; i < dev->nr_rates; i++ ) {
01135                         int ok = 0;
01136                         for ( j = 0; j < dev->hw->nr_rates[band]; j++ ) {
01137                                 if ( dev->hw->rates[band][j] == dev->rates[i] ){
01138                                         ok = 1;
01139                                         break;
01140                                 }
01141                         }
01142 
01143                         if ( ! ok )
01144                                 delta++;
01145                         else {
01146                                 dev->rates[i - delta] = dev->rates[i];
01147                                 if ( old_rate == dev->rates[i] )
01148                                         dev->rate = i - delta;
01149                         }
01150                 }
01151 
01152                 dev->nr_rates -= delta;
01153 
01154                 /* Sort available rates - sorted subclumps tend to already
01155                    exist, so insertion sort works well. */
01156                 for ( i = 1; i < dev->nr_rates; i++ ) {
01157                         u16 rate = dev->rates[i];
01158                         u32 tmp, br, mask;
01159 
01160                         for ( j = i - 1; j >= 0 && dev->rates[j] >= rate; j-- )
01161                                 dev->rates[j + 1] = dev->rates[j];
01162                         dev->rates[j + 1] = rate;
01163 
01164                         /* Adjust basic_rates to match by rotating the
01165                            bits from bit j+1 to bit i left one position. */
01166                         mask = ( ( 1 << i ) - 1 ) & ~( ( 1 << ( j + 1 ) ) - 1 );
01167                         br = dev->basic_rates;
01168                         tmp = br & ( 1 << i );
01169                         br = ( br & ~( mask | tmp ) ) | ( ( br & mask ) << 1 );
01170                         br |= ( tmp >> ( i - j - 1 ) );
01171                         dev->basic_rates = br;
01172                 }
01173 
01174                 net80211_set_rtscts_rate ( dev );
01175 
01176                 if ( dev->rates[dev->rate] != old_rate )
01177                         changed |= NET80211_CFG_RATE;
01178         }
01179 
01180         if ( dev->hw->flags & NET80211_HW_NO_SHORT_PREAMBLE )
01181                 dev->phy_flags &= ~NET80211_PHY_USE_SHORT_PREAMBLE;
01182         if ( dev->hw->flags & NET80211_HW_NO_SHORT_SLOT )
01183                 dev->phy_flags &= ~NET80211_PHY_USE_SHORT_SLOT;
01184 
01185         if ( old_phy != dev->phy_flags )
01186                 changed |= NET80211_CFG_PHY_PARAMS;
01187 
01188         if ( changed )
01189                 dev->op->config ( dev, changed );
01190 
01191         return 0;
01192 }
01193 
01194 /**
01195  * Create information elements for outgoing probe or association packet
01196  *
01197  * @v dev               802.11 device
01198  * @v ie                Pointer to start of information element area
01199  * @ret next_ie         Pointer to first byte after added information elements
01200  */
01201 static union ieee80211_ie *
01202 net80211_marshal_request_info ( struct net80211_device *dev,
01203                                 union ieee80211_ie *ie )
01204 {
01205         int i;
01206 
01207         ie->id = IEEE80211_IE_SSID;
01208         ie->len = strlen ( dev->essid );
01209         memcpy ( ie->ssid, dev->essid, ie->len );
01210 
01211         ie = ieee80211_next_ie ( ie, NULL );
01212 
01213         ie->id = IEEE80211_IE_RATES;
01214         ie->len = dev->nr_rates;
01215         if ( ie->len > 8 )
01216                 ie->len = 8;
01217 
01218         for ( i = 0; i < ie->len; i++ ) {
01219                 ie->rates[i] = dev->rates[i] / 5;
01220                 if ( dev->basic_rates & ( 1 << i ) )
01221                         ie->rates[i] |= 0x80;
01222         }
01223 
01224         ie = ieee80211_next_ie ( ie, NULL );
01225 
01226         if ( dev->rsn_ie && dev->rsn_ie->id == IEEE80211_IE_RSN ) {
01227                 memcpy ( ie, dev->rsn_ie, dev->rsn_ie->len + 2 );
01228                 ie = ieee80211_next_ie ( ie, NULL );
01229         }
01230 
01231         if ( dev->nr_rates > 8 ) {
01232                 /* 802.11 requires we use an Extended Basic Rates IE
01233                    for the rates beyond the eighth. */
01234 
01235                 ie->id = IEEE80211_IE_EXT_RATES;
01236                 ie->len = dev->nr_rates - 8;
01237 
01238                 for ( ; i < dev->nr_rates; i++ ) {
01239                         ie->rates[i - 8] = dev->rates[i] / 5;
01240                         if ( dev->basic_rates & ( 1 << i ) )
01241                                 ie->rates[i - 8] |= 0x80;
01242                 }
01243 
01244                 ie = ieee80211_next_ie ( ie, NULL );
01245         }
01246 
01247         if ( dev->rsn_ie && dev->rsn_ie->id == IEEE80211_IE_VENDOR ) {
01248                 memcpy ( ie, dev->rsn_ie, dev->rsn_ie->len + 2 );
01249                 ie = ieee80211_next_ie ( ie, NULL );
01250         }
01251 
01252         return ie;
01253 }
01254 
01255 /** Seconds to wait after finding a network, to possibly find better APs for it
01256  *
01257  * This is used when a specific SSID to scan for is specified.
01258  */
01259 #define NET80211_PROBE_GATHER    1
01260 
01261 /** Seconds to wait after finding a network, to possibly find other networks
01262  *
01263  * This is used when an empty SSID is specified, to scan for all
01264  * networks.
01265  */
01266 #define NET80211_PROBE_GATHER_ALL 2
01267 
01268 /** Seconds to allow a probe to take if no network has been found */
01269 #define NET80211_PROBE_TIMEOUT   6
01270 
01271 /**
01272  * Begin probe of 802.11 networks
01273  *
01274  * @v dev       802.11 device
01275  * @v essid     SSID to probe for, or "" to accept any (may not be NULL)
01276  * @v active    Whether to use active scanning
01277  * @ret ctx     Probe context
01278  *
01279  * Active scanning may only be used on channels 1-11 in the 2.4GHz
01280  * band, due to iPXE's lack of a complete regulatory database. If
01281  * active scanning is used, probe packets will be sent on each
01282  * channel; this can allow association with hidden-SSID networks if
01283  * the SSID is properly specified.
01284  *
01285  * A @c NULL return indicates an out-of-memory condition.
01286  *
01287  * The returned context must be periodically passed to
01288  * net80211_probe_step() until that function returns zero.
01289  */
01290 struct net80211_probe_ctx * net80211_probe_start ( struct net80211_device *dev,
01291                                                    const char *essid,
01292                                                    int active )
01293 {
01294         struct net80211_probe_ctx *ctx = zalloc ( sizeof ( *ctx ) );
01295 
01296         if ( ! ctx )
01297                 return NULL;
01298 
01299         assert ( netdev_is_open ( dev->netdev ) );
01300 
01301         ctx->dev = dev;
01302         ctx->old_keep_mgmt = net80211_keep_mgmt ( dev, 1 );
01303         ctx->essid = essid;
01304         if ( dev->essid != ctx->essid )
01305                 strcpy ( dev->essid, ctx->essid );
01306 
01307         if ( active ) {
01308                 struct ieee80211_probe_req *probe_req;
01309                 union ieee80211_ie *ie;
01310 
01311                 ctx->probe = alloc_iob ( 128 );
01312                 iob_reserve ( ctx->probe, IEEE80211_TYP_FRAME_HEADER_LEN );
01313                 probe_req = ctx->probe->data;
01314 
01315                 ie = net80211_marshal_request_info ( dev,
01316                                                      probe_req->info_element );
01317 
01318                 iob_put ( ctx->probe, ( void * ) ie - ctx->probe->data );
01319         }
01320 
01321         ctx->ticks_start = currticks();
01322         ctx->ticks_beacon = 0;
01323         ctx->ticks_channel = currticks();
01324         ctx->hop_time = TICKS_PER_SEC / ( active ? 2 : 6 );
01325 
01326         /*
01327          * Channels on 2.4GHz overlap, and the most commonly used
01328          * are 1, 6, and 11. We'll get a result faster if we check
01329          * every 5 channels, but in order to hit all of them the
01330          * number of channels must be relatively prime to 5. If it's
01331          * not, tweak the hop.
01332          */
01333         ctx->hop_step = 5;
01334         while ( dev->nr_channels % ctx->hop_step == 0 && ctx->hop_step > 1 )
01335                 ctx->hop_step--;
01336 
01337         ctx->beacons = malloc ( sizeof ( *ctx->beacons ) );
01338         INIT_LIST_HEAD ( ctx->beacons );
01339 
01340         dev->channel = 0;
01341         dev->op->config ( dev, NET80211_CFG_CHANNEL );
01342 
01343         return ctx;
01344 }
01345 
01346 /**
01347  * Continue probe of 802.11 networks
01348  *
01349  * @v ctx       Probe context returned by net80211_probe_start()
01350  * @ret rc      Probe status
01351  *
01352  * The return code will be 0 if the probe is still going on (and this
01353  * function should be called again), a positive number if the probe
01354  * completed successfully, or a negative error code if the probe
01355  * failed for that reason.
01356  *
01357  * Whether the probe succeeded or failed, you must call
01358  * net80211_probe_finish_all() or net80211_probe_finish_best()
01359  * (depending on whether you want information on all networks or just
01360  * the best-signal one) in order to release the probe context. A
01361  * failed probe may still have acquired some valid data.
01362  */
01363 int net80211_probe_step ( struct net80211_probe_ctx *ctx )
01364 {
01365         struct net80211_device *dev = ctx->dev;
01366         u32 start_timeout = NET80211_PROBE_TIMEOUT * TICKS_PER_SEC;
01367         u32 gather_timeout = TICKS_PER_SEC;
01368         u32 now = currticks();
01369         struct io_buffer *iob;
01370         int signal;
01371         int rc;
01372         char ssid[IEEE80211_MAX_SSID_LEN + 1];
01373 
01374         gather_timeout *= ( ctx->essid[0] ? NET80211_PROBE_GATHER :
01375                             NET80211_PROBE_GATHER_ALL );
01376 
01377         /* Time out if necessary */
01378         if ( now >= ctx->ticks_start + start_timeout )
01379                 return list_empty ( ctx->beacons ) ? -ETIMEDOUT : +1;
01380 
01381         if ( ctx->ticks_beacon > 0 && now >= ctx->ticks_start + gather_timeout )
01382                 return +1;
01383 
01384         /* Change channels if necessary */
01385         if ( now >= ctx->ticks_channel + ctx->hop_time ) {
01386                 dev->channel = ( dev->channel + ctx->hop_step )
01387                         % dev->nr_channels;
01388                 dev->op->config ( dev, NET80211_CFG_CHANNEL );
01389                 udelay ( dev->hw->channel_change_time );
01390 
01391                 ctx->ticks_channel = now;
01392 
01393                 if ( ctx->probe ) {
01394                         struct io_buffer *siob = ctx->probe; /* to send */
01395 
01396                         /* make a copy for future use */
01397                         iob = alloc_iob ( siob->tail - siob->head );
01398                         iob_reserve ( iob, iob_headroom ( siob ) );
01399                         memcpy ( iob_put ( iob, iob_len ( siob ) ),
01400                                  siob->data, iob_len ( siob ) );
01401 
01402                         ctx->probe = iob;
01403                         rc = net80211_tx_mgmt ( dev, IEEE80211_STYPE_PROBE_REQ,
01404                                                 eth_broadcast,
01405                                                 iob_disown ( siob ) );
01406                         if ( rc ) {
01407                                 DBGC ( dev, "802.11 %p send probe failed: "
01408                                        "%s\n", dev, strerror ( rc ) );
01409                                 return rc;
01410                         }
01411                 }
01412         }
01413 
01414         /* Check for new management packets */
01415         while ( ( iob = net80211_mgmt_dequeue ( dev, &signal ) ) != NULL ) {
01416                 struct ieee80211_frame *hdr;
01417                 struct ieee80211_beacon *beacon;
01418                 union ieee80211_ie *ie;
01419                 struct net80211_wlan *wlan;
01420                 u16 type;
01421 
01422                 hdr = iob->data;
01423                 type = hdr->fc & IEEE80211_FC_SUBTYPE;
01424                 beacon = ( struct ieee80211_beacon * ) hdr->data;
01425 
01426                 if ( type != IEEE80211_STYPE_BEACON &&
01427                      type != IEEE80211_STYPE_PROBE_RESP ) {
01428                         DBGC2 ( dev, "802.11 %p probe: non-beacon\n", dev );
01429                         goto drop;
01430                 }
01431 
01432                 if ( ( void * ) beacon->info_element >= iob->tail ) {
01433                         DBGC ( dev, "802.11 %p probe: beacon with no IEs\n",
01434                                dev );
01435                         goto drop;
01436                 }
01437 
01438                 ie = beacon->info_element;
01439 
01440                 if ( ! ieee80211_ie_bound ( ie, iob->tail ) )
01441                         ie = NULL;
01442 
01443                 while ( ie && ie->id != IEEE80211_IE_SSID )
01444                         ie = ieee80211_next_ie ( ie, iob->tail );
01445 
01446                 if ( ! ie ) {
01447                         DBGC ( dev, "802.11 %p probe: beacon with no SSID\n",
01448                                dev );
01449                         goto drop;
01450                 }
01451 
01452                 memcpy ( ssid, ie->ssid, ie->len );
01453                 ssid[ie->len] = 0;
01454 
01455                 if ( ctx->essid[0] && strcmp ( ctx->essid, ssid ) != 0 ) {
01456                         DBGC2 ( dev, "802.11 %p probe: beacon with wrong SSID "
01457                                 "(%s)\n", dev, ssid );
01458                         goto drop;
01459                 }
01460 
01461                 /* See if we've got an entry for this network */
01462                 list_for_each_entry ( wlan, ctx->beacons, list ) {
01463                         if ( strcmp ( wlan->essid, ssid ) != 0 )
01464                                 continue;
01465 
01466                         if ( signal < wlan->signal ) {
01467                                 DBGC2 ( dev, "802.11 %p probe: beacon for %s "
01468                                         "(%s) with weaker signal %d\n", dev,
01469                                         ssid, eth_ntoa ( hdr->addr3 ), signal );
01470                                 goto drop;
01471                         }
01472 
01473                         goto fill;
01474                 }
01475 
01476                 /* No entry yet - make one */
01477                 wlan = zalloc ( sizeof ( *wlan ) );
01478                 strcpy ( wlan->essid, ssid );
01479                 list_add_tail ( &wlan->list, ctx->beacons );
01480 
01481                 /* Whether we're using an old entry or a new one, fill
01482                    it with new data. */
01483         fill:
01484                 memcpy ( wlan->bssid, hdr->addr3, ETH_ALEN );
01485                 wlan->signal = signal;
01486                 wlan->channel = dev->channels[dev->channel].channel_nr;
01487 
01488                 /* Copy this I/O buffer into a new wlan->beacon; the
01489                  * iob we've got probably came from the device driver
01490                  * and may have the full 2.4k allocation, which we
01491                  * don't want to keep around wasting memory.
01492                  */
01493                 free_iob ( wlan->beacon );
01494                 wlan->beacon = alloc_iob ( iob_len ( iob ) );
01495                 memcpy ( iob_put ( wlan->beacon, iob_len ( iob ) ),
01496                          iob->data, iob_len ( iob ) );
01497 
01498                 if ( ( rc = sec80211_detect ( wlan->beacon, &wlan->handshaking,
01499                                               &wlan->crypto ) ) == -ENOTSUP ) {
01500                         struct ieee80211_beacon *beacon =
01501                                 ( struct ieee80211_beacon * ) hdr->data;
01502 
01503                         if ( beacon->capability & IEEE80211_CAPAB_PRIVACY ) {
01504                                 DBG ( "802.11 %p probe: secured network %s but "
01505                                       "encryption support not compiled in\n",
01506                                       dev, wlan->essid );
01507                                 wlan->handshaking = NET80211_SECPROT_UNKNOWN;
01508                                 wlan->crypto = NET80211_CRYPT_UNKNOWN;
01509                         } else {
01510                                 wlan->handshaking = NET80211_SECPROT_NONE;
01511                                 wlan->crypto = NET80211_CRYPT_NONE;
01512                         }
01513                 } else if ( rc != 0 ) {
01514                         DBGC ( dev, "802.11 %p probe warning: network "
01515                                "%s with unidentifiable security "
01516                                "settings: %s\n", dev, wlan->essid,
01517                                strerror ( rc ) );
01518                 }
01519 
01520                 ctx->ticks_beacon = now;
01521 
01522                 DBGC2 ( dev, "802.11 %p probe: good beacon for %s (%s)\n",
01523                         dev, wlan->essid, eth_ntoa ( wlan->bssid ) );
01524 
01525         drop:
01526                 free_iob ( iob );
01527         }
01528 
01529         return 0;
01530 }
01531 
01532 
01533 /**
01534  * Finish probe of 802.11 networks, returning best-signal network found
01535  *
01536  * @v ctx       Probe context
01537  * @ret wlan    Best-signal network found, or @c NULL if none were found
01538  *
01539  * If net80211_probe_start() was called with a particular SSID
01540  * parameter as filter, only a network with that SSID (matching
01541  * case-sensitively) can be returned from this function.
01542  */
01543 struct net80211_wlan *
01544 net80211_probe_finish_best ( struct net80211_probe_ctx *ctx )
01545 {
01546         struct net80211_wlan *best = NULL, *wlan;
01547 
01548         if ( ! ctx )
01549                 return NULL;
01550 
01551         list_for_each_entry ( wlan, ctx->beacons, list ) {
01552                 if ( ! best || best->signal < wlan->signal )
01553                         best = wlan;
01554         }
01555 
01556         if ( best )
01557                 list_del ( &best->list );
01558         else
01559                 DBGC ( ctx->dev, "802.11 %p probe: found nothing for '%s'\n",
01560                        ctx->dev, ctx->essid );
01561 
01562         net80211_free_wlanlist ( ctx->beacons );
01563 
01564         net80211_keep_mgmt ( ctx->dev, ctx->old_keep_mgmt );
01565 
01566         if ( ctx->probe )
01567                 free_iob ( ctx->probe );
01568 
01569         free ( ctx );
01570 
01571         return best;
01572 }
01573 
01574 
01575 /**
01576  * Finish probe of 802.11 networks, returning all networks found
01577  *
01578  * @v ctx       Probe context
01579  * @ret list    List of net80211_wlan detailing networks found
01580  *
01581  * If net80211_probe_start() was called with a particular SSID
01582  * parameter as filter, this will always return either an empty or a
01583  * one-element list.
01584  */
01585 struct list_head *net80211_probe_finish_all ( struct net80211_probe_ctx *ctx )
01586 {
01587         struct list_head *beacons = ctx->beacons;
01588 
01589         net80211_keep_mgmt ( ctx->dev, ctx->old_keep_mgmt );
01590 
01591         if ( ctx->probe )
01592                 free_iob ( ctx->probe );
01593 
01594         free ( ctx );
01595 
01596         return beacons;
01597 }
01598 
01599 
01600 /**
01601  * Free WLAN structure
01602  *
01603  * @v wlan      WLAN structure to free
01604  */
01605 void net80211_free_wlan ( struct net80211_wlan *wlan )
01606 {
01607         if ( wlan ) {
01608                 free_iob ( wlan->beacon );
01609                 free ( wlan );
01610         }
01611 }
01612 
01613 
01614 /**
01615  * Free list of WLAN structures
01616  *
01617  * @v list      List of WLAN structures to free
01618  */
01619 void net80211_free_wlanlist ( struct list_head *list )
01620 {
01621         struct net80211_wlan *wlan, *tmp;
01622 
01623         if ( ! list )
01624                 return;
01625 
01626         list_for_each_entry_safe ( wlan, tmp, list, list ) {
01627                 list_del ( &wlan->list );
01628                 net80211_free_wlan ( wlan );
01629         }
01630 
01631         free ( list );
01632 }
01633 
01634 
01635 /** Number of ticks to wait for replies to association management frames */
01636 #define ASSOC_TIMEOUT   TICKS_PER_SEC
01637 
01638 /** Number of times to try sending a particular association management frame */
01639 #define ASSOC_RETRIES   2
01640 
01641 /**
01642  * Step 802.11 association process
01643  *
01644  * @v dev       802.11 device
01645  */
01646 static void net80211_step_associate ( struct net80211_device *dev )
01647 {
01648         int rc = 0;
01649         int status = dev->state & NET80211_STATUS_MASK;
01650 
01651         /*
01652          * We use a sort of state machine implemented using bits in
01653          * the dev->state variable. At each call, we take the
01654          * logically first step that has not yet succeeded; either it
01655          * has not been tried yet, it's being retried, or it failed.
01656          * If it failed, we return an error indication; otherwise we
01657          * perform the step. If it succeeds, RX handling code will set
01658          * the appropriate status bit for us.
01659          *
01660          * Probe works a bit differently, since we have to step it
01661          * on every call instead of waiting for a packet to arrive
01662          * that will set the completion bit for us.
01663          */
01664 
01665         /* If we're waiting for a reply, check for timeout condition */
01666         if ( dev->state & NET80211_WAITING ) {
01667                 /* Sanity check */
01668                 if ( ! dev->associating )
01669                         return;
01670 
01671                 if ( currticks() - dev->ctx.assoc->last_packet > ASSOC_TIMEOUT ) {
01672                         /* Timed out - fail if too many retries, or retry */
01673                         dev->ctx.assoc->times_tried++;
01674                         if ( ++dev->ctx.assoc->times_tried > ASSOC_RETRIES ) {
01675                                 rc = -ETIMEDOUT;
01676                                 goto fail;
01677                         }
01678                 } else {
01679                         /* Didn't time out - let it keep going */
01680                         return;
01681                 }
01682         } else {
01683                 if ( dev->state & NET80211_PROBED )
01684                         dev->ctx.assoc->times_tried = 0;
01685         }
01686 
01687         if ( ! ( dev->state & NET80211_PROBED ) ) {
01688                 /* state: probe */
01689 
01690                 if ( ! dev->ctx.probe ) {
01691                         /* start probe */
01692                         int active = fetch_intz_setting ( NULL,
01693                                                 &net80211_active_setting );
01694                         int band = dev->hw->bands;
01695 
01696                         if ( active )
01697                                 band &= ~NET80211_BAND_BIT_5GHZ;
01698 
01699                         rc = net80211_prepare_probe ( dev, band, active );
01700                         if ( rc )
01701                                 goto fail;
01702 
01703                         dev->ctx.probe = net80211_probe_start ( dev, dev->essid,
01704                                                                 active );
01705                         if ( ! dev->ctx.probe ) {
01706                                 dev->assoc_rc = -ENOMEM;
01707                                 goto fail;
01708                         }
01709                 }
01710 
01711                 rc = net80211_probe_step ( dev->ctx.probe );
01712                 if ( ! rc ) {
01713                         return; /* still going */
01714                 }
01715 
01716                 dev->associating = net80211_probe_finish_best ( dev->ctx.probe );
01717                 dev->ctx.probe = NULL;
01718                 if ( ! dev->associating ) {
01719                         if ( rc > 0 ) /* "successful" probe found nothing */
01720                                 rc = -ETIMEDOUT;
01721                         goto fail;
01722                 }
01723 
01724                 /* If we probed using a broadcast SSID, record that
01725                    fact for the settings applicator before we clobber
01726                    it with the specific SSID we've chosen. */
01727                 if ( ! dev->essid[0] )
01728                         dev->state |= NET80211_AUTO_SSID;
01729 
01730                 DBGC ( dev, "802.11 %p found network %s (%s)\n", dev,
01731                        dev->associating->essid,
01732                        eth_ntoa ( dev->associating->bssid ) );
01733 
01734                 dev->ctx.assoc = zalloc ( sizeof ( *dev->ctx.assoc ) );
01735                 if ( ! dev->ctx.assoc ) {
01736                         rc = -ENOMEM;
01737                         goto fail;
01738                 }
01739 
01740                 dev->state |= NET80211_PROBED;
01741                 dev->ctx.assoc->method = IEEE80211_AUTH_OPEN_SYSTEM;
01742 
01743                 return;
01744         }
01745 
01746         /* Record time of sending the packet we're about to send, for timeout */
01747         dev->ctx.assoc->last_packet = currticks();
01748 
01749         if ( ! ( dev->state & NET80211_AUTHENTICATED ) ) {
01750                 /* state: prepare and authenticate */
01751 
01752                 if ( status != IEEE80211_STATUS_SUCCESS ) {
01753                         /* we tried authenticating already, but failed */
01754                         int method = dev->ctx.assoc->method;
01755 
01756                         if ( method == IEEE80211_AUTH_OPEN_SYSTEM &&
01757                              ( status == IEEE80211_STATUS_AUTH_CHALL_INVALID ||
01758                                status == IEEE80211_STATUS_AUTH_ALGO_UNSUPP ) ) {
01759                                 /* Maybe this network uses Shared Key? */
01760                                 dev->ctx.assoc->method =
01761                                         IEEE80211_AUTH_SHARED_KEY;
01762                         } else {
01763                                 goto fail;
01764                         }
01765                 }
01766 
01767                 DBGC ( dev, "802.11 %p authenticating with method %d\n", dev,
01768                        dev->ctx.assoc->method );
01769 
01770                 rc = net80211_prepare_assoc ( dev, dev->associating );
01771                 if ( rc )
01772                         goto fail;
01773 
01774                 rc = net80211_send_auth ( dev, dev->associating,
01775                                           dev->ctx.assoc->method );
01776                 if ( rc )
01777                         goto fail;
01778 
01779                 return;
01780         }
01781 
01782         if ( ! ( dev->state & NET80211_ASSOCIATED ) ) {
01783                 /* state: associate */
01784 
01785                 if ( status != IEEE80211_STATUS_SUCCESS )
01786                         goto fail;
01787 
01788                 DBGC ( dev, "802.11 %p associating\n", dev );
01789 
01790                 if ( dev->handshaker && dev->handshaker->start &&
01791                      ! dev->handshaker->started ) {
01792                         rc = dev->handshaker->start ( dev );
01793                         if ( rc < 0 )
01794                                 goto fail;
01795                         dev->handshaker->started = 1;
01796                 }
01797 
01798                 rc = net80211_send_assoc ( dev, dev->associating );
01799                 if ( rc )
01800                         goto fail;
01801 
01802                 return;
01803         }
01804 
01805         if ( ! ( dev->state & NET80211_CRYPTO_SYNCED ) ) {
01806                 /* state: crypto sync */
01807                 DBGC ( dev, "802.11 %p security handshaking\n", dev );
01808 
01809                 if ( ! dev->handshaker || ! dev->handshaker->step ) {
01810                         dev->state |= NET80211_CRYPTO_SYNCED;
01811                         return;
01812                 }
01813 
01814                 rc = dev->handshaker->step ( dev );
01815 
01816                 if ( rc < 0 ) {
01817                         /* Only record the returned error if we're
01818                            still marked as associated, because an
01819                            asynchronous error will have already been
01820                            reported to net80211_deauthenticate() and
01821                            assoc_rc thereby set. */
01822                         if ( dev->state & NET80211_ASSOCIATED )
01823                                 dev->assoc_rc = rc;
01824                         rc = 0;
01825                         goto fail;
01826                 }
01827 
01828                 if ( rc > 0 ) {
01829                         dev->assoc_rc = 0;
01830                         dev->state |= NET80211_CRYPTO_SYNCED;
01831                 }
01832                 return;
01833         }
01834 
01835         /* state: done! */
01836         netdev_link_up ( dev->netdev );
01837         dev->assoc_rc = 0;
01838         dev->state &= ~NET80211_WORKING;
01839 
01840         free ( dev->ctx.assoc );
01841         dev->ctx.assoc = NULL;
01842 
01843         net80211_free_wlan ( dev->associating );
01844         dev->associating = NULL;
01845 
01846         dev->rctl = rc80211_init ( dev );
01847 
01848         process_del ( &dev->proc_assoc );
01849 
01850         DBGC ( dev, "802.11 %p associated with %s (%s)\n", dev,
01851                dev->essid, eth_ntoa ( dev->bssid ) );
01852 
01853         return;
01854 
01855  fail:
01856         dev->state &= ~( NET80211_WORKING | NET80211_WAITING );
01857         if ( rc )
01858                 dev->assoc_rc = rc;
01859 
01860         netdev_link_err ( dev->netdev, dev->assoc_rc );
01861 
01862         /* We never reach here from the middle of a probe, so we don't
01863            need to worry about freeing dev->ctx.probe. */
01864 
01865         if ( dev->state & NET80211_PROBED ) {
01866                 free ( dev->ctx.assoc );
01867                 dev->ctx.assoc = NULL;
01868         }
01869 
01870         net80211_free_wlan ( dev->associating );
01871         dev->associating = NULL;
01872 
01873         process_del ( &dev->proc_assoc );
01874 
01875         DBGC ( dev, "802.11 %p association failed (state=%04x): "
01876                "%s\n", dev, dev->state, strerror ( dev->assoc_rc ) );
01877 
01878         /* Try it again: */
01879         net80211_autoassociate ( dev );
01880 }
01881 
01882 /**
01883  * Check for 802.11 SSID or key updates
01884  *
01885  * This acts as a settings applicator; if the user changes netX/ssid,
01886  * and netX is currently open, the association task will be invoked
01887  * again. If the user changes the encryption key, the current security
01888  * handshaker will be asked to update its state to match; if that is
01889  * impossible without reassociation, we reassociate.
01890  */
01891 static int net80211_check_settings_update ( void )
01892 {
01893         struct net80211_device *dev;
01894         char ssid[IEEE80211_MAX_SSID_LEN + 1];
01895         int key_reassoc;
01896 
01897         list_for_each_entry ( dev, &net80211_devices, list ) {
01898                 if ( ! netdev_is_open ( dev->netdev ) )
01899                         continue;
01900 
01901                 key_reassoc = 0;
01902                 if ( dev->handshaker && dev->handshaker->change_key &&
01903                      dev->handshaker->change_key ( dev ) < 0 )
01904                         key_reassoc = 1;
01905 
01906                 fetch_string_setting ( netdev_settings ( dev->netdev ),
01907                                        &net80211_ssid_setting, ssid,
01908                                        IEEE80211_MAX_SSID_LEN + 1 );
01909 
01910                 if ( key_reassoc ||
01911                      ( ! ( ! ssid[0] && ( dev->state & NET80211_AUTO_SSID ) ) &&
01912                        strcmp ( ssid, dev->essid ) != 0 ) ) {
01913                         DBGC ( dev, "802.11 %p updating association: "
01914                                "%s -> %s\n", dev, dev->essid, ssid );
01915                         net80211_autoassociate ( dev );
01916                 }
01917         }
01918 
01919         return 0;
01920 }
01921 
01922 /**
01923  * Start 802.11 association process
01924  *
01925  * @v dev       802.11 device
01926  *
01927  * If the association process is running, it will be restarted.
01928  */
01929 void net80211_autoassociate ( struct net80211_device *dev )
01930 {
01931         if ( ! ( dev->state & NET80211_WORKING ) ) {
01932                 DBGC2 ( dev, "802.11 %p spawning association process\n", dev );
01933                 process_add ( &dev->proc_assoc );
01934         } else {
01935                 DBGC2 ( dev, "802.11 %p restarting association\n", dev );
01936         }
01937 
01938         /* Clean up everything an earlier association process might
01939            have been in the middle of using */
01940         if ( dev->associating )
01941                 net80211_free_wlan ( dev->associating );
01942 
01943         if ( ! ( dev->state & NET80211_PROBED ) )
01944                 net80211_free_wlan (
01945                         net80211_probe_finish_best ( dev->ctx.probe ) );
01946         else
01947                 free ( dev->ctx.assoc );
01948 
01949         /* Reset to a clean state */
01950         fetch_string_setting ( netdev_settings ( dev->netdev ),
01951                                &net80211_ssid_setting, dev->essid,
01952                                IEEE80211_MAX_SSID_LEN + 1 );
01953         dev->ctx.probe = NULL;
01954         dev->associating = NULL;
01955         dev->assoc_rc = 0;
01956         net80211_set_state ( dev, NET80211_PROBED, NET80211_WORKING, 0 );
01957 }
01958 
01959 /**
01960  * Pick TX rate for RTS/CTS packets based on data rate
01961  *
01962  * @v dev       802.11 device
01963  *
01964  * The RTS/CTS rate is the fastest TX rate marked as "basic" that is
01965  * not faster than the data rate.
01966  */
01967 static void net80211_set_rtscts_rate ( struct net80211_device *dev )
01968 {
01969         u16 datarate = dev->rates[dev->rate];
01970         u16 rtsrate = 0;
01971         int rts_idx = -1;
01972         int i;
01973 
01974         for ( i = 0; i < dev->nr_rates; i++ ) {
01975                 u16 rate = dev->rates[i];
01976 
01977                 if ( ! ( dev->basic_rates & ( 1 << i ) ) || rate > datarate )
01978                         continue;
01979 
01980                 if ( rate > rtsrate ) {
01981                         rtsrate = rate;
01982                         rts_idx = i;
01983                 }
01984         }
01985 
01986         /* If this is in initialization, we might not have any basic
01987            rates; just use the first data rate in that case. */
01988         if ( rts_idx < 0 )
01989                 rts_idx = 0;
01990 
01991         dev->rtscts_rate = rts_idx;
01992 }
01993 
01994 /**
01995  * Set data transmission rate for 802.11 device
01996  *
01997  * @v dev       802.11 device
01998  * @v rate      Rate to set, as index into @c dev->rates array
01999  */
02000 void net80211_set_rate_idx ( struct net80211_device *dev, int rate )
02001 {
02002         assert ( netdev_is_open ( dev->netdev ) );
02003 
02004         if ( rate >= 0 && rate < dev->nr_rates && rate != dev->rate ) {
02005                 DBGC2 ( dev, "802.11 %p changing rate from %d->%d Mbps\n",
02006                         dev, dev->rates[dev->rate] / 10,
02007                         dev->rates[rate] / 10 );
02008 
02009                 dev->rate = rate;
02010                 net80211_set_rtscts_rate ( dev );
02011                 dev->op->config ( dev, NET80211_CFG_RATE );
02012         }
02013 }
02014 
02015 /**
02016  * Configure 802.11 device to transmit on a certain channel
02017  *
02018  * @v dev       802.11 device
02019  * @v channel   Channel number (1-11 for 2.4GHz) to transmit on
02020  */
02021 int net80211_change_channel ( struct net80211_device *dev, int channel )
02022 {
02023         int i, oldchan = dev->channel;
02024 
02025         assert ( netdev_is_open ( dev->netdev ) );
02026 
02027         for ( i = 0; i < dev->nr_channels; i++ ) {
02028                 if ( dev->channels[i].channel_nr == channel ) {
02029                         dev->channel = i;
02030                         break;
02031                 }
02032         }
02033 
02034         if ( i == dev->nr_channels )
02035                 return -ENOENT;
02036 
02037         if ( i != oldchan )
02038                 return dev->op->config ( dev, NET80211_CFG_CHANNEL );
02039 
02040         return 0;
02041 }
02042 
02043 /**
02044  * Prepare 802.11 device channel and rate set for scanning
02045  *
02046  * @v dev       802.11 device
02047  * @v band      RF band(s) on which to prepare for scanning
02048  * @v active    Whether the scanning will be active
02049  * @ret rc      Return status code
02050  */
02051 int net80211_prepare_probe ( struct net80211_device *dev, int band,
02052                              int active )
02053 {
02054         assert ( netdev_is_open ( dev->netdev ) );
02055 
02056         if ( active && ( band & NET80211_BAND_BIT_5GHZ ) ) {
02057                 DBGC ( dev, "802.11 %p cannot perform active scanning on "
02058                        "5GHz band\n", dev );
02059                 return -EINVAL_ACTIVE_SCAN;
02060         }
02061 
02062         if ( band == 0 ) {
02063                 /* This can happen for a 5GHz-only card with 5GHz
02064                    scanning masked out by an active request. */
02065                 DBGC ( dev, "802.11 %p asked to prepare for scanning nothing\n",
02066                        dev );
02067                 return -EINVAL_ACTIVE_SCAN;
02068         }
02069 
02070         dev->nr_channels = 0;
02071 
02072         if ( active )
02073                 net80211_add_channels ( dev, 1, 11, NET80211_REG_TXPOWER );
02074         else {
02075                 if ( band & NET80211_BAND_BIT_2GHZ )
02076                         net80211_add_channels ( dev, 1, 14,
02077                                                 NET80211_REG_TXPOWER );
02078                 if ( band & NET80211_BAND_BIT_5GHZ )
02079                         net80211_add_channels ( dev, 36, 8,
02080                                                 NET80211_REG_TXPOWER );
02081         }
02082 
02083         net80211_filter_hw_channels ( dev );
02084 
02085         /* Use channel 1 for now */
02086         dev->channel = 0;
02087         dev->op->config ( dev, NET80211_CFG_CHANNEL );
02088 
02089         /* Always do active probes at lowest (presumably first) speed */
02090         dev->rate = 0;
02091         dev->nr_rates = 1;
02092         dev->rates[0] = dev->hw->rates[dev->channels[0].band][0];
02093         dev->op->config ( dev, NET80211_CFG_RATE );
02094 
02095         return 0;
02096 }
02097 
02098 /**
02099  * Prepare 802.11 device channel and rate set for communication
02100  *
02101  * @v dev       802.11 device
02102  * @v wlan      WLAN to prepare for communication with
02103  * @ret rc      Return status code
02104  */
02105 int net80211_prepare_assoc ( struct net80211_device *dev,
02106                              struct net80211_wlan *wlan )
02107 {
02108         struct ieee80211_frame *hdr = wlan->beacon->data;
02109         struct ieee80211_beacon *beacon =
02110                 ( struct ieee80211_beacon * ) hdr->data;
02111         struct net80211_handshaker *handshaker;
02112         int rc;
02113 
02114         assert ( netdev_is_open ( dev->netdev ) );
02115 
02116         net80211_set_state ( dev, NET80211_ASSOCIATED, 0, 0 );
02117         memcpy ( dev->bssid, wlan->bssid, ETH_ALEN );
02118         strcpy ( dev->essid, wlan->essid );
02119 
02120         free ( dev->rsn_ie );
02121         dev->rsn_ie = NULL;
02122 
02123         dev->last_beacon_timestamp = beacon->timestamp;
02124         dev->tx_beacon_interval = 1024 * beacon->beacon_interval;
02125 
02126         /* Barring an IE that tells us the channel outright, assume
02127            the channel we heard this AP best on is the channel it's
02128            communicating on. */
02129         net80211_change_channel ( dev, wlan->channel );
02130 
02131         rc = net80211_process_capab ( dev, beacon->capability );
02132         if ( rc )
02133                 return rc;
02134 
02135         rc = net80211_process_ie ( dev, beacon->info_element,
02136                                    wlan->beacon->tail );
02137         if ( rc )
02138                 return rc;
02139 
02140         /* Associate at the lowest rate so we know it'll get through */
02141         dev->rate = 0;
02142         dev->op->config ( dev, NET80211_CFG_RATE );
02143 
02144         /* Free old handshaker and crypto, if they exist */
02145         if ( dev->handshaker && dev->handshaker->stop &&
02146              dev->handshaker->started )
02147                 dev->handshaker->stop ( dev );
02148         free ( dev->handshaker );
02149         dev->handshaker = NULL;
02150         free ( dev->crypto );
02151         free ( dev->gcrypto );
02152         dev->crypto = dev->gcrypto = NULL;
02153 
02154         /* Find new security handshaker to use */
02155         for_each_table_entry ( handshaker, NET80211_HANDSHAKERS ) {
02156                 if ( handshaker->protocol == wlan->handshaking ) {
02157                         dev->handshaker = zalloc ( sizeof ( *handshaker ) +
02158                                                    handshaker->priv_len );
02159                         if ( ! dev->handshaker )
02160                                 return -ENOMEM;
02161 
02162                         memcpy ( dev->handshaker, handshaker,
02163                                  sizeof ( *handshaker ) );
02164                         dev->handshaker->priv = ( ( void * ) dev->handshaker +
02165                                                   sizeof ( *handshaker ) );
02166                         break;
02167                 }
02168         }
02169 
02170         if ( ( wlan->handshaking != NET80211_SECPROT_NONE ) &&
02171              ! dev->handshaker ) {
02172                 DBGC ( dev, "802.11 %p no support for handshaking scheme %d\n",
02173                        dev, wlan->handshaking );
02174                 return -( ENOTSUP | ( wlan->handshaking << 8 ) );
02175         }
02176 
02177         /* Initialize security handshaker */
02178         if ( dev->handshaker ) {
02179                 rc = dev->handshaker->init ( dev );
02180                 if ( rc < 0 )
02181                         return rc;
02182         }
02183 
02184         return 0;
02185 }
02186 
02187 /**
02188  * Send 802.11 initial authentication frame
02189  *
02190  * @v dev       802.11 device
02191  * @v wlan      WLAN to authenticate with
02192  * @v method    Authentication method
02193  * @ret rc      Return status code
02194  *
02195  * @a method may be 0 for Open System authentication or 1 for Shared
02196  * Key authentication. Open System provides no security in association
02197  * whatsoever, relying on encryption for confidentiality, but Shared
02198  * Key actively introduces security problems and is very rarely used.
02199  */
02200 int net80211_send_auth ( struct net80211_device *dev,
02201                          struct net80211_wlan *wlan, int method )
02202 {
02203         struct io_buffer *iob = alloc_iob ( 64 );
02204         struct ieee80211_auth *auth;
02205 
02206         net80211_set_state ( dev, 0, NET80211_WAITING, 0 );
02207         iob_reserve ( iob, IEEE80211_TYP_FRAME_HEADER_LEN );
02208         auth = iob_put ( iob, sizeof ( *auth ) );
02209         auth->algorithm = method;
02210         auth->tx_seq = 1;
02211         auth->status = 0;
02212 
02213         return net80211_tx_mgmt ( dev, IEEE80211_STYPE_AUTH, wlan->bssid, iob );
02214 }
02215 
02216 /**
02217  * Handle receipt of 802.11 authentication frame
02218  *
02219  * @v dev       802.11 device
02220  * @v iob       I/O buffer
02221  *
02222  * If the authentication method being used is Shared Key, and the
02223  * frame that was received included challenge text, the frame is
02224  * encrypted using the cryptosystem currently in effect and sent back
02225  * to the AP to complete the authentication.
02226  */
02227 static void net80211_handle_auth ( struct net80211_device *dev,
02228                                    struct io_buffer *iob )
02229 {
02230         struct ieee80211_frame *hdr = iob->data;
02231         struct ieee80211_auth *auth =
02232             ( struct ieee80211_auth * ) hdr->data;
02233 
02234         if ( auth->tx_seq & 1 ) {
02235                 DBGC ( dev, "802.11 %p authentication received improperly "
02236                        "directed frame (seq. %d)\n", dev, auth->tx_seq );
02237                 net80211_set_state ( dev, NET80211_WAITING, 0,
02238                                      IEEE80211_STATUS_FAILURE );
02239                 return;
02240         }
02241 
02242         if ( auth->status != IEEE80211_STATUS_SUCCESS ) {
02243                 DBGC ( dev, "802.11 %p authentication failed: status %d\n",
02244                        dev, auth->status );
02245                 net80211_set_state ( dev, NET80211_WAITING, 0,
02246                                      auth->status );
02247                 return;
02248         }
02249 
02250         if ( auth->algorithm == IEEE80211_AUTH_SHARED_KEY && ! dev->crypto ) {
02251                 DBGC ( dev, "802.11 %p can't perform shared-key authentication "
02252                        "without a cryptosystem\n", dev );
02253                 net80211_set_state ( dev, NET80211_WAITING, 0,
02254                                      IEEE80211_STATUS_FAILURE );
02255                 return;
02256         }
02257 
02258         if ( auth->algorithm == IEEE80211_AUTH_SHARED_KEY &&
02259              auth->tx_seq == 2 ) {
02260                 /* Since the iob we got is going to be freed as soon
02261                    as we return, we can do some in-place
02262                    modification. */
02263                 auth->tx_seq = 3;
02264                 auth->status = 0;
02265 
02266                 memcpy ( hdr->addr2, hdr->addr1, ETH_ALEN );
02267                 memcpy ( hdr->addr1, hdr->addr3, ETH_ALEN );
02268 
02269                 netdev_tx ( dev->netdev,
02270                             dev->crypto->encrypt ( dev->crypto, iob ) );
02271                 return;
02272         }
02273 
02274         net80211_set_state ( dev, NET80211_WAITING, NET80211_AUTHENTICATED,
02275                              IEEE80211_STATUS_SUCCESS );
02276 
02277         return;
02278 }
02279 
02280 /**
02281  * Send 802.11 association frame
02282  *
02283  * @v dev       802.11 device
02284  * @v wlan      WLAN to associate with
02285  * @ret rc      Return status code
02286  */
02287 int net80211_send_assoc ( struct net80211_device *dev,
02288                           struct net80211_wlan *wlan )
02289 {
02290         struct io_buffer *iob = alloc_iob ( 128 );
02291         struct ieee80211_assoc_req *assoc;
02292         union ieee80211_ie *ie;
02293 
02294         net80211_set_state ( dev, 0, NET80211_WAITING, 0 );
02295 
02296         iob_reserve ( iob, IEEE80211_TYP_FRAME_HEADER_LEN );
02297         assoc = iob->data;
02298 
02299         assoc->capability = IEEE80211_CAPAB_MANAGED;
02300         if ( ! ( dev->hw->flags & NET80211_HW_NO_SHORT_PREAMBLE ) )
02301                 assoc->capability |= IEEE80211_CAPAB_SHORT_PMBL;
02302         if ( ! ( dev->hw->flags & NET80211_HW_NO_SHORT_SLOT ) )
02303                 assoc->capability |= IEEE80211_CAPAB_SHORT_SLOT;
02304         if ( wlan->crypto )
02305                 assoc->capability |= IEEE80211_CAPAB_PRIVACY;
02306 
02307         assoc->listen_interval = 1;
02308 
02309         ie = net80211_marshal_request_info ( dev, assoc->info_element );
02310 
02311         DBGP ( "802.11 %p about to send association request:\n", dev );
02312         DBGP_HD ( iob->data, ( void * ) ie - iob->data );
02313 
02314         iob_put ( iob, ( void * ) ie - iob->data );
02315 
02316         return net80211_tx_mgmt ( dev, IEEE80211_STYPE_ASSOC_REQ,
02317                                   wlan->bssid, iob );
02318 }
02319 
02320 /**
02321  * Handle receipt of 802.11 association reply frame
02322  *
02323  * @v dev       802.11 device
02324  * @v iob       I/O buffer
02325  */
02326 static void net80211_handle_assoc_reply ( struct net80211_device *dev,
02327                                           struct io_buffer *iob )
02328 {
02329         struct ieee80211_frame *hdr = iob->data;
02330         struct ieee80211_assoc_resp *assoc =
02331                 ( struct ieee80211_assoc_resp * ) hdr->data;
02332 
02333         net80211_process_capab ( dev, assoc->capability );
02334         net80211_process_ie ( dev, assoc->info_element, iob->tail );
02335 
02336         if ( assoc->status != IEEE80211_STATUS_SUCCESS ) {
02337                 DBGC ( dev, "802.11 %p association failed: status %d\n",
02338                        dev, assoc->status );
02339                 net80211_set_state ( dev, NET80211_WAITING, 0,
02340                                      assoc->status );
02341                 return;
02342         }
02343 
02344         /* ESSID was filled before the association request was sent */
02345         memcpy ( dev->bssid, hdr->addr3, ETH_ALEN );
02346         dev->aid = assoc->aid;
02347 
02348         net80211_set_state ( dev, NET80211_WAITING, NET80211_ASSOCIATED,
02349                              IEEE80211_STATUS_SUCCESS );
02350 }
02351 
02352 
02353 /**
02354  * Send 802.11 disassociation frame
02355  *
02356  * @v dev       802.11 device
02357  * @v reason    Reason for disassociation
02358  * @v deauth    If TRUE, send deauthentication instead of disassociation
02359  * @ret rc      Return status code
02360  */
02361 static int net80211_send_disassoc ( struct net80211_device *dev, int reason,
02362                                     int deauth )
02363 {
02364         struct io_buffer *iob = alloc_iob ( 64 );
02365         struct ieee80211_disassoc *disassoc;
02366 
02367         if ( ! ( dev->state & NET80211_ASSOCIATED ) )
02368                 return -EINVAL;
02369 
02370         net80211_set_state ( dev, NET80211_ASSOCIATED, 0, 0 );
02371         iob_reserve ( iob, IEEE80211_TYP_FRAME_HEADER_LEN );
02372         disassoc = iob_put ( iob, sizeof ( *disassoc ) );
02373         disassoc->reason = reason;
02374 
02375         return net80211_tx_mgmt ( dev, deauth ? IEEE80211_STYPE_DEAUTH :
02376                                   IEEE80211_STYPE_DISASSOC, dev->bssid, iob );
02377 }
02378 
02379 
02380 /**
02381  * Deauthenticate from current network and try again
02382  *
02383  * @v dev       802.11 device
02384  * @v rc        Return status code indicating reason
02385  *
02386  * The deauthentication will be sent using an 802.11 "unspecified
02387  * reason", as is common, but @a rc will be set as a link-up
02388  * error to aid the user in debugging.
02389  */
02390 void net80211_deauthenticate ( struct net80211_device *dev, int rc )
02391 {
02392         net80211_send_disassoc ( dev, IEEE80211_REASON_UNSPECIFIED, 1 );
02393         dev->assoc_rc = rc;
02394         netdev_link_err ( dev->netdev, rc );
02395 
02396         net80211_autoassociate ( dev );
02397 }
02398 
02399 
02400 /** Smoothing factor (1-7) for link quality calculation */
02401 #define LQ_SMOOTH       7
02402 
02403 /**
02404  * Update link quality information based on received beacon
02405  *
02406  * @v dev       802.11 device
02407  * @v iob       I/O buffer containing beacon
02408  * @ret rc      Return status code
02409  */
02410 static void net80211_update_link_quality ( struct net80211_device *dev,
02411                                            struct io_buffer *iob )
02412 {
02413         struct ieee80211_frame *hdr = iob->data;
02414         struct ieee80211_beacon *beacon;
02415         u32 dt, rxi;
02416 
02417         if ( ! ( dev->state & NET80211_ASSOCIATED ) )
02418                 return;
02419 
02420         beacon = ( struct ieee80211_beacon * ) hdr->data;
02421         dt = ( u32 ) ( beacon->timestamp - dev->last_beacon_timestamp );
02422         rxi = dev->rx_beacon_interval;
02423 
02424         rxi = ( LQ_SMOOTH * rxi ) + ( ( 8 - LQ_SMOOTH ) * dt );
02425         dev->rx_beacon_interval = rxi >> 3;
02426 
02427         dev->last_beacon_timestamp = beacon->timestamp;
02428 }
02429 
02430 
02431 /**
02432  * Handle receipt of 802.11 management frame
02433  *
02434  * @v dev       802.11 device
02435  * @v iob       I/O buffer
02436  * @v signal    Signal strength of received frame
02437  */
02438 static void net80211_handle_mgmt ( struct net80211_device *dev,
02439                                    struct io_buffer *iob, int signal )
02440 {
02441         struct ieee80211_frame *hdr = iob->data;
02442         struct ieee80211_disassoc *disassoc;
02443         u16 stype = hdr->fc & IEEE80211_FC_SUBTYPE;
02444         int keep = 0;
02445         int is_deauth = ( stype == IEEE80211_STYPE_DEAUTH );
02446 
02447         if ( ( hdr->fc & IEEE80211_FC_TYPE ) != IEEE80211_TYPE_MGMT ) {
02448                 free_iob ( iob );
02449                 return;         /* only handle management frames */
02450         }
02451 
02452         switch ( stype ) {
02453                 /* We reconnect on deauthentication and disassociation. */
02454         case IEEE80211_STYPE_DEAUTH:
02455         case IEEE80211_STYPE_DISASSOC:
02456                 disassoc = ( struct ieee80211_disassoc * ) hdr->data;
02457                 net80211_set_state ( dev, is_deauth ? NET80211_AUTHENTICATED :
02458                                      NET80211_ASSOCIATED, 0,
02459                                      NET80211_IS_REASON | disassoc->reason );
02460                 DBGC ( dev, "802.11 %p %s: reason %d\n",
02461                        dev, is_deauth ? "deauthenticated" : "disassociated",
02462                        disassoc->reason );
02463 
02464                 /* Try to reassociate, in case it's transient. */
02465                 net80211_autoassociate ( dev );
02466 
02467                 break;
02468 
02469                 /* We handle authentication and association. */
02470         case IEEE80211_STYPE_AUTH:
02471                 if ( ! ( dev->state & NET80211_AUTHENTICATED ) )
02472                         net80211_handle_auth ( dev, iob );
02473                 break;
02474 
02475         case IEEE80211_STYPE_ASSOC_RESP:
02476         case IEEE80211_STYPE_REASSOC_RESP:
02477                 if ( ! ( dev->state & NET80211_ASSOCIATED ) )
02478                         net80211_handle_assoc_reply ( dev, iob );
02479                 break;
02480 
02481                 /* We pass probes and beacons onto network scanning
02482                    code. Pass actions for future extensibility. */
02483         case IEEE80211_STYPE_BEACON:
02484                 net80211_update_link_quality ( dev, iob );
02485                 /* fall through */
02486         case IEEE80211_STYPE_PROBE_RESP:
02487         case IEEE80211_STYPE_ACTION:
02488                 if ( dev->keep_mgmt ) {
02489                         struct net80211_rx_info *rxinf;
02490                         rxinf = zalloc ( sizeof ( *rxinf ) );
02491                         if ( ! rxinf ) {
02492                                 DBGC ( dev, "802.11 %p out of memory\n", dev );
02493                                 break;
02494                         }
02495                         rxinf->signal = signal;
02496                         list_add_tail ( &iob->list, &dev->mgmt_queue );
02497                         list_add_tail ( &rxinf->list, &dev->mgmt_info_queue );
02498                         keep = 1;
02499                 }
02500                 break;
02501 
02502         case IEEE80211_STYPE_PROBE_REQ:
02503                 /* Some nodes send these broadcast. Ignore them. */
02504                 break;
02505 
02506         case IEEE80211_STYPE_ASSOC_REQ:
02507         case IEEE80211_STYPE_REASSOC_REQ:
02508                 /* We should never receive these, only send them. */
02509                 DBGC ( dev, "802.11 %p received strange management request "
02510                        "(%04x)\n", dev, stype );
02511                 break;
02512 
02513         default:
02514                 DBGC ( dev, "802.11 %p received unimplemented management "
02515                        "packet (%04x)\n", dev, stype );
02516                 break;
02517         }
02518 
02519         if ( ! keep )
02520                 free_iob ( iob );
02521 }
02522 
02523 /* ---------- Packet handling functions ---------- */
02524 
02525 /**
02526  * Free buffers used by 802.11 fragment cache entry
02527  *
02528  * @v dev       802.11 device
02529  * @v fcid      Fragment cache entry index
02530  *
02531  * After this function, the referenced entry will be marked unused.
02532  */
02533 static void net80211_free_frags ( struct net80211_device *dev, int fcid )
02534 {
02535         int j;
02536         struct net80211_frag_cache *frag = &dev->frags[fcid];
02537 
02538         for ( j = 0; j < 16; j++ ) {
02539                 if ( frag->iob[j] ) {
02540                         free_iob ( frag->iob[j] );
02541                         frag->iob[j] = NULL;
02542                 }
02543         }
02544 
02545         frag->seqnr = 0;
02546         frag->start_ticks = 0;
02547         frag->in_use = 0;
02548 }
02549 
02550 /**
02551  * Accumulate 802.11 fragments into one I/O buffer
02552  *
02553  * @v dev       802.11 device
02554  * @v fcid      Fragment cache entry index
02555  * @v nfrags    Number of fragments received
02556  * @v size      Sum of sizes of all fragments, including headers
02557  * @ret iob     I/O buffer containing reassembled packet
02558  *
02559  * This function does not free the fragment buffers.
02560  */
02561 static struct io_buffer *net80211_accum_frags ( struct net80211_device *dev,
02562                                                 int fcid, int nfrags, int size )
02563 {
02564         struct net80211_frag_cache *frag = &dev->frags[fcid];
02565         int hdrsize = IEEE80211_TYP_FRAME_HEADER_LEN;
02566         int nsize = size - hdrsize * ( nfrags - 1 );
02567         int i;
02568 
02569         struct io_buffer *niob = alloc_iob ( nsize );
02570         struct ieee80211_frame *hdr;
02571 
02572         /* Add the header from the first one... */
02573         memcpy ( iob_put ( niob, hdrsize ), frag->iob[0]->data, hdrsize );
02574 
02575         /* ... and all the data from all of them. */
02576         for ( i = 0; i < nfrags; i++ ) {
02577                 int len = iob_len ( frag->iob[i] ) - hdrsize;
02578                 memcpy ( iob_put ( niob, len ),
02579                          frag->iob[i]->data + hdrsize, len );
02580         }
02581 
02582         /* Turn off the fragment bit. */
02583         hdr = niob->data;
02584         hdr->fc &= ~IEEE80211_FC_MORE_FRAG;
02585 
02586         return niob;
02587 }
02588 
02589 /**
02590  * Handle receipt of 802.11 fragment
02591  *
02592  * @v dev       802.11 device
02593  * @v iob       I/O buffer containing fragment
02594  * @v signal    Signal strength with which fragment was received
02595  */
02596 static void net80211_rx_frag ( struct net80211_device *dev,
02597                                struct io_buffer *iob, int signal )
02598 {
02599         struct ieee80211_frame *hdr = iob->data;
02600         int fragnr = IEEE80211_FRAG ( hdr->seq );
02601 
02602         if ( fragnr == 0 && ( hdr->fc & IEEE80211_FC_MORE_FRAG ) ) {
02603                 /* start a frag cache entry */
02604                 int i, newest = -1;
02605                 u32 curr_ticks = currticks(), newest_ticks = 0;
02606                 u32 timeout = TICKS_PER_SEC * NET80211_FRAG_TIMEOUT;
02607 
02608                 for ( i = 0; i < NET80211_NR_CONCURRENT_FRAGS; i++ ) {
02609                         if ( dev->frags[i].in_use == 0 )
02610                                 break;
02611 
02612                         if ( dev->frags[i].start_ticks + timeout >=
02613                              curr_ticks ) {
02614                                 net80211_free_frags ( dev, i );
02615                                 break;
02616                         }
02617 
02618                         if ( dev->frags[i].start_ticks > newest_ticks ) {
02619                                 newest = i;
02620                                 newest_ticks = dev->frags[i].start_ticks;
02621                         }
02622                 }
02623 
02624                 /* If we're being sent more concurrent fragmented
02625                    packets than we can handle, drop the newest so the
02626                    older ones have time to complete. */
02627                 if ( i == NET80211_NR_CONCURRENT_FRAGS ) {
02628                         i = newest;
02629                         net80211_free_frags ( dev, i );
02630                 }
02631 
02632                 dev->frags[i].in_use = 1;
02633                 dev->frags[i].seqnr = IEEE80211_SEQNR ( hdr->seq );
02634                 dev->frags[i].start_ticks = currticks();
02635                 dev->frags[i].iob[0] = iob;
02636                 return;
02637         } else {
02638                 int i;
02639                 for ( i = 0; i < NET80211_NR_CONCURRENT_FRAGS; i++ ) {
02640                         if ( dev->frags[i].in_use && dev->frags[i].seqnr ==
02641                              IEEE80211_SEQNR ( hdr->seq ) )
02642                                 break;
02643                 }
02644                 if ( i == NET80211_NR_CONCURRENT_FRAGS ) {
02645                         /* Drop non-first not-in-cache fragments */
02646                         DBGC ( dev, "802.11 %p dropped fragment fc=%04x "
02647                                "seq=%04x\n", dev, hdr->fc, hdr->seq );
02648                         free_iob ( iob );
02649                         return;
02650                 }
02651 
02652                 dev->frags[i].iob[fragnr] = iob;
02653 
02654                 if ( ! ( hdr->fc & IEEE80211_FC_MORE_FRAG ) ) {
02655                         int j, size = 0;
02656                         for ( j = 0; j < fragnr; j++ ) {
02657                                 size += iob_len ( dev->frags[i].iob[j] );
02658                                 if ( dev->frags[i].iob[j] == NULL )
02659                                         break;
02660                         }
02661                         if ( j == fragnr ) {
02662                                 /* We've got everything */
02663                                 struct io_buffer *niob =
02664                                     net80211_accum_frags ( dev, i, fragnr,
02665                                                            size );
02666                                 net80211_free_frags ( dev, i );
02667                                 net80211_rx ( dev, niob, signal, 0 );
02668                         } else {
02669                                 DBGC ( dev, "802.11 %p dropping fragmented "
02670                                        "packet due to out-of-order arrival, "
02671                                        "fc=%04x seq=%04x\n", dev, hdr->fc,
02672                                        hdr->seq );
02673                                 net80211_free_frags ( dev, i );
02674                         }
02675                 }
02676         }
02677 }
02678 
02679 /**
02680  * Handle receipt of 802.11 frame
02681  *
02682  * @v dev       802.11 device
02683  * @v iob       I/O buffer
02684  * @v signal    Received signal strength
02685  * @v rate      Bitrate at which frame was received, in 100 kbps units
02686  *
02687  * If the rate or signal is unknown, 0 should be passed.
02688  */
02689 void net80211_rx ( struct net80211_device *dev, struct io_buffer *iob,
02690                    int signal, u16 rate )
02691 {
02692         struct ieee80211_frame *hdr = iob->data;
02693         u16 type = hdr->fc & IEEE80211_FC_TYPE;
02694         if ( ( hdr->fc & IEEE80211_FC_VERSION ) != IEEE80211_THIS_VERSION )
02695                 goto drop;      /* drop invalid-version packets */
02696 
02697         if ( type == IEEE80211_TYPE_CTRL )
02698                 goto drop;      /* we don't handle control packets,
02699                                    the hardware does */
02700 
02701         if ( dev->last_rx_seq == hdr->seq )
02702                 goto drop;      /* avoid duplicate packet */
02703         dev->last_rx_seq = hdr->seq;
02704 
02705         if ( dev->hw->flags & NET80211_HW_RX_HAS_FCS ) {
02706                 /* discard the FCS */
02707                 iob_unput ( iob, 4 );
02708         }
02709 
02710         /* Only decrypt packets from our BSSID, to avoid spurious errors */
02711         if ( ( hdr->fc & IEEE80211_FC_PROTECTED ) &&
02712              ! memcmp ( hdr->addr2, dev->bssid, ETH_ALEN ) ) {
02713                 /* Decrypt packet; record and drop if it fails */
02714                 struct io_buffer *niob;
02715                 struct net80211_crypto *crypto = dev->crypto;
02716 
02717                 if ( ! dev->crypto ) {
02718                         DBGC ( dev, "802.11 %p cannot decrypt packet "
02719                                "without a cryptosystem\n", dev );
02720                         goto drop_crypt;
02721                 }
02722 
02723                 if ( ( hdr->addr1[0] & 1 ) && dev->gcrypto ) {
02724                         /* Use group decryption if needed */
02725                         crypto = dev->gcrypto;
02726                 }
02727 
02728                 niob = crypto->decrypt ( crypto, iob );
02729                 if ( ! niob ) {
02730                         DBGC ( dev, "802.11 %p decryption error\n", dev );
02731                         goto drop_crypt;
02732                 }
02733                 free_iob ( iob );
02734                 iob = niob;
02735                 hdr = iob->data;
02736         }
02737 
02738         dev->last_signal = signal;
02739 
02740         /* Fragments go into the frag cache or get dropped. */
02741         if ( IEEE80211_FRAG ( hdr->seq ) != 0
02742              || ( hdr->fc & IEEE80211_FC_MORE_FRAG ) ) {
02743                 net80211_rx_frag ( dev, iob, signal );
02744                 return;
02745         }
02746 
02747         /* Management frames get handled, enqueued, or dropped. */
02748         if ( type == IEEE80211_TYPE_MGMT ) {
02749                 net80211_handle_mgmt ( dev, iob, signal );
02750                 return;
02751         }
02752 
02753         /* Data frames get dropped or sent to the net_device. */
02754         if ( ( hdr->fc & IEEE80211_FC_SUBTYPE ) != IEEE80211_STYPE_DATA )
02755                 goto drop;      /* drop QoS, CFP, or null data packets */
02756 
02757         /* Update rate-control algorithm */
02758         if ( dev->rctl )
02759                 rc80211_update_rx ( dev, hdr->fc & IEEE80211_FC_RETRY, rate );
02760 
02761         /* Pass packet onward */
02762         if ( dev->state & NET80211_ASSOCIATED ) {
02763                 netdev_rx ( dev->netdev, iob );
02764                 return;
02765         }
02766 
02767         /* No association? Drop it. */
02768         goto drop;
02769 
02770  drop_crypt:
02771         netdev_rx_err ( dev->netdev, NULL, EINVAL_CRYPTO_REQUEST );
02772  drop:
02773         DBGC2 ( dev, "802.11 %p dropped packet fc=%04x seq=%04x\n", dev,
02774                 hdr->fc, hdr->seq );
02775         free_iob ( iob );
02776         return;
02777 }
02778 
02779 /** Indicate an error in receiving a packet
02780  *
02781  * @v dev       802.11 device
02782  * @v iob       I/O buffer with received packet, or NULL
02783  * @v rc        Error code
02784  *
02785  * This logs the error with the wrapping net_device, and frees iob if
02786  * it is passed.
02787  */
02788 void net80211_rx_err ( struct net80211_device *dev,
02789                        struct io_buffer *iob, int rc )
02790 {
02791         netdev_rx_err ( dev->netdev, iob, rc );
02792 }
02793 
02794 /** Indicate the completed transmission of a packet
02795  *
02796  * @v dev       802.11 device
02797  * @v iob       I/O buffer of transmitted packet
02798  * @v retries   Number of times this packet was retransmitted
02799  * @v rc        Error code, or 0 for success
02800  *
02801  * This logs an error with the wrapping net_device if one occurred,
02802  * and removes and frees the I/O buffer from its TX queue. The
02803  * provided retry information is used to tune our transmission rate.
02804  *
02805  * If the packet did not need to be retransmitted because it was
02806  * properly ACKed the first time, @a retries should be 0.
02807  */
02808 void net80211_tx_complete ( struct net80211_device *dev,
02809                             struct io_buffer *iob, int retries, int rc )
02810 {
02811         /* Update rate-control algorithm */
02812         if ( dev->rctl )
02813                 rc80211_update_tx ( dev, retries, rc );
02814 
02815         /* Pass completion onward */
02816         netdev_tx_complete_err ( dev->netdev, iob, rc );
02817 }
02818 
02819 /** Common 802.11 errors */
02820 struct errortab common_wireless_errors[] __errortab = {
02821         __einfo_errortab ( EINFO_EINVAL_CRYPTO_REQUEST ),
02822         __einfo_errortab ( EINFO_ECONNRESET_UNSPECIFIED ),
02823         __einfo_errortab ( EINFO_ECONNRESET_INACTIVITY ),
02824         __einfo_errortab ( EINFO_ECONNRESET_4WAY_TIMEOUT ),
02825         __einfo_errortab ( EINFO_ECONNRESET_8021X_FAILURE ),
02826         __einfo_errortab ( EINFO_ECONNREFUSED_FAILURE ),
02827         __einfo_errortab ( EINFO_ECONNREFUSED_ASSOC_DENIED ),
02828         __einfo_errortab ( EINFO_ECONNREFUSED_AUTH_ALGO_UNSUPP ),
02829 };
02830 
02831 /* Drag in objects via net80211_ll_protocol */
02832 REQUIRING_SYMBOL ( net80211_ll_protocol );
02833 
02834 /* Drag in 802.11 configuration */
02835 REQUIRE_OBJECT ( config_net80211 );