Add qemu 2.4.0
[kvmfornfv.git] / qemu / roms / ipxe / src / net / 80211 / net80211.c
1 /*
2  * The iPXE 802.11 MAC layer.
3  *
4  * Copyright (c) 2009 Joshua Oreman <oremanj@rwcr.net>.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or any later version.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19  * 02110-1301, USA.
20  */
21
22 FILE_LICENCE ( GPL2_OR_LATER );
23
24 #include <string.h>
25 #include <byteswap.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <errno.h>
29 #include <ipxe/settings.h>
30 #include <ipxe/if_arp.h>
31 #include <ipxe/ethernet.h>
32 #include <ipxe/ieee80211.h>
33 #include <ipxe/netdevice.h>
34 #include <ipxe/net80211.h>
35 #include <ipxe/sec80211.h>
36 #include <ipxe/timer.h>
37 #include <ipxe/nap.h>
38 #include <ipxe/errortab.h>
39 #include <ipxe/net80211_err.h>
40
41 /** @file
42  *
43  * 802.11 device management
44  */
45
46 /** List of 802.11 devices */
47 static struct list_head net80211_devices = LIST_HEAD_INIT ( net80211_devices );
48
49 /** Set of device operations that does nothing */
50 static struct net80211_device_operations net80211_null_ops;
51
52 /** Information associated with a received management packet
53  *
54  * This is used to keep beacon signal strengths in a parallel queue to
55  * the beacons themselves.
56  */
57 struct net80211_rx_info {
58         int signal;
59         struct list_head list;
60 };
61
62 /** Context for a probe operation */
63 struct net80211_probe_ctx {
64         /** 802.11 device to probe on */
65         struct net80211_device *dev;
66
67         /** Value of keep_mgmt before probe was started */
68         int old_keep_mgmt;
69
70         /** If scanning actively, pointer to probe packet to send */
71         struct io_buffer *probe;
72
73         /** If non-"", the ESSID to limit ourselves to */
74         const char *essid;
75
76         /** Time probe was started */
77         u32 ticks_start;
78
79         /** Time last useful beacon was received */
80         u32 ticks_beacon;
81
82         /** Time channel was last changed */
83         u32 ticks_channel;
84
85         /** Time to stay on each channel */
86         u32 hop_time;
87
88         /** Channels to hop by when changing channel */
89         int hop_step;
90
91         /** List of best beacons for each network found so far */
92         struct list_head *beacons;
93 };
94
95 /** Context for the association task */
96 struct net80211_assoc_ctx {
97         /** Next authentication method to try using */
98         int method;
99
100         /** Time (in ticks) of the last sent association-related packet */
101         int last_packet;
102
103         /** Number of times we have tried sending it */
104         int times_tried;
105 };
106
107 /**
108  * Detect secure 802.11 network when security support is not available
109  *
110  * @return -ENOTSUP, always.
111  */
112 __weak int sec80211_detect ( struct io_buffer *iob __unused,
113                              enum net80211_security_proto *secprot __unused,
114                              enum net80211_crypto_alg *crypt __unused ) {
115         return -ENOTSUP;
116 }
117
118 /**
119  * @defgroup net80211_netdev Network device interface functions
120  * @{
121  */
122 static int net80211_netdev_open ( struct net_device *netdev );
123 static void net80211_netdev_close ( struct net_device *netdev );
124 static int net80211_netdev_transmit ( struct net_device *netdev,
125                                       struct io_buffer *iobuf );
126 static void net80211_netdev_poll ( struct net_device *netdev );
127 static void net80211_netdev_irq ( struct net_device *netdev, int enable );
128 /** @} */
129
130 /**
131  * @defgroup net80211_linklayer 802.11 link-layer protocol functions
132  * @{
133  */
134 static int net80211_ll_push ( struct net_device *netdev,
135                               struct io_buffer *iobuf, const void *ll_dest,
136                               const void *ll_source, uint16_t net_proto );
137 static int net80211_ll_pull ( struct net_device *netdev,
138                               struct io_buffer *iobuf, const void **ll_dest,
139                               const void **ll_source, uint16_t * net_proto,
140                               unsigned int *flags );
141 /** @} */
142
143 /**
144  * @defgroup net80211_help 802.11 helper functions
145  * @{
146  */
147 static void net80211_add_channels ( struct net80211_device *dev, int start,
148                                     int len, int txpower );
149 static void net80211_filter_hw_channels ( struct net80211_device *dev );
150 static void net80211_set_rtscts_rate ( struct net80211_device *dev );
151 static int net80211_process_capab ( struct net80211_device *dev,
152                                     u16 capab );
153 static int net80211_process_ie ( struct net80211_device *dev,
154                                  union ieee80211_ie *ie, void *ie_end );
155 static union ieee80211_ie *
156 net80211_marshal_request_info ( struct net80211_device *dev,
157                                 union ieee80211_ie *ie );
158 /** @} */
159
160 /**
161  * @defgroup net80211_assoc_ll 802.11 association handling functions
162  * @{
163  */
164 static void net80211_step_associate ( struct net80211_device *dev );
165 static void net80211_handle_auth ( struct net80211_device *dev,
166                                    struct io_buffer *iob );
167 static void net80211_handle_assoc_reply ( struct net80211_device *dev,
168                                           struct io_buffer *iob );
169 static int net80211_send_disassoc ( struct net80211_device *dev, int reason,
170                                     int deauth );
171 static void net80211_handle_mgmt ( struct net80211_device *dev,
172                                    struct io_buffer *iob, int signal );
173 /** @} */
174
175 /**
176  * @defgroup net80211_frag 802.11 fragment handling functions
177  * @{
178  */
179 static void net80211_free_frags ( struct net80211_device *dev, int fcid );
180 static struct io_buffer *net80211_accum_frags ( struct net80211_device *dev,
181                                                 int fcid, int nfrags, int size );
182 static void net80211_rx_frag ( struct net80211_device *dev,
183                                struct io_buffer *iob, int signal );
184 /** @} */
185
186 /**
187  * @defgroup net80211_settings 802.11 settings handlers
188  * @{
189  */
190 static int net80211_check_settings_update ( void );
191
192 /** 802.11 settings applicator
193  *
194  * When the SSID is changed, this will cause any open devices to
195  * re-associate; when the encryption key is changed, we similarly
196  * update their state.
197  */
198 struct settings_applicator net80211_applicator __settings_applicator = {
199         .apply = net80211_check_settings_update,
200 };
201
202 /** The network name to associate with
203  *
204  * If this is blank, we scan for all networks and use the one with the
205  * greatest signal strength.
206  */
207 const struct setting net80211_ssid_setting __setting ( SETTING_NETDEV_EXTRA,
208                                                        ssid ) = {
209         .name = "ssid",
210         .description = "Wireless SSID",
211         .type = &setting_type_string,
212 };
213
214 /** Whether to use active scanning
215  *
216  * In order to associate with a hidden SSID, it's necessary to use an
217  * active scan (send probe packets). If this setting is nonzero, an
218  * active scan on the 2.4GHz band will be used to associate.
219  */
220 const struct setting net80211_active_setting __setting ( SETTING_NETDEV_EXTRA,
221                                                          active-scan ) = {
222         .name = "active-scan",
223         .description = "Actively scan for wireless networks",
224         .type = &setting_type_int8,
225 };
226
227 /** The cryptographic key to use
228  *
229  * For hex WEP keys, as is common, this must be entered using the
230  * normal iPXE method for entering hex settings; an ASCII string of
231  * hex characters will not behave as expected.
232  */
233 const struct setting net80211_key_setting __setting ( SETTING_NETDEV_EXTRA,
234                                                       key ) = {
235         .name = "key",
236         .description = "Wireless encryption key",
237         .type = &setting_type_string,
238 };
239
240 /** @} */
241
242
243 /* ---------- net_device wrapper ---------- */
244
245 /**
246  * Open 802.11 device and start association
247  *
248  * @v netdev    Wrapping network device
249  * @ret rc      Return status code
250  *
251  * This sets up a default conservative set of channels for probing,
252  * and starts the auto-association task unless the @c
253  * NET80211_NO_ASSOC flag is set in the wrapped 802.11 device's @c
254  * state field.
255  */
256 static int net80211_netdev_open ( struct net_device *netdev )
257 {
258         struct net80211_device *dev = netdev->priv;
259         int rc = 0;
260
261         if ( dev->op == &net80211_null_ops )
262                 return -EFAULT;
263
264         if ( dev->op->open )
265                 rc = dev->op->open ( dev );
266
267         if ( rc < 0 )
268                 return rc;
269
270         if ( ! ( dev->state & NET80211_NO_ASSOC ) )
271                 net80211_autoassociate ( dev );
272
273         return 0;
274 }
275
276 /**
277  * Close 802.11 device
278  *
279  * @v netdev    Wrapping network device.
280  *
281  * If the association task is running, this will stop it.
282  */
283 static void net80211_netdev_close ( struct net_device *netdev )
284 {
285         struct net80211_device *dev = netdev->priv;
286
287         if ( dev->state & NET80211_WORKING )
288                 process_del ( &dev->proc_assoc );
289
290         /* Send disassociation frame to AP, to be polite */
291         if ( dev->state & NET80211_ASSOCIATED )
292                 net80211_send_disassoc ( dev, IEEE80211_REASON_LEAVING, 0 );
293
294         if ( dev->handshaker && dev->handshaker->stop &&
295              dev->handshaker->started )
296                 dev->handshaker->stop ( dev );
297
298         free ( dev->crypto );
299         free ( dev->handshaker );
300         dev->crypto = NULL;
301         dev->handshaker = NULL;
302
303         netdev_link_down ( netdev );
304         dev->state = 0;
305
306         if ( dev->op->close )
307                 dev->op->close ( dev );
308 }
309
310 /**
311  * Transmit packet on 802.11 device
312  *
313  * @v netdev    Wrapping network device
314  * @v iobuf     I/O buffer
315  * @ret rc      Return status code
316  *
317  * If encryption is enabled for the currently associated network, the
318  * packet will be encrypted prior to transmission.
319  */
320 static int net80211_netdev_transmit ( struct net_device *netdev,
321                                       struct io_buffer *iobuf )
322 {
323         struct net80211_device *dev = netdev->priv;
324         struct ieee80211_frame *hdr = iobuf->data;
325         int rc = -ENOSYS;
326
327         if ( dev->crypto && ! ( hdr->fc & IEEE80211_FC_PROTECTED ) &&
328              ( ( hdr->fc & IEEE80211_FC_TYPE ) == IEEE80211_TYPE_DATA ) ) {
329                 struct io_buffer *niob = dev->crypto->encrypt ( dev->crypto,
330                                                                 iobuf );
331                 if ( ! niob )
332                         return -ENOMEM; /* only reason encryption could fail */
333
334                 /* Free the non-encrypted iob */
335                 netdev_tx_complete ( netdev, iobuf );
336
337                 /* Transmit the encrypted iob; the Protected flag is
338                    set, so we won't recurse into here again */
339                 netdev_tx ( netdev, niob );
340
341                 /* Don't transmit the freed packet */
342                 return 0;
343         }
344
345         if ( dev->op->transmit )
346                 rc = dev->op->transmit ( dev, iobuf );
347
348         return rc;
349 }
350
351 /**
352  * Poll 802.11 device for received packets and completed transmissions
353  *
354  * @v netdev    Wrapping network device
355  */
356 static void net80211_netdev_poll ( struct net_device *netdev )
357 {
358         struct net80211_device *dev = netdev->priv;
359
360         if ( dev->op->poll )
361                 dev->op->poll ( dev );
362 }
363
364 /**
365  * Enable or disable interrupts for 802.11 device
366  *
367  * @v netdev    Wrapping network device
368  * @v enable    Whether to enable interrupts
369  */
370 static void net80211_netdev_irq ( struct net_device *netdev, int enable )
371 {
372         struct net80211_device *dev = netdev->priv;
373
374         if ( dev->op->irq )
375                 dev->op->irq ( dev, enable );
376 }
377
378 /** Network device operations for a wrapped 802.11 device */
379 static struct net_device_operations net80211_netdev_ops = {
380         .open = net80211_netdev_open,
381         .close = net80211_netdev_close,
382         .transmit = net80211_netdev_transmit,
383         .poll = net80211_netdev_poll,
384         .irq = net80211_netdev_irq,
385 };
386
387
388 /* ---------- 802.11 link-layer protocol ---------- */
389
390 /**
391  * Determine whether a transmission rate uses ERP/OFDM
392  *
393  * @v rate      Rate in 100 kbps units
394  * @ret is_erp  TRUE if the rate is an ERP/OFDM rate
395  *
396  * 802.11b supports rates of 1.0, 2.0, 5.5, and 11.0 Mbps; any other
397  * rate than these on the 2.4GHz spectrum is an ERP (802.11g) rate.
398  */
399 static inline int net80211_rate_is_erp ( u16 rate )
400 {
401         if ( rate == 10 || rate == 20 || rate == 55 || rate == 110 )
402                 return 0;
403         return 1;
404 }
405
406
407 /**
408  * Calculate one frame's contribution to 802.11 duration field
409  *
410  * @v dev       802.11 device
411  * @v bytes     Amount of data to calculate duration for
412  * @ret dur     Duration field in microseconds
413  *
414  * To avoid multiple stations attempting to transmit at once, 802.11
415  * provides that every packet shall include a duration field
416  * specifying a length of time for which the wireless medium will be
417  * reserved after it is transmitted. The duration is measured in
418  * microseconds and is calculated with respect to the current
419  * physical-layer parameters of the 802.11 device.
420  *
421  * For an unfragmented data or management frame, or the last fragment
422  * of a fragmented frame, the duration captures only the 10 data bytes
423  * of one ACK; call once with bytes = 10.
424  *
425  * For a fragment of a data or management rame that will be followed
426  * by more fragments, the duration captures an ACK, the following
427  * fragment, and its ACK; add the results of three calls, two with
428  * bytes = 10 and one with bytes set to the next fragment's size.
429  *
430  * For an RTS control frame, the duration captures the responding CTS,
431  * the frame being sent, and its ACK; add the results of three calls,
432  * two with bytes = 10 and one with bytes set to the next frame's size
433  * (assuming unfragmented).
434  *
435  * For a CTS-to-self control frame, the duration captures the frame
436  * being protected and its ACK; add the results of two calls, one with
437  * bytes = 10 and one with bytes set to the next frame's size.
438  *
439  * No other frame types are currently supported by iPXE.
440  */
441 u16 net80211_duration ( struct net80211_device *dev, int bytes, u16 rate )
442 {
443         struct net80211_channel *chan = &dev->channels[dev->channel];
444         u32 kbps = rate * 100;
445
446         if ( chan->band == NET80211_BAND_5GHZ || net80211_rate_is_erp ( rate ) ) {
447                 /* OFDM encoding (802.11a/g) */
448                 int bits_per_symbol = ( kbps * 4 ) / 1000;      /* 4us/symbol */
449                 int bits = 22 + ( bytes << 3 ); /* 22-bit PLCP */
450                 int symbols = ( bits + bits_per_symbol - 1 ) / bits_per_symbol;
451
452                 return 16 + 20 + ( symbols * 4 ); /* 16us SIFS, 20us preamble */
453         } else {
454                 /* CCK encoding (802.11b) */
455                 int phy_time = 144 + 48;        /* preamble + PLCP */
456                 int bits = bytes << 3;
457                 int data_time = ( bits * 1000 + kbps - 1 ) / kbps;
458
459                 if ( dev->phy_flags & NET80211_PHY_USE_SHORT_PREAMBLE )
460                         phy_time >>= 1;
461
462                 return 10 + phy_time + data_time; /* 10us SIFS */
463         }
464 }
465
466 /**
467  * Add 802.11 link-layer header
468  *
469  * @v netdev            Wrapping network device
470  * @v iobuf             I/O buffer
471  * @v ll_dest           Link-layer destination address
472  * @v ll_source         Link-layer source address
473  * @v net_proto         Network-layer protocol, in network byte order
474  * @ret rc              Return status code
475  *
476  * This adds both the 802.11 frame header and the 802.2 LLC/SNAP
477  * header used on data packets.
478  *
479  * We also check here for state of the link that would make it invalid
480  * to send a data packet; every data packet must pass through here,
481  * and no non-data packet (e.g. management frame) should.
482  */
483 static int net80211_ll_push ( struct net_device *netdev,
484                               struct io_buffer *iobuf, const void *ll_dest,
485                               const void *ll_source, uint16_t net_proto )
486 {
487         struct net80211_device *dev = netdev->priv;
488         struct ieee80211_frame *hdr = iob_push ( iobuf,
489                                                  IEEE80211_LLC_HEADER_LEN +
490                                                  IEEE80211_TYP_FRAME_HEADER_LEN );
491         struct ieee80211_llc_snap_header *lhdr =
492                 ( void * ) hdr + IEEE80211_TYP_FRAME_HEADER_LEN;
493
494         /* We can't send data packets if we're not associated. */
495         if ( ! ( dev->state & NET80211_ASSOCIATED ) ) {
496                 if ( dev->assoc_rc )
497                         return dev->assoc_rc;
498                 return -ENETUNREACH;
499         }
500
501         hdr->fc = IEEE80211_THIS_VERSION | IEEE80211_TYPE_DATA |
502             IEEE80211_STYPE_DATA | IEEE80211_FC_TODS;
503
504         /* We don't send fragmented frames, so duration is the time
505            for an SIFS + 10-byte ACK. */
506         hdr->duration = net80211_duration ( dev, 10, dev->rates[dev->rate] );
507
508         memcpy ( hdr->addr1, dev->bssid, ETH_ALEN );
509         memcpy ( hdr->addr2, ll_source, ETH_ALEN );
510         memcpy ( hdr->addr3, ll_dest, ETH_ALEN );
511
512         hdr->seq = IEEE80211_MAKESEQ ( ++dev->last_tx_seqnr, 0 );
513
514         lhdr->dsap = IEEE80211_LLC_DSAP;
515         lhdr->ssap = IEEE80211_LLC_SSAP;
516         lhdr->ctrl = IEEE80211_LLC_CTRL;
517         memset ( lhdr->oui, 0x00, 3 );
518         lhdr->ethertype = net_proto;
519
520         return 0;
521 }
522
523 /**
524  * Remove 802.11 link-layer header
525  *
526  * @v netdev            Wrapping network device
527  * @v iobuf             I/O buffer
528  * @ret ll_dest         Link-layer destination address
529  * @ret ll_source       Link-layer source
530  * @ret net_proto       Network-layer protocol, in network byte order
531  * @ret flags           Packet flags
532  * @ret rc              Return status code
533  *
534  * This expects and removes both the 802.11 frame header and the 802.2
535  * LLC/SNAP header that are used on data packets.
536  */
537 static int net80211_ll_pull ( struct net_device *netdev __unused,
538                               struct io_buffer *iobuf,
539                               const void **ll_dest, const void **ll_source,
540                               uint16_t * net_proto, unsigned int *flags )
541 {
542         struct ieee80211_frame *hdr = iobuf->data;
543         struct ieee80211_llc_snap_header *lhdr =
544                 ( void * ) hdr + IEEE80211_TYP_FRAME_HEADER_LEN;
545
546         /* Bunch of sanity checks */
547         if ( iob_len ( iobuf ) < IEEE80211_TYP_FRAME_HEADER_LEN +
548              IEEE80211_LLC_HEADER_LEN ) {
549                 DBGC ( netdev->priv, "802.11 %p packet too short (%zd bytes)\n",
550                        netdev->priv, iob_len ( iobuf ) );
551                 return -EINVAL_PKT_TOO_SHORT;
552         }
553
554         if ( ( hdr->fc & IEEE80211_FC_VERSION ) != IEEE80211_THIS_VERSION ) {
555                 DBGC ( netdev->priv, "802.11 %p packet invalid version %04x\n",
556                        netdev->priv, hdr->fc & IEEE80211_FC_VERSION );
557                 return -EINVAL_PKT_VERSION;
558         }
559
560         if ( ( hdr->fc & IEEE80211_FC_TYPE ) != IEEE80211_TYPE_DATA ||
561              ( hdr->fc & IEEE80211_FC_SUBTYPE ) != IEEE80211_STYPE_DATA ) {
562                 DBGC ( netdev->priv, "802.11 %p packet not data/data (fc=%04x)\n",
563                        netdev->priv, hdr->fc );
564                 return -EINVAL_PKT_NOT_DATA;
565         }
566
567         if ( ( hdr->fc & ( IEEE80211_FC_TODS | IEEE80211_FC_FROMDS ) ) !=
568              IEEE80211_FC_FROMDS ) {
569                 DBGC ( netdev->priv, "802.11 %p packet not from DS (fc=%04x)\n",
570                        netdev->priv, hdr->fc );
571                 return -EINVAL_PKT_NOT_FROMDS;
572         }
573
574         if ( lhdr->dsap != IEEE80211_LLC_DSAP || lhdr->ssap != IEEE80211_LLC_SSAP ||
575              lhdr->ctrl != IEEE80211_LLC_CTRL || lhdr->oui[0] || lhdr->oui[1] ||
576              lhdr->oui[2] ) {
577                 DBGC ( netdev->priv, "802.11 %p LLC header is not plain EtherType "
578                        "encapsulator: %02x->%02x [%02x] %02x:%02x:%02x %04x\n",
579                        netdev->priv, lhdr->dsap, lhdr->ssap, lhdr->ctrl,
580                        lhdr->oui[0], lhdr->oui[1], lhdr->oui[2], lhdr->ethertype );
581                 return -EINVAL_PKT_LLC_HEADER;
582         }
583
584         iob_pull ( iobuf, sizeof ( *hdr ) + sizeof ( *lhdr ) );
585
586         *ll_dest = hdr->addr1;
587         *ll_source = hdr->addr3;
588         *net_proto = lhdr->ethertype;
589         *flags = ( ( is_multicast_ether_addr ( hdr->addr1 ) ?
590                      LL_MULTICAST : 0 ) |
591                    ( is_broadcast_ether_addr ( hdr->addr1 ) ?
592                      LL_BROADCAST : 0 ) );
593         return 0;
594 }
595
596 /** 802.11 link-layer protocol */
597 static struct ll_protocol net80211_ll_protocol __ll_protocol = {
598         .name = "802.11",
599         .push = net80211_ll_push,
600         .pull = net80211_ll_pull,
601         .init_addr = eth_init_addr,
602         .ntoa = eth_ntoa,
603         .mc_hash = eth_mc_hash,
604         .eth_addr = eth_eth_addr,
605         .eui64 = eth_eui64,
606         .ll_proto = htons ( ARPHRD_ETHER ),     /* "encapsulated Ethernet" */
607         .hw_addr_len = ETH_ALEN,
608         .ll_addr_len = ETH_ALEN,
609         .ll_header_len = IEEE80211_TYP_FRAME_HEADER_LEN +
610                                 IEEE80211_LLC_HEADER_LEN,
611 };
612
613
614 /* ---------- 802.11 network management API ---------- */
615
616 /**
617  * Get 802.11 device from wrapping network device
618  *
619  * @v netdev    Wrapping network device
620  * @ret dev     802.11 device wrapped by network device, or NULL
621  *
622  * Returns NULL if the network device does not wrap an 802.11 device.
623  */
624 struct net80211_device * net80211_get ( struct net_device *netdev )
625 {
626         struct net80211_device *dev;
627
628         list_for_each_entry ( dev, &net80211_devices, list ) {
629                 if ( netdev->priv == dev )
630                         return netdev->priv;
631         }
632
633         return NULL;
634 }
635
636 /**
637  * Set state of 802.11 device keeping management frames
638  *
639  * @v dev       802.11 device
640  * @v enable    Whether to keep management frames
641  * @ret oldenab Whether management frames were enabled before this call
642  *
643  * If enable is TRUE, beacon, probe, and action frames will be kept
644  * and may be retrieved by calling net80211_mgmt_dequeue().
645  */
646 int net80211_keep_mgmt ( struct net80211_device *dev, int enable )
647 {
648         int oldenab = dev->keep_mgmt;
649
650         dev->keep_mgmt = enable;
651         return oldenab;
652 }
653
654 /**
655  * Get 802.11 management frame
656  *
657  * @v dev       802.11 device
658  * @ret signal  Signal strength of returned management frame
659  * @ret iob     I/O buffer, or NULL if no management frame is queued
660  *
661  * Frames will only be returned by this function if
662  * net80211_keep_mgmt() has been previously called with enable set to
663  * TRUE.
664  *
665  * The calling function takes ownership of the returned I/O buffer.
666  */
667 struct io_buffer * net80211_mgmt_dequeue ( struct net80211_device *dev,
668                                            int *signal )
669 {
670         struct io_buffer *iobuf;
671         struct net80211_rx_info *rxi;
672
673         list_for_each_entry ( rxi, &dev->mgmt_info_queue, list ) {
674                 list_del ( &rxi->list );
675                 if ( signal )
676                         *signal = rxi->signal;
677                 free ( rxi );
678
679                 assert ( ! list_empty ( &dev->mgmt_queue ) );
680                 iobuf = list_first_entry ( &dev->mgmt_queue, struct io_buffer,
681                                            list );
682                 list_del ( &iobuf->list );
683                 return iobuf;
684         }
685
686         return NULL;
687 }
688
689 /**
690  * Transmit 802.11 management frame
691  *
692  * @v dev       802.11 device
693  * @v fc        Frame Control flags for management frame
694  * @v dest      Destination access point
695  * @v iob       I/O buffer
696  * @ret rc      Return status code
697  *
698  * The @a fc argument must contain at least an IEEE 802.11 management
699  * subtype number (e.g. IEEE80211_STYPE_PROBE_REQ). If it contains
700  * IEEE80211_FC_PROTECTED, the frame will be encrypted prior to
701  * transmission.
702  *
703  * It is required that @a iob have at least 24 bytes of headroom
704  * reserved before its data start.
705  */
706 int net80211_tx_mgmt ( struct net80211_device *dev, u16 fc, u8 dest[6],
707                        struct io_buffer *iob )
708 {
709         struct ieee80211_frame *hdr = iob_push ( iob,
710                                                  IEEE80211_TYP_FRAME_HEADER_LEN );
711
712         hdr->fc = IEEE80211_THIS_VERSION | IEEE80211_TYPE_MGMT |
713             ( fc & ~IEEE80211_FC_PROTECTED );
714         hdr->duration = net80211_duration ( dev, 10, dev->rates[dev->rate] );
715         hdr->seq = IEEE80211_MAKESEQ ( ++dev->last_tx_seqnr, 0 );
716
717         memcpy ( hdr->addr1, dest, ETH_ALEN );  /* DA = RA */
718         memcpy ( hdr->addr2, dev->netdev->ll_addr, ETH_ALEN );  /* SA = TA */
719         memcpy ( hdr->addr3, dest, ETH_ALEN );  /* BSSID */
720
721         if ( fc & IEEE80211_FC_PROTECTED ) {
722                 if ( ! dev->crypto )
723                         return -EINVAL_CRYPTO_REQUEST;
724
725                 struct io_buffer *eiob = dev->crypto->encrypt ( dev->crypto,
726                                                                 iob );
727                 free_iob ( iob );
728                 iob = eiob;
729         }
730
731         return netdev_tx ( dev->netdev, iob );
732 }
733
734
735 /* ---------- Driver API ---------- */
736
737 /** 802.11 association process descriptor */
738 static struct process_descriptor net80211_process_desc =
739         PROC_DESC ( struct net80211_device, proc_assoc,
740                     net80211_step_associate );
741
742 /**
743  * Allocate 802.11 device
744  *
745  * @v priv_size         Size of driver-private allocation area
746  * @ret dev             Newly allocated 802.11 device
747  *
748  * This function allocates a net_device with space in its private area
749  * for both the net80211_device it will wrap and the driver-private
750  * data space requested. It initializes the link-layer-specific parts
751  * of the net_device, and links the net80211_device to the net_device
752  * appropriately.
753  */
754 struct net80211_device * net80211_alloc ( size_t priv_size )
755 {
756         struct net80211_device *dev;
757         struct net_device *netdev =
758                 alloc_netdev ( sizeof ( *dev ) + priv_size );
759
760         if ( ! netdev )
761                 return NULL;
762
763         netdev->ll_protocol = &net80211_ll_protocol;
764         netdev->ll_broadcast = eth_broadcast;
765         netdev->max_pkt_len = IEEE80211_MAX_DATA_LEN;
766         netdev_init ( netdev, &net80211_netdev_ops );
767
768         dev = netdev->priv;
769         dev->netdev = netdev;
770         dev->priv = ( u8 * ) dev + sizeof ( *dev );
771         dev->op = &net80211_null_ops;
772
773         process_init_stopped ( &dev->proc_assoc, &net80211_process_desc,
774                                &netdev->refcnt );
775         INIT_LIST_HEAD ( &dev->mgmt_queue );
776         INIT_LIST_HEAD ( &dev->mgmt_info_queue );
777
778         return dev;
779 }
780
781 /**
782  * Register 802.11 device with network stack
783  *
784  * @v dev       802.11 device
785  * @v ops       802.11 device operations
786  * @v hw        802.11 hardware information
787  *
788  * This also registers the wrapping net_device with the higher network
789  * layers.
790  */
791 int net80211_register ( struct net80211_device *dev,
792                         struct net80211_device_operations *ops,
793                         struct net80211_hw_info *hw )
794 {
795         dev->op = ops;
796         dev->hw = malloc ( sizeof ( *hw ) );
797         if ( ! dev->hw )
798                 return -ENOMEM;
799
800         memcpy ( dev->hw, hw, sizeof ( *hw ) );
801         memcpy ( dev->netdev->hw_addr, hw->hwaddr, ETH_ALEN );
802
803         /* Set some sensible channel defaults for driver's open() function */
804         memcpy ( dev->channels, dev->hw->channels,
805                  NET80211_MAX_CHANNELS * sizeof ( dev->channels[0] ) );
806         dev->channel = 0;
807
808         list_add_tail ( &dev->list, &net80211_devices );
809         return register_netdev ( dev->netdev );
810 }
811
812 /**
813  * Unregister 802.11 device from network stack
814  *
815  * @v dev       802.11 device
816  *
817  * After this call, the device operations are cleared so that they
818  * will not be called.
819  */
820 void net80211_unregister ( struct net80211_device *dev )
821 {
822         unregister_netdev ( dev->netdev );
823         list_del ( &dev->list );
824         dev->op = &net80211_null_ops;
825 }
826
827 /**
828  * Free 802.11 device
829  *
830  * @v dev       802.11 device
831  *
832  * The device should be unregistered before this function is called.
833  */
834 void net80211_free ( struct net80211_device *dev )
835 {
836         free ( dev->hw );
837         rc80211_free ( dev->rctl );
838         netdev_nullify ( dev->netdev );
839         netdev_put ( dev->netdev );
840 }
841
842
843 /* ---------- 802.11 network management workhorse code ---------- */
844
845 /**
846  * Set state of 802.11 device
847  *
848  * @v dev       802.11 device
849  * @v clear     Bitmask of flags to clear
850  * @v set       Bitmask of flags to set
851  * @v status    Status or reason code for most recent operation
852  *
853  * If @a status represents a reason code, it should be OR'ed with
854  * NET80211_IS_REASON.
855  *
856  * Clearing authentication also clears association; clearing
857  * association also clears security handshaking state. Clearing
858  * association removes the link-up flag from the wrapping net_device,
859  * but setting it does not automatically set the flag; that is left to
860  * the judgment of higher-level code.
861  */
862 static inline void net80211_set_state ( struct net80211_device *dev,
863                                         short clear, short set,
864                                         u16 status )
865 {
866         /* The conditions in this function are deliberately formulated
867            to be decidable at compile-time in most cases. Since clear
868            and set are generally passed as constants, the body of this
869            function can be reduced down to a few statements by the
870            compiler. */
871
872         const int statmsk = NET80211_STATUS_MASK | NET80211_IS_REASON;
873
874         if ( clear & NET80211_PROBED )
875                 clear |= NET80211_AUTHENTICATED;
876
877         if ( clear & NET80211_AUTHENTICATED )
878                 clear |= NET80211_ASSOCIATED;
879
880         if ( clear & NET80211_ASSOCIATED )
881                 clear |= NET80211_CRYPTO_SYNCED;
882
883         dev->state = ( dev->state & ~clear ) | set;
884         dev->state = ( dev->state & ~statmsk ) | ( status & statmsk );
885
886         if ( clear & NET80211_ASSOCIATED )
887                 netdev_link_down ( dev->netdev );
888
889         if ( ( clear | set ) & NET80211_ASSOCIATED )
890                 dev->op->config ( dev, NET80211_CFG_ASSOC );
891
892         if ( status != 0 ) {
893                 if ( status & NET80211_IS_REASON )
894                         dev->assoc_rc = -E80211_REASON ( status );
895                 else
896                         dev->assoc_rc = -E80211_STATUS ( status );
897                 netdev_link_err ( dev->netdev, dev->assoc_rc );
898         }
899 }
900
901 /**
902  * Add channels to 802.11 device
903  *
904  * @v dev       802.11 device
905  * @v start     First channel number to add
906  * @v len       Number of channels to add
907  * @v txpower   TX power (dBm) to allow on added channels
908  *
909  * To replace the current list of channels instead of adding to it,
910  * set the nr_channels field of the 802.11 device to 0 before calling
911  * this function.
912  */
913 static void net80211_add_channels ( struct net80211_device *dev, int start,
914                                     int len, int txpower )
915 {
916         int i, chan = start;
917
918         for ( i = dev->nr_channels; len-- && i < NET80211_MAX_CHANNELS; i++ ) {
919                 dev->channels[i].channel_nr = chan;
920                 dev->channels[i].maxpower = txpower;
921                 dev->channels[i].hw_value = 0;
922
923                 if ( chan >= 1 && chan <= 14 ) {
924                         dev->channels[i].band = NET80211_BAND_2GHZ;
925                         if ( chan == 14 )
926                                 dev->channels[i].center_freq = 2484;
927                         else
928                                 dev->channels[i].center_freq = 2407 + 5 * chan;
929                         chan++;
930                 } else {
931                         dev->channels[i].band = NET80211_BAND_5GHZ;
932                         dev->channels[i].center_freq = 5000 + 5 * chan;
933                         chan += 4;
934                 }
935         }
936
937         dev->nr_channels = i;
938 }
939
940 /**
941  * Filter 802.11 device channels for hardware capabilities
942  *
943  * @v dev       802.11 device
944  *
945  * Hardware may support fewer channels than regulatory restrictions
946  * allow; this function filters out channels in dev->channels that are
947  * not supported by the hardware list in dev->hwinfo. It also copies
948  * over the net80211_channel::hw_value and limits maximum TX power
949  * appropriately.
950  *
951  * Channels are matched based on center frequency, ignoring band and
952  * channel number.
953  *
954  * If the driver specifies no supported channels, the effect will be
955  * as though all were supported.
956  */
957 static void net80211_filter_hw_channels ( struct net80211_device *dev )
958 {
959         int delta = 0, i = 0;
960         int old_freq = dev->channels[dev->channel].center_freq;
961         struct net80211_channel *chan, *hwchan;
962
963         if ( ! dev->hw->nr_channels )
964                 return;
965
966         dev->channel = 0;
967         for ( chan = dev->channels; chan < dev->channels + dev->nr_channels;
968               chan++, i++ ) {
969                 int ok = 0;
970                 for ( hwchan = dev->hw->channels;
971                       hwchan < dev->hw->channels + dev->hw->nr_channels;
972                       hwchan++ ) {
973                         if ( hwchan->center_freq == chan->center_freq ) {
974                                 ok = 1;
975                                 break;
976                         }
977                 }
978
979                 if ( ! ok )
980                         delta++;
981                 else {
982                         chan->hw_value = hwchan->hw_value;
983                         if ( hwchan->maxpower != 0 &&
984                              chan->maxpower > hwchan->maxpower )
985                                 chan->maxpower = hwchan->maxpower;
986                         if ( old_freq == chan->center_freq )
987                                 dev->channel = i - delta;
988                         if ( delta )
989                                 chan[-delta] = *chan;
990                 }
991         }
992
993         dev->nr_channels -= delta;
994
995         if ( dev->channels[dev->channel].center_freq != old_freq )
996                 dev->op->config ( dev, NET80211_CFG_CHANNEL );
997 }
998
999 /**
1000  * Update 802.11 device state to reflect received capabilities field
1001  *
1002  * @v dev       802.11 device
1003  * @v capab     Capabilities field in beacon, probe, or association frame
1004  * @ret rc      Return status code
1005  */
1006 static int net80211_process_capab ( struct net80211_device *dev,
1007                                     u16 capab )
1008 {
1009         u16 old_phy = dev->phy_flags;
1010
1011         if ( ( capab & ( IEEE80211_CAPAB_MANAGED | IEEE80211_CAPAB_ADHOC ) ) !=
1012              IEEE80211_CAPAB_MANAGED ) {
1013                 DBGC ( dev, "802.11 %p cannot handle IBSS network\n", dev );
1014                 return -ENOSYS;
1015         }
1016
1017         dev->phy_flags &= ~( NET80211_PHY_USE_SHORT_PREAMBLE |
1018                              NET80211_PHY_USE_SHORT_SLOT );
1019
1020         if ( capab & IEEE80211_CAPAB_SHORT_PMBL )
1021                 dev->phy_flags |= NET80211_PHY_USE_SHORT_PREAMBLE;
1022
1023         if ( capab & IEEE80211_CAPAB_SHORT_SLOT )
1024                 dev->phy_flags |= NET80211_PHY_USE_SHORT_SLOT;
1025
1026         if ( old_phy != dev->phy_flags )
1027                 dev->op->config ( dev, NET80211_CFG_PHY_PARAMS );
1028
1029         return 0;
1030 }
1031
1032 /**
1033  * Update 802.11 device state to reflect received information elements
1034  *
1035  * @v dev       802.11 device
1036  * @v ie        Pointer to first information element
1037  * @v ie_end    Pointer to tail of packet I/O buffer
1038  * @ret rc      Return status code
1039  */
1040 static int net80211_process_ie ( struct net80211_device *dev,
1041                                  union ieee80211_ie *ie, void *ie_end )
1042 {
1043         u16 old_rate = dev->rates[dev->rate];
1044         u16 old_phy = dev->phy_flags;
1045         int have_rates = 0, i;
1046         int ds_channel = 0;
1047         int changed = 0;
1048         int band = dev->channels[dev->channel].band;
1049
1050         if ( ! ieee80211_ie_bound ( ie, ie_end ) )
1051                 return 0;
1052
1053         for ( ; ie; ie = ieee80211_next_ie ( ie, ie_end ) ) {
1054                 switch ( ie->id ) {
1055                 case IEEE80211_IE_SSID:
1056                         if ( ie->len <= 32 ) {
1057                                 memcpy ( dev->essid, ie->ssid, ie->len );
1058                                 dev->essid[ie->len] = 0;
1059                         }
1060                         break;
1061
1062                 case IEEE80211_IE_RATES:
1063                 case IEEE80211_IE_EXT_RATES:
1064                         if ( ! have_rates ) {
1065                                 dev->nr_rates = 0;
1066                                 dev->basic_rates = 0;
1067                                 have_rates = 1;
1068                         }
1069                         for ( i = 0; i < ie->len &&
1070                               dev->nr_rates < NET80211_MAX_RATES; i++ ) {
1071                                 u8 rid = ie->rates[i];
1072                                 u16 rate = ( rid & 0x7f ) * 5;
1073
1074                                 if ( rid & 0x80 )
1075                                         dev->basic_rates |=
1076                                                 ( 1 << dev->nr_rates );
1077
1078                                 dev->rates[dev->nr_rates++] = rate;
1079                         }
1080
1081                         break;
1082
1083                 case IEEE80211_IE_DS_PARAM:
1084                         if ( dev->channel < dev->nr_channels && ds_channel ==
1085                              dev->channels[dev->channel].channel_nr )
1086                                 break;
1087                         ds_channel = ie->ds_param.current_channel;
1088                         net80211_change_channel ( dev, ds_channel );
1089                         break;
1090
1091                 case IEEE80211_IE_COUNTRY:
1092                         dev->nr_channels = 0;
1093
1094                         DBGC ( dev, "802.11 %p setting country regulations "
1095                                "for %c%c\n", dev, ie->country.name[0],
1096                                ie->country.name[1] );
1097                         for ( i = 0; i < ( ie->len - 3 ) / 3; i++ ) {
1098                                 union ieee80211_ie_country_triplet *t =
1099                                         &ie->country.triplet[i];
1100                                 if ( t->first > 200 ) {
1101                                         DBGC ( dev, "802.11 %p ignoring regulatory "
1102                                                "extension information\n", dev );
1103                                 } else {
1104                                         net80211_add_channels ( dev,
1105                                                         t->band.first_channel,
1106                                                         t->band.nr_channels,
1107                                                         t->band.max_txpower );
1108                                 }
1109                         }
1110                         net80211_filter_hw_channels ( dev );
1111                         break;
1112
1113                 case IEEE80211_IE_ERP_INFO:
1114                         dev->phy_flags &= ~( NET80211_PHY_USE_PROTECTION |
1115                                              NET80211_PHY_USE_SHORT_PREAMBLE );
1116                         if ( ie->erp_info & IEEE80211_ERP_USE_PROTECTION )
1117                                 dev->phy_flags |= NET80211_PHY_USE_PROTECTION;
1118                         if ( ! ( ie->erp_info & IEEE80211_ERP_BARKER_LONG ) )
1119                                 dev->phy_flags |= NET80211_PHY_USE_SHORT_PREAMBLE;
1120                         break;
1121                 }
1122         }
1123
1124         if ( have_rates ) {
1125                 /* Allow only those rates that are also supported by
1126                    the hardware. */
1127                 int delta = 0, j;
1128
1129                 dev->rate = 0;
1130                 for ( i = 0; i < dev->nr_rates; i++ ) {
1131                         int ok = 0;
1132                         for ( j = 0; j < dev->hw->nr_rates[band]; j++ ) {
1133                                 if ( dev->hw->rates[band][j] == dev->rates[i] ){
1134                                         ok = 1;
1135                                         break;
1136                                 }
1137                         }
1138
1139                         if ( ! ok )
1140                                 delta++;
1141                         else {
1142                                 dev->rates[i - delta] = dev->rates[i];
1143                                 if ( old_rate == dev->rates[i] )
1144                                         dev->rate = i - delta;
1145                         }
1146                 }
1147
1148                 dev->nr_rates -= delta;
1149
1150                 /* Sort available rates - sorted subclumps tend to already
1151                    exist, so insertion sort works well. */
1152                 for ( i = 1; i < dev->nr_rates; i++ ) {
1153                         u16 rate = dev->rates[i];
1154                         u32 tmp, br, mask;
1155
1156                         for ( j = i - 1; j >= 0 && dev->rates[j] >= rate; j-- )
1157                                 dev->rates[j + 1] = dev->rates[j];
1158                         dev->rates[j + 1] = rate;
1159
1160                         /* Adjust basic_rates to match by rotating the
1161                            bits from bit j+1 to bit i left one position. */
1162                         mask = ( ( 1 << i ) - 1 ) & ~( ( 1 << ( j + 1 ) ) - 1 );
1163                         br = dev->basic_rates;
1164                         tmp = br & ( 1 << i );
1165                         br = ( br & ~( mask | tmp ) ) | ( ( br & mask ) << 1 );
1166                         br |= ( tmp >> ( i - j - 1 ) );
1167                         dev->basic_rates = br;
1168                 }
1169
1170                 net80211_set_rtscts_rate ( dev );
1171
1172                 if ( dev->rates[dev->rate] != old_rate )
1173                         changed |= NET80211_CFG_RATE;
1174         }
1175
1176         if ( dev->hw->flags & NET80211_HW_NO_SHORT_PREAMBLE )
1177                 dev->phy_flags &= ~NET80211_PHY_USE_SHORT_PREAMBLE;
1178         if ( dev->hw->flags & NET80211_HW_NO_SHORT_SLOT )
1179                 dev->phy_flags &= ~NET80211_PHY_USE_SHORT_SLOT;
1180
1181         if ( old_phy != dev->phy_flags )
1182                 changed |= NET80211_CFG_PHY_PARAMS;
1183
1184         if ( changed )
1185                 dev->op->config ( dev, changed );
1186
1187         return 0;
1188 }
1189
1190 /**
1191  * Create information elements for outgoing probe or association packet
1192  *
1193  * @v dev               802.11 device
1194  * @v ie                Pointer to start of information element area
1195  * @ret next_ie         Pointer to first byte after added information elements
1196  */
1197 static union ieee80211_ie *
1198 net80211_marshal_request_info ( struct net80211_device *dev,
1199                                 union ieee80211_ie *ie )
1200 {
1201         int i;
1202
1203         ie->id = IEEE80211_IE_SSID;
1204         ie->len = strlen ( dev->essid );
1205         memcpy ( ie->ssid, dev->essid, ie->len );
1206
1207         ie = ieee80211_next_ie ( ie, NULL );
1208
1209         ie->id = IEEE80211_IE_RATES;
1210         ie->len = dev->nr_rates;
1211         if ( ie->len > 8 )
1212                 ie->len = 8;
1213
1214         for ( i = 0; i < ie->len; i++ ) {
1215                 ie->rates[i] = dev->rates[i] / 5;
1216                 if ( dev->basic_rates & ( 1 << i ) )
1217                         ie->rates[i] |= 0x80;
1218         }
1219
1220         ie = ieee80211_next_ie ( ie, NULL );
1221
1222         if ( dev->rsn_ie && dev->rsn_ie->id == IEEE80211_IE_RSN ) {
1223                 memcpy ( ie, dev->rsn_ie, dev->rsn_ie->len + 2 );
1224                 ie = ieee80211_next_ie ( ie, NULL );
1225         }
1226
1227         if ( dev->nr_rates > 8 ) {
1228                 /* 802.11 requires we use an Extended Basic Rates IE
1229                    for the rates beyond the eighth. */
1230
1231                 ie->id = IEEE80211_IE_EXT_RATES;
1232                 ie->len = dev->nr_rates - 8;
1233
1234                 for ( ; i < dev->nr_rates; i++ ) {
1235                         ie->rates[i - 8] = dev->rates[i] / 5;
1236                         if ( dev->basic_rates & ( 1 << i ) )
1237                                 ie->rates[i - 8] |= 0x80;
1238                 }
1239
1240                 ie = ieee80211_next_ie ( ie, NULL );
1241         }
1242
1243         if ( dev->rsn_ie && dev->rsn_ie->id == IEEE80211_IE_VENDOR ) {
1244                 memcpy ( ie, dev->rsn_ie, dev->rsn_ie->len + 2 );
1245                 ie = ieee80211_next_ie ( ie, NULL );
1246         }
1247
1248         return ie;
1249 }
1250
1251 /** Seconds to wait after finding a network, to possibly find better APs for it
1252  *
1253  * This is used when a specific SSID to scan for is specified.
1254  */
1255 #define NET80211_PROBE_GATHER    1
1256
1257 /** Seconds to wait after finding a network, to possibly find other networks
1258  *
1259  * This is used when an empty SSID is specified, to scan for all
1260  * networks.
1261  */
1262 #define NET80211_PROBE_GATHER_ALL 2
1263
1264 /** Seconds to allow a probe to take if no network has been found */
1265 #define NET80211_PROBE_TIMEOUT   6
1266
1267 /**
1268  * Begin probe of 802.11 networks
1269  *
1270  * @v dev       802.11 device
1271  * @v essid     SSID to probe for, or "" to accept any (may not be NULL)
1272  * @v active    Whether to use active scanning
1273  * @ret ctx     Probe context
1274  *
1275  * Active scanning may only be used on channels 1-11 in the 2.4GHz
1276  * band, due to iPXE's lack of a complete regulatory database. If
1277  * active scanning is used, probe packets will be sent on each
1278  * channel; this can allow association with hidden-SSID networks if
1279  * the SSID is properly specified.
1280  *
1281  * A @c NULL return indicates an out-of-memory condition.
1282  *
1283  * The returned context must be periodically passed to
1284  * net80211_probe_step() until that function returns zero.
1285  */
1286 struct net80211_probe_ctx * net80211_probe_start ( struct net80211_device *dev,
1287                                                    const char *essid,
1288                                                    int active )
1289 {
1290         struct net80211_probe_ctx *ctx = zalloc ( sizeof ( *ctx ) );
1291
1292         if ( ! ctx )
1293                 return NULL;
1294
1295         assert ( netdev_is_open ( dev->netdev ) );
1296
1297         ctx->dev = dev;
1298         ctx->old_keep_mgmt = net80211_keep_mgmt ( dev, 1 );
1299         ctx->essid = essid;
1300         if ( dev->essid != ctx->essid )
1301                 strcpy ( dev->essid, ctx->essid );
1302
1303         if ( active ) {
1304                 struct ieee80211_probe_req *probe_req;
1305                 union ieee80211_ie *ie;
1306
1307                 ctx->probe = alloc_iob ( 128 );
1308                 iob_reserve ( ctx->probe, IEEE80211_TYP_FRAME_HEADER_LEN );
1309                 probe_req = ctx->probe->data;
1310
1311                 ie = net80211_marshal_request_info ( dev,
1312                                                      probe_req->info_element );
1313
1314                 iob_put ( ctx->probe, ( void * ) ie - ctx->probe->data );
1315         }
1316
1317         ctx->ticks_start = currticks();
1318         ctx->ticks_beacon = 0;
1319         ctx->ticks_channel = currticks();
1320         ctx->hop_time = ticks_per_sec() / ( active ? 2 : 6 );
1321
1322         /*
1323          * Channels on 2.4GHz overlap, and the most commonly used
1324          * are 1, 6, and 11. We'll get a result faster if we check
1325          * every 5 channels, but in order to hit all of them the
1326          * number of channels must be relatively prime to 5. If it's
1327          * not, tweak the hop.
1328          */
1329         ctx->hop_step = 5;
1330         while ( dev->nr_channels % ctx->hop_step == 0 && ctx->hop_step > 1 )
1331                 ctx->hop_step--;
1332
1333         ctx->beacons = malloc ( sizeof ( *ctx->beacons ) );
1334         INIT_LIST_HEAD ( ctx->beacons );
1335
1336         dev->channel = 0;
1337         dev->op->config ( dev, NET80211_CFG_CHANNEL );
1338
1339         return ctx;
1340 }
1341
1342 /**
1343  * Continue probe of 802.11 networks
1344  *
1345  * @v ctx       Probe context returned by net80211_probe_start()
1346  * @ret rc      Probe status
1347  *
1348  * The return code will be 0 if the probe is still going on (and this
1349  * function should be called again), a positive number if the probe
1350  * completed successfully, or a negative error code if the probe
1351  * failed for that reason.
1352  *
1353  * Whether the probe succeeded or failed, you must call
1354  * net80211_probe_finish_all() or net80211_probe_finish_best()
1355  * (depending on whether you want information on all networks or just
1356  * the best-signal one) in order to release the probe context. A
1357  * failed probe may still have acquired some valid data.
1358  */
1359 int net80211_probe_step ( struct net80211_probe_ctx *ctx )
1360 {
1361         struct net80211_device *dev = ctx->dev;
1362         u32 start_timeout = NET80211_PROBE_TIMEOUT * ticks_per_sec();
1363         u32 gather_timeout = ticks_per_sec();
1364         u32 now = currticks();
1365         struct io_buffer *iob;
1366         int signal;
1367         int rc;
1368         char ssid[IEEE80211_MAX_SSID_LEN + 1];
1369
1370         gather_timeout *= ( ctx->essid[0] ? NET80211_PROBE_GATHER :
1371                             NET80211_PROBE_GATHER_ALL );
1372
1373         /* Time out if necessary */
1374         if ( now >= ctx->ticks_start + start_timeout )
1375                 return list_empty ( ctx->beacons ) ? -ETIMEDOUT : +1;
1376
1377         if ( ctx->ticks_beacon > 0 && now >= ctx->ticks_start + gather_timeout )
1378                 return +1;
1379
1380         /* Change channels if necessary */
1381         if ( now >= ctx->ticks_channel + ctx->hop_time ) {
1382                 dev->channel = ( dev->channel + ctx->hop_step )
1383                         % dev->nr_channels;
1384                 dev->op->config ( dev, NET80211_CFG_CHANNEL );
1385                 udelay ( dev->hw->channel_change_time );
1386
1387                 ctx->ticks_channel = now;
1388
1389                 if ( ctx->probe ) {
1390                         struct io_buffer *siob = ctx->probe; /* to send */
1391
1392                         /* make a copy for future use */
1393                         iob = alloc_iob ( siob->tail - siob->head );
1394                         iob_reserve ( iob, iob_headroom ( siob ) );
1395                         memcpy ( iob_put ( iob, iob_len ( siob ) ),
1396                                  siob->data, iob_len ( siob ) );
1397
1398                         ctx->probe = iob;
1399                         rc = net80211_tx_mgmt ( dev, IEEE80211_STYPE_PROBE_REQ,
1400                                                 eth_broadcast,
1401                                                 iob_disown ( siob ) );
1402                         if ( rc ) {
1403                                 DBGC ( dev, "802.11 %p send probe failed: "
1404                                        "%s\n", dev, strerror ( rc ) );
1405                                 return rc;
1406                         }
1407                 }
1408         }
1409
1410         /* Check for new management packets */
1411         while ( ( iob = net80211_mgmt_dequeue ( dev, &signal ) ) != NULL ) {
1412                 struct ieee80211_frame *hdr;
1413                 struct ieee80211_beacon *beacon;
1414                 union ieee80211_ie *ie;
1415                 struct net80211_wlan *wlan;
1416                 u16 type;
1417
1418                 hdr = iob->data;
1419                 type = hdr->fc & IEEE80211_FC_SUBTYPE;
1420                 beacon = ( struct ieee80211_beacon * ) hdr->data;
1421
1422                 if ( type != IEEE80211_STYPE_BEACON &&
1423                      type != IEEE80211_STYPE_PROBE_RESP ) {
1424                         DBGC2 ( dev, "802.11 %p probe: non-beacon\n", dev );
1425                         goto drop;
1426                 }
1427
1428                 if ( ( void * ) beacon->info_element >= iob->tail ) {
1429                         DBGC ( dev, "802.11 %p probe: beacon with no IEs\n",
1430                                dev );
1431                         goto drop;
1432                 }
1433
1434                 ie = beacon->info_element;
1435
1436                 if ( ! ieee80211_ie_bound ( ie, iob->tail ) )
1437                         ie = NULL;
1438
1439                 while ( ie && ie->id != IEEE80211_IE_SSID )
1440                         ie = ieee80211_next_ie ( ie, iob->tail );
1441
1442                 if ( ! ie ) {
1443                         DBGC ( dev, "802.11 %p probe: beacon with no SSID\n",
1444                                dev );
1445                         goto drop;
1446                 }
1447
1448                 memcpy ( ssid, ie->ssid, ie->len );
1449                 ssid[ie->len] = 0;
1450
1451                 if ( ctx->essid[0] && strcmp ( ctx->essid, ssid ) != 0 ) {
1452                         DBGC2 ( dev, "802.11 %p probe: beacon with wrong SSID "
1453                                 "(%s)\n", dev, ssid );
1454                         goto drop;
1455                 }
1456
1457                 /* See if we've got an entry for this network */
1458                 list_for_each_entry ( wlan, ctx->beacons, list ) {
1459                         if ( strcmp ( wlan->essid, ssid ) != 0 )
1460                                 continue;
1461
1462                         if ( signal < wlan->signal ) {
1463                                 DBGC2 ( dev, "802.11 %p probe: beacon for %s "
1464                                         "(%s) with weaker signal %d\n", dev,
1465                                         ssid, eth_ntoa ( hdr->addr3 ), signal );
1466                                 goto drop;
1467                         }
1468
1469                         goto fill;
1470                 }
1471
1472                 /* No entry yet - make one */
1473                 wlan = zalloc ( sizeof ( *wlan ) );
1474                 strcpy ( wlan->essid, ssid );
1475                 list_add_tail ( &wlan->list, ctx->beacons );
1476
1477                 /* Whether we're using an old entry or a new one, fill
1478                    it with new data. */
1479         fill:
1480                 memcpy ( wlan->bssid, hdr->addr3, ETH_ALEN );
1481                 wlan->signal = signal;
1482                 wlan->channel = dev->channels[dev->channel].channel_nr;
1483
1484                 /* Copy this I/O buffer into a new wlan->beacon; the
1485                  * iob we've got probably came from the device driver
1486                  * and may have the full 2.4k allocation, which we
1487                  * don't want to keep around wasting memory.
1488                  */
1489                 free_iob ( wlan->beacon );
1490                 wlan->beacon = alloc_iob ( iob_len ( iob ) );
1491                 memcpy ( iob_put ( wlan->beacon, iob_len ( iob ) ),
1492                          iob->data, iob_len ( iob ) );
1493
1494                 if ( ( rc = sec80211_detect ( wlan->beacon, &wlan->handshaking,
1495                                               &wlan->crypto ) ) == -ENOTSUP ) {
1496                         struct ieee80211_beacon *beacon =
1497                                 ( struct ieee80211_beacon * ) hdr->data;
1498
1499                         if ( beacon->capability & IEEE80211_CAPAB_PRIVACY ) {
1500                                 DBG ( "802.11 %p probe: secured network %s but "
1501                                       "encryption support not compiled in\n",
1502                                       dev, wlan->essid );
1503                                 wlan->handshaking = NET80211_SECPROT_UNKNOWN;
1504                                 wlan->crypto = NET80211_CRYPT_UNKNOWN;
1505                         } else {
1506                                 wlan->handshaking = NET80211_SECPROT_NONE;
1507                                 wlan->crypto = NET80211_CRYPT_NONE;
1508                         }
1509                 } else if ( rc != 0 ) {
1510                         DBGC ( dev, "802.11 %p probe warning: network "
1511                                "%s with unidentifiable security "
1512                                "settings: %s\n", dev, wlan->essid,
1513                                strerror ( rc ) );
1514                 }
1515
1516                 ctx->ticks_beacon = now;
1517
1518                 DBGC2 ( dev, "802.11 %p probe: good beacon for %s (%s)\n",
1519                         dev, wlan->essid, eth_ntoa ( wlan->bssid ) );
1520
1521         drop:
1522                 free_iob ( iob );
1523         }
1524
1525         return 0;
1526 }
1527
1528
1529 /**
1530  * Finish probe of 802.11 networks, returning best-signal network found
1531  *
1532  * @v ctx       Probe context
1533  * @ret wlan    Best-signal network found, or @c NULL if none were found
1534  *
1535  * If net80211_probe_start() was called with a particular SSID
1536  * parameter as filter, only a network with that SSID (matching
1537  * case-sensitively) can be returned from this function.
1538  */
1539 struct net80211_wlan *
1540 net80211_probe_finish_best ( struct net80211_probe_ctx *ctx )
1541 {
1542         struct net80211_wlan *best = NULL, *wlan;
1543
1544         if ( ! ctx )
1545                 return NULL;
1546
1547         list_for_each_entry ( wlan, ctx->beacons, list ) {
1548                 if ( ! best || best->signal < wlan->signal )
1549                         best = wlan;
1550         }
1551
1552         if ( best )
1553                 list_del ( &best->list );
1554         else
1555                 DBGC ( ctx->dev, "802.11 %p probe: found nothing for '%s'\n",
1556                        ctx->dev, ctx->essid );
1557
1558         net80211_free_wlanlist ( ctx->beacons );
1559
1560         net80211_keep_mgmt ( ctx->dev, ctx->old_keep_mgmt );
1561
1562         if ( ctx->probe )
1563                 free_iob ( ctx->probe );
1564
1565         free ( ctx );
1566
1567         return best;
1568 }
1569
1570
1571 /**
1572  * Finish probe of 802.11 networks, returning all networks found
1573  *
1574  * @v ctx       Probe context
1575  * @ret list    List of net80211_wlan detailing networks found
1576  *
1577  * If net80211_probe_start() was called with a particular SSID
1578  * parameter as filter, this will always return either an empty or a
1579  * one-element list.
1580  */
1581 struct list_head *net80211_probe_finish_all ( struct net80211_probe_ctx *ctx )
1582 {
1583         struct list_head *beacons = ctx->beacons;
1584
1585         if ( ! ctx )
1586                 return NULL;
1587
1588         net80211_keep_mgmt ( ctx->dev, ctx->old_keep_mgmt );
1589
1590         if ( ctx->probe )
1591                 free_iob ( ctx->probe );
1592
1593         free ( ctx );
1594
1595         return beacons;
1596 }
1597
1598
1599 /**
1600  * Free WLAN structure
1601  *
1602  * @v wlan      WLAN structure to free
1603  */
1604 void net80211_free_wlan ( struct net80211_wlan *wlan )
1605 {
1606         if ( wlan ) {
1607                 free_iob ( wlan->beacon );
1608                 free ( wlan );
1609         }
1610 }
1611
1612
1613 /**
1614  * Free list of WLAN structures
1615  *
1616  * @v list      List of WLAN structures to free
1617  */
1618 void net80211_free_wlanlist ( struct list_head *list )
1619 {
1620         struct net80211_wlan *wlan, *tmp;
1621
1622         if ( ! list )
1623                 return;
1624
1625         list_for_each_entry_safe ( wlan, tmp, list, list ) {
1626                 list_del ( &wlan->list );
1627                 net80211_free_wlan ( wlan );
1628         }
1629
1630         free ( list );
1631 }
1632
1633
1634 /** Number of ticks to wait for replies to association management frames */
1635 #define ASSOC_TIMEOUT   TICKS_PER_SEC
1636
1637 /** Number of times to try sending a particular association management frame */
1638 #define ASSOC_RETRIES   2
1639
1640 /**
1641  * Step 802.11 association process
1642  *
1643  * @v dev       802.11 device
1644  */
1645 static void net80211_step_associate ( struct net80211_device *dev )
1646 {
1647         int rc = 0;
1648         int status = dev->state & NET80211_STATUS_MASK;
1649
1650         /*
1651          * We use a sort of state machine implemented using bits in
1652          * the dev->state variable. At each call, we take the
1653          * logically first step that has not yet succeeded; either it
1654          * has not been tried yet, it's being retried, or it failed.
1655          * If it failed, we return an error indication; otherwise we
1656          * perform the step. If it succeeds, RX handling code will set
1657          * the appropriate status bit for us.
1658          *
1659          * Probe works a bit differently, since we have to step it
1660          * on every call instead of waiting for a packet to arrive
1661          * that will set the completion bit for us.
1662          */
1663
1664         /* If we're waiting for a reply, check for timeout condition */
1665         if ( dev->state & NET80211_WAITING ) {
1666                 /* Sanity check */
1667                 if ( ! dev->associating )
1668                         return;
1669
1670                 if ( currticks() - dev->ctx.assoc->last_packet > ASSOC_TIMEOUT ) {
1671                         /* Timed out - fail if too many retries, or retry */
1672                         dev->ctx.assoc->times_tried++;
1673                         if ( ++dev->ctx.assoc->times_tried > ASSOC_RETRIES ) {
1674                                 rc = -ETIMEDOUT;
1675                                 goto fail;
1676                         }
1677                 } else {
1678                         /* Didn't time out - let it keep going */
1679                         return;
1680                 }
1681         } else {
1682                 if ( dev->state & NET80211_PROBED )
1683                         dev->ctx.assoc->times_tried = 0;
1684         }
1685
1686         if ( ! ( dev->state & NET80211_PROBED ) ) {
1687                 /* state: probe */
1688
1689                 if ( ! dev->ctx.probe ) {
1690                         /* start probe */
1691                         int active = fetch_intz_setting ( NULL,
1692                                                 &net80211_active_setting );
1693                         int band = dev->hw->bands;
1694
1695                         if ( active )
1696                                 band &= ~NET80211_BAND_BIT_5GHZ;
1697
1698                         rc = net80211_prepare_probe ( dev, band, active );
1699                         if ( rc )
1700                                 goto fail;
1701
1702                         dev->ctx.probe = net80211_probe_start ( dev, dev->essid,
1703                                                                 active );
1704                         if ( ! dev->ctx.probe ) {
1705                                 dev->assoc_rc = -ENOMEM;
1706                                 goto fail;
1707                         }
1708                 }
1709
1710                 rc = net80211_probe_step ( dev->ctx.probe );
1711                 if ( ! rc ) {
1712                         return; /* still going */
1713                 }
1714
1715                 dev->associating = net80211_probe_finish_best ( dev->ctx.probe );
1716                 dev->ctx.probe = NULL;
1717                 if ( ! dev->associating ) {
1718                         if ( rc > 0 ) /* "successful" probe found nothing */
1719                                 rc = -ETIMEDOUT;
1720                         goto fail;
1721                 }
1722
1723                 /* If we probed using a broadcast SSID, record that
1724                    fact for the settings applicator before we clobber
1725                    it with the specific SSID we've chosen. */
1726                 if ( ! dev->essid[0] )
1727                         dev->state |= NET80211_AUTO_SSID;
1728
1729                 DBGC ( dev, "802.11 %p found network %s (%s)\n", dev,
1730                        dev->associating->essid,
1731                        eth_ntoa ( dev->associating->bssid ) );
1732
1733                 dev->ctx.assoc = zalloc ( sizeof ( *dev->ctx.assoc ) );
1734                 if ( ! dev->ctx.assoc ) {
1735                         rc = -ENOMEM;
1736                         goto fail;
1737                 }
1738
1739                 dev->state |= NET80211_PROBED;
1740                 dev->ctx.assoc->method = IEEE80211_AUTH_OPEN_SYSTEM;
1741
1742                 return;
1743         }
1744
1745         /* Record time of sending the packet we're about to send, for timeout */
1746         dev->ctx.assoc->last_packet = currticks();
1747
1748         if ( ! ( dev->state & NET80211_AUTHENTICATED ) ) {
1749                 /* state: prepare and authenticate */
1750
1751                 if ( status != IEEE80211_STATUS_SUCCESS ) {
1752                         /* we tried authenticating already, but failed */
1753                         int method = dev->ctx.assoc->method;
1754
1755                         if ( method == IEEE80211_AUTH_OPEN_SYSTEM &&
1756                              ( status == IEEE80211_STATUS_AUTH_CHALL_INVALID ||
1757                                status == IEEE80211_STATUS_AUTH_ALGO_UNSUPP ) ) {
1758                                 /* Maybe this network uses Shared Key? */
1759                                 dev->ctx.assoc->method =
1760                                         IEEE80211_AUTH_SHARED_KEY;
1761                         } else {
1762                                 goto fail;
1763                         }
1764                 }
1765
1766                 DBGC ( dev, "802.11 %p authenticating with method %d\n", dev,
1767                        dev->ctx.assoc->method );
1768
1769                 rc = net80211_prepare_assoc ( dev, dev->associating );
1770                 if ( rc )
1771                         goto fail;
1772
1773                 rc = net80211_send_auth ( dev, dev->associating,
1774                                           dev->ctx.assoc->method );
1775                 if ( rc )
1776                         goto fail;
1777
1778                 return;
1779         }
1780
1781         if ( ! ( dev->state & NET80211_ASSOCIATED ) ) {
1782                 /* state: associate */
1783
1784                 if ( status != IEEE80211_STATUS_SUCCESS )
1785                         goto fail;
1786
1787                 DBGC ( dev, "802.11 %p associating\n", dev );
1788
1789                 if ( dev->handshaker && dev->handshaker->start &&
1790                      ! dev->handshaker->started ) {
1791                         rc = dev->handshaker->start ( dev );
1792                         if ( rc < 0 )
1793                                 goto fail;
1794                         dev->handshaker->started = 1;
1795                 }
1796
1797                 rc = net80211_send_assoc ( dev, dev->associating );
1798                 if ( rc )
1799                         goto fail;
1800
1801                 return;
1802         }
1803
1804         if ( ! ( dev->state & NET80211_CRYPTO_SYNCED ) ) {
1805                 /* state: crypto sync */
1806                 DBGC ( dev, "802.11 %p security handshaking\n", dev );
1807
1808                 if ( ! dev->handshaker || ! dev->handshaker->step ) {
1809                         dev->state |= NET80211_CRYPTO_SYNCED;
1810                         return;
1811                 }
1812
1813                 rc = dev->handshaker->step ( dev );
1814
1815                 if ( rc < 0 ) {
1816                         /* Only record the returned error if we're
1817                            still marked as associated, because an
1818                            asynchronous error will have already been
1819                            reported to net80211_deauthenticate() and
1820                            assoc_rc thereby set. */
1821                         if ( dev->state & NET80211_ASSOCIATED )
1822                                 dev->assoc_rc = rc;
1823                         rc = 0;
1824                         goto fail;
1825                 }
1826
1827                 if ( rc > 0 ) {
1828                         dev->assoc_rc = 0;
1829                         dev->state |= NET80211_CRYPTO_SYNCED;
1830                 }
1831                 return;
1832         }
1833
1834         /* state: done! */
1835         netdev_link_up ( dev->netdev );
1836         dev->assoc_rc = 0;
1837         dev->state &= ~NET80211_WORKING;
1838
1839         free ( dev->ctx.assoc );
1840         dev->ctx.assoc = NULL;
1841
1842         net80211_free_wlan ( dev->associating );
1843         dev->associating = NULL;
1844
1845         dev->rctl = rc80211_init ( dev );
1846
1847         process_del ( &dev->proc_assoc );
1848
1849         DBGC ( dev, "802.11 %p associated with %s (%s)\n", dev,
1850                dev->essid, eth_ntoa ( dev->bssid ) );
1851
1852         return;
1853
1854  fail:
1855         dev->state &= ~( NET80211_WORKING | NET80211_WAITING );
1856         if ( rc )
1857                 dev->assoc_rc = rc;
1858
1859         netdev_link_err ( dev->netdev, dev->assoc_rc );
1860
1861         /* We never reach here from the middle of a probe, so we don't
1862            need to worry about freeing dev->ctx.probe. */
1863
1864         if ( dev->state & NET80211_PROBED ) {
1865                 free ( dev->ctx.assoc );
1866                 dev->ctx.assoc = NULL;
1867         }
1868
1869         net80211_free_wlan ( dev->associating );
1870         dev->associating = NULL;
1871
1872         process_del ( &dev->proc_assoc );
1873
1874         DBGC ( dev, "802.11 %p association failed (state=%04x): "
1875                "%s\n", dev, dev->state, strerror ( dev->assoc_rc ) );
1876
1877         /* Try it again: */
1878         net80211_autoassociate ( dev );
1879 }
1880
1881 /**
1882  * Check for 802.11 SSID or key updates
1883  *
1884  * This acts as a settings applicator; if the user changes netX/ssid,
1885  * and netX is currently open, the association task will be invoked
1886  * again. If the user changes the encryption key, the current security
1887  * handshaker will be asked to update its state to match; if that is
1888  * impossible without reassociation, we reassociate.
1889  */
1890 static int net80211_check_settings_update ( void )
1891 {
1892         struct net80211_device *dev;
1893         char ssid[IEEE80211_MAX_SSID_LEN + 1];
1894         int key_reassoc;
1895
1896         list_for_each_entry ( dev, &net80211_devices, list ) {
1897                 if ( ! netdev_is_open ( dev->netdev ) )
1898                         continue;
1899
1900                 key_reassoc = 0;
1901                 if ( dev->handshaker && dev->handshaker->change_key &&
1902                      dev->handshaker->change_key ( dev ) < 0 )
1903                         key_reassoc = 1;
1904
1905                 fetch_string_setting ( netdev_settings ( dev->netdev ),
1906                                        &net80211_ssid_setting, ssid,
1907                                        IEEE80211_MAX_SSID_LEN + 1 );
1908
1909                 if ( key_reassoc ||
1910                      ( ! ( ! ssid[0] && ( dev->state & NET80211_AUTO_SSID ) ) &&
1911                        strcmp ( ssid, dev->essid ) != 0 ) ) {
1912                         DBGC ( dev, "802.11 %p updating association: "
1913                                "%s -> %s\n", dev, dev->essid, ssid );
1914                         net80211_autoassociate ( dev );
1915                 }
1916         }
1917
1918         return 0;
1919 }
1920
1921 /**
1922  * Start 802.11 association process
1923  *
1924  * @v dev       802.11 device
1925  *
1926  * If the association process is running, it will be restarted.
1927  */
1928 void net80211_autoassociate ( struct net80211_device *dev )
1929 {
1930         if ( ! ( dev->state & NET80211_WORKING ) ) {
1931                 DBGC2 ( dev, "802.11 %p spawning association process\n", dev );
1932                 process_add ( &dev->proc_assoc );
1933         } else {
1934                 DBGC2 ( dev, "802.11 %p restarting association\n", dev );
1935         }
1936
1937         /* Clean up everything an earlier association process might
1938            have been in the middle of using */
1939         if ( dev->associating )
1940                 net80211_free_wlan ( dev->associating );
1941
1942         if ( ! ( dev->state & NET80211_PROBED ) )
1943                 net80211_free_wlan (
1944                         net80211_probe_finish_best ( dev->ctx.probe ) );
1945         else
1946                 free ( dev->ctx.assoc );
1947
1948         /* Reset to a clean state */
1949         fetch_string_setting ( netdev_settings ( dev->netdev ),
1950                                &net80211_ssid_setting, dev->essid,
1951                                IEEE80211_MAX_SSID_LEN + 1 );
1952         dev->ctx.probe = NULL;
1953         dev->associating = NULL;
1954         dev->assoc_rc = 0;
1955         net80211_set_state ( dev, NET80211_PROBED, NET80211_WORKING, 0 );
1956 }
1957
1958 /**
1959  * Pick TX rate for RTS/CTS packets based on data rate
1960  *
1961  * @v dev       802.11 device
1962  *
1963  * The RTS/CTS rate is the fastest TX rate marked as "basic" that is
1964  * not faster than the data rate.
1965  */
1966 static void net80211_set_rtscts_rate ( struct net80211_device *dev )
1967 {
1968         u16 datarate = dev->rates[dev->rate];
1969         u16 rtsrate = 0;
1970         int rts_idx = -1;
1971         int i;
1972
1973         for ( i = 0; i < dev->nr_rates; i++ ) {
1974                 u16 rate = dev->rates[i];
1975
1976                 if ( ! ( dev->basic_rates & ( 1 << i ) ) || rate > datarate )
1977                         continue;
1978
1979                 if ( rate > rtsrate ) {
1980                         rtsrate = rate;
1981                         rts_idx = i;
1982                 }
1983         }
1984
1985         /* If this is in initialization, we might not have any basic
1986            rates; just use the first data rate in that case. */
1987         if ( rts_idx < 0 )
1988                 rts_idx = 0;
1989
1990         dev->rtscts_rate = rts_idx;
1991 }
1992
1993 /**
1994  * Set data transmission rate for 802.11 device
1995  *
1996  * @v dev       802.11 device
1997  * @v rate      Rate to set, as index into @c dev->rates array
1998  */
1999 void net80211_set_rate_idx ( struct net80211_device *dev, int rate )
2000 {
2001         assert ( netdev_is_open ( dev->netdev ) );
2002
2003         if ( rate >= 0 && rate < dev->nr_rates && rate != dev->rate ) {
2004                 DBGC2 ( dev, "802.11 %p changing rate from %d->%d Mbps\n",
2005                         dev, dev->rates[dev->rate] / 10,
2006                         dev->rates[rate] / 10 );
2007
2008                 dev->rate = rate;
2009                 net80211_set_rtscts_rate ( dev );
2010                 dev->op->config ( dev, NET80211_CFG_RATE );
2011         }
2012 }
2013
2014 /**
2015  * Configure 802.11 device to transmit on a certain channel
2016  *
2017  * @v dev       802.11 device
2018  * @v channel   Channel number (1-11 for 2.4GHz) to transmit on
2019  */
2020 int net80211_change_channel ( struct net80211_device *dev, int channel )
2021 {
2022         int i, oldchan = dev->channel;
2023
2024         assert ( netdev_is_open ( dev->netdev ) );
2025
2026         for ( i = 0; i < dev->nr_channels; i++ ) {
2027                 if ( dev->channels[i].channel_nr == channel ) {
2028                         dev->channel = i;
2029                         break;
2030                 }
2031         }
2032
2033         if ( i == dev->nr_channels )
2034                 return -ENOENT;
2035
2036         if ( i != oldchan )
2037                 return dev->op->config ( dev, NET80211_CFG_CHANNEL );
2038
2039         return 0;
2040 }
2041
2042 /**
2043  * Prepare 802.11 device channel and rate set for scanning
2044  *
2045  * @v dev       802.11 device
2046  * @v band      RF band(s) on which to prepare for scanning
2047  * @v active    Whether the scanning will be active
2048  * @ret rc      Return status code
2049  */
2050 int net80211_prepare_probe ( struct net80211_device *dev, int band,
2051                              int active )
2052 {
2053         assert ( netdev_is_open ( dev->netdev ) );
2054
2055         if ( active && ( band & NET80211_BAND_BIT_5GHZ ) ) {
2056                 DBGC ( dev, "802.11 %p cannot perform active scanning on "
2057                        "5GHz band\n", dev );
2058                 return -EINVAL_ACTIVE_SCAN;
2059         }
2060
2061         if ( band == 0 ) {
2062                 /* This can happen for a 5GHz-only card with 5GHz
2063                    scanning masked out by an active request. */
2064                 DBGC ( dev, "802.11 %p asked to prepare for scanning nothing\n",
2065                        dev );
2066                 return -EINVAL_ACTIVE_SCAN;
2067         }
2068
2069         dev->nr_channels = 0;
2070
2071         if ( active )
2072                 net80211_add_channels ( dev, 1, 11, NET80211_REG_TXPOWER );
2073         else {
2074                 if ( band & NET80211_BAND_BIT_2GHZ )
2075                         net80211_add_channels ( dev, 1, 14,
2076                                                 NET80211_REG_TXPOWER );
2077                 if ( band & NET80211_BAND_BIT_5GHZ )
2078                         net80211_add_channels ( dev, 36, 8,
2079                                                 NET80211_REG_TXPOWER );
2080         }
2081
2082         net80211_filter_hw_channels ( dev );
2083
2084         /* Use channel 1 for now */
2085         dev->channel = 0;
2086         dev->op->config ( dev, NET80211_CFG_CHANNEL );
2087
2088         /* Always do active probes at lowest (presumably first) speed */
2089         dev->rate = 0;
2090         dev->nr_rates = 1;
2091         dev->rates[0] = dev->hw->rates[dev->channels[0].band][0];
2092         dev->op->config ( dev, NET80211_CFG_RATE );
2093
2094         return 0;
2095 }
2096
2097 /**
2098  * Prepare 802.11 device channel and rate set for communication
2099  *
2100  * @v dev       802.11 device
2101  * @v wlan      WLAN to prepare for communication with
2102  * @ret rc      Return status code
2103  */
2104 int net80211_prepare_assoc ( struct net80211_device *dev,
2105                              struct net80211_wlan *wlan )
2106 {
2107         struct ieee80211_frame *hdr = wlan->beacon->data;
2108         struct ieee80211_beacon *beacon =
2109                 ( struct ieee80211_beacon * ) hdr->data;
2110         struct net80211_handshaker *handshaker;
2111         int rc;
2112
2113         assert ( netdev_is_open ( dev->netdev ) );
2114
2115         net80211_set_state ( dev, NET80211_ASSOCIATED, 0, 0 );
2116         memcpy ( dev->bssid, wlan->bssid, ETH_ALEN );
2117         strcpy ( dev->essid, wlan->essid );
2118
2119         free ( dev->rsn_ie );
2120         dev->rsn_ie = NULL;
2121
2122         dev->last_beacon_timestamp = beacon->timestamp;
2123         dev->tx_beacon_interval = 1024 * beacon->beacon_interval;
2124
2125         /* Barring an IE that tells us the channel outright, assume
2126            the channel we heard this AP best on is the channel it's
2127            communicating on. */
2128         net80211_change_channel ( dev, wlan->channel );
2129
2130         rc = net80211_process_capab ( dev, beacon->capability );
2131         if ( rc )
2132                 return rc;
2133
2134         rc = net80211_process_ie ( dev, beacon->info_element,
2135                                    wlan->beacon->tail );
2136         if ( rc )
2137                 return rc;
2138
2139         /* Associate at the lowest rate so we know it'll get through */
2140         dev->rate = 0;
2141         dev->op->config ( dev, NET80211_CFG_RATE );
2142
2143         /* Free old handshaker and crypto, if they exist */
2144         if ( dev->handshaker && dev->handshaker->stop &&
2145              dev->handshaker->started )
2146                 dev->handshaker->stop ( dev );
2147         free ( dev->handshaker );
2148         dev->handshaker = NULL;
2149         free ( dev->crypto );
2150         free ( dev->gcrypto );
2151         dev->crypto = dev->gcrypto = NULL;
2152
2153         /* Find new security handshaker to use */
2154         for_each_table_entry ( handshaker, NET80211_HANDSHAKERS ) {
2155                 if ( handshaker->protocol == wlan->handshaking ) {
2156                         dev->handshaker = zalloc ( sizeof ( *handshaker ) +
2157                                                    handshaker->priv_len );
2158                         if ( ! dev->handshaker )
2159                                 return -ENOMEM;
2160
2161                         memcpy ( dev->handshaker, handshaker,
2162                                  sizeof ( *handshaker ) );
2163                         dev->handshaker->priv = ( ( void * ) dev->handshaker +
2164                                                   sizeof ( *handshaker ) );
2165                         break;
2166                 }
2167         }
2168
2169         if ( ( wlan->handshaking != NET80211_SECPROT_NONE ) &&
2170              ! dev->handshaker ) {
2171                 DBGC ( dev, "802.11 %p no support for handshaking scheme %d\n",
2172                        dev, wlan->handshaking );
2173                 return -( ENOTSUP | ( wlan->handshaking << 8 ) );
2174         }
2175
2176         /* Initialize security handshaker */
2177         if ( dev->handshaker ) {
2178                 rc = dev->handshaker->init ( dev );
2179                 if ( rc < 0 )
2180                         return rc;
2181         }
2182
2183         return 0;
2184 }
2185
2186 /**
2187  * Send 802.11 initial authentication frame
2188  *
2189  * @v dev       802.11 device
2190  * @v wlan      WLAN to authenticate with
2191  * @v method    Authentication method
2192  * @ret rc      Return status code
2193  *
2194  * @a method may be 0 for Open System authentication or 1 for Shared
2195  * Key authentication. Open System provides no security in association
2196  * whatsoever, relying on encryption for confidentiality, but Shared
2197  * Key actively introduces security problems and is very rarely used.
2198  */
2199 int net80211_send_auth ( struct net80211_device *dev,
2200                          struct net80211_wlan *wlan, int method )
2201 {
2202         struct io_buffer *iob = alloc_iob ( 64 );
2203         struct ieee80211_auth *auth;
2204
2205         net80211_set_state ( dev, 0, NET80211_WAITING, 0 );
2206         iob_reserve ( iob, IEEE80211_TYP_FRAME_HEADER_LEN );
2207         auth = iob_put ( iob, sizeof ( *auth ) );
2208         auth->algorithm = method;
2209         auth->tx_seq = 1;
2210         auth->status = 0;
2211
2212         return net80211_tx_mgmt ( dev, IEEE80211_STYPE_AUTH, wlan->bssid, iob );
2213 }
2214
2215 /**
2216  * Handle receipt of 802.11 authentication frame
2217  *
2218  * @v dev       802.11 device
2219  * @v iob       I/O buffer
2220  *
2221  * If the authentication method being used is Shared Key, and the
2222  * frame that was received included challenge text, the frame is
2223  * encrypted using the cryptosystem currently in effect and sent back
2224  * to the AP to complete the authentication.
2225  */
2226 static void net80211_handle_auth ( struct net80211_device *dev,
2227                                    struct io_buffer *iob )
2228 {
2229         struct ieee80211_frame *hdr = iob->data;
2230         struct ieee80211_auth *auth =
2231             ( struct ieee80211_auth * ) hdr->data;
2232
2233         if ( auth->tx_seq & 1 ) {
2234                 DBGC ( dev, "802.11 %p authentication received improperly "
2235                        "directed frame (seq. %d)\n", dev, auth->tx_seq );
2236                 net80211_set_state ( dev, NET80211_WAITING, 0,
2237                                      IEEE80211_STATUS_FAILURE );
2238                 return;
2239         }
2240
2241         if ( auth->status != IEEE80211_STATUS_SUCCESS ) {
2242                 DBGC ( dev, "802.11 %p authentication failed: status %d\n",
2243                        dev, auth->status );
2244                 net80211_set_state ( dev, NET80211_WAITING, 0,
2245                                      auth->status );
2246                 return;
2247         }
2248
2249         if ( auth->algorithm == IEEE80211_AUTH_SHARED_KEY && ! dev->crypto ) {
2250                 DBGC ( dev, "802.11 %p can't perform shared-key authentication "
2251                        "without a cryptosystem\n", dev );
2252                 net80211_set_state ( dev, NET80211_WAITING, 0,
2253                                      IEEE80211_STATUS_FAILURE );
2254                 return;
2255         }
2256
2257         if ( auth->algorithm == IEEE80211_AUTH_SHARED_KEY &&
2258              auth->tx_seq == 2 ) {
2259                 /* Since the iob we got is going to be freed as soon
2260                    as we return, we can do some in-place
2261                    modification. */
2262                 auth->tx_seq = 3;
2263                 auth->status = 0;
2264
2265                 memcpy ( hdr->addr2, hdr->addr1, ETH_ALEN );
2266                 memcpy ( hdr->addr1, hdr->addr3, ETH_ALEN );
2267
2268                 netdev_tx ( dev->netdev,
2269                             dev->crypto->encrypt ( dev->crypto, iob ) );
2270                 return;
2271         }
2272
2273         net80211_set_state ( dev, NET80211_WAITING, NET80211_AUTHENTICATED,
2274                              IEEE80211_STATUS_SUCCESS );
2275
2276         return;
2277 }
2278
2279 /**
2280  * Send 802.11 association frame
2281  *
2282  * @v dev       802.11 device
2283  * @v wlan      WLAN to associate with
2284  * @ret rc      Return status code
2285  */
2286 int net80211_send_assoc ( struct net80211_device *dev,
2287                           struct net80211_wlan *wlan )
2288 {
2289         struct io_buffer *iob = alloc_iob ( 128 );
2290         struct ieee80211_assoc_req *assoc;
2291         union ieee80211_ie *ie;
2292
2293         net80211_set_state ( dev, 0, NET80211_WAITING, 0 );
2294
2295         iob_reserve ( iob, IEEE80211_TYP_FRAME_HEADER_LEN );
2296         assoc = iob->data;
2297
2298         assoc->capability = IEEE80211_CAPAB_MANAGED;
2299         if ( ! ( dev->hw->flags & NET80211_HW_NO_SHORT_PREAMBLE ) )
2300                 assoc->capability |= IEEE80211_CAPAB_SHORT_PMBL;
2301         if ( ! ( dev->hw->flags & NET80211_HW_NO_SHORT_SLOT ) )
2302                 assoc->capability |= IEEE80211_CAPAB_SHORT_SLOT;
2303         if ( wlan->crypto )
2304                 assoc->capability |= IEEE80211_CAPAB_PRIVACY;
2305
2306         assoc->listen_interval = 1;
2307
2308         ie = net80211_marshal_request_info ( dev, assoc->info_element );
2309
2310         DBGP ( "802.11 %p about to send association request:\n", dev );
2311         DBGP_HD ( iob->data, ( void * ) ie - iob->data );
2312
2313         iob_put ( iob, ( void * ) ie - iob->data );
2314
2315         return net80211_tx_mgmt ( dev, IEEE80211_STYPE_ASSOC_REQ,
2316                                   wlan->bssid, iob );
2317 }
2318
2319 /**
2320  * Handle receipt of 802.11 association reply frame
2321  *
2322  * @v dev       802.11 device
2323  * @v iob       I/O buffer
2324  */
2325 static void net80211_handle_assoc_reply ( struct net80211_device *dev,
2326                                           struct io_buffer *iob )
2327 {
2328         struct ieee80211_frame *hdr = iob->data;
2329         struct ieee80211_assoc_resp *assoc =
2330                 ( struct ieee80211_assoc_resp * ) hdr->data;
2331
2332         net80211_process_capab ( dev, assoc->capability );
2333         net80211_process_ie ( dev, assoc->info_element, iob->tail );
2334
2335         if ( assoc->status != IEEE80211_STATUS_SUCCESS ) {
2336                 DBGC ( dev, "802.11 %p association failed: status %d\n",
2337                        dev, assoc->status );
2338                 net80211_set_state ( dev, NET80211_WAITING, 0,
2339                                      assoc->status );
2340                 return;
2341         }
2342
2343         /* ESSID was filled before the association request was sent */
2344         memcpy ( dev->bssid, hdr->addr3, ETH_ALEN );
2345         dev->aid = assoc->aid;
2346
2347         net80211_set_state ( dev, NET80211_WAITING, NET80211_ASSOCIATED,
2348                              IEEE80211_STATUS_SUCCESS );
2349 }
2350
2351
2352 /**
2353  * Send 802.11 disassociation frame
2354  *
2355  * @v dev       802.11 device
2356  * @v reason    Reason for disassociation
2357  * @v deauth    If TRUE, send deauthentication instead of disassociation
2358  * @ret rc      Return status code
2359  */
2360 static int net80211_send_disassoc ( struct net80211_device *dev, int reason,
2361                                     int deauth )
2362 {
2363         struct io_buffer *iob = alloc_iob ( 64 );
2364         struct ieee80211_disassoc *disassoc;
2365
2366         if ( ! ( dev->state & NET80211_ASSOCIATED ) )
2367                 return -EINVAL;
2368
2369         net80211_set_state ( dev, NET80211_ASSOCIATED, 0, 0 );
2370         iob_reserve ( iob, IEEE80211_TYP_FRAME_HEADER_LEN );
2371         disassoc = iob_put ( iob, sizeof ( *disassoc ) );
2372         disassoc->reason = reason;
2373
2374         return net80211_tx_mgmt ( dev, deauth ? IEEE80211_STYPE_DEAUTH :
2375                                   IEEE80211_STYPE_DISASSOC, dev->bssid, iob );
2376 }
2377
2378
2379 /**
2380  * Deauthenticate from current network and try again
2381  *
2382  * @v dev       802.11 device
2383  * @v rc        Return status code indicating reason
2384  *
2385  * The deauthentication will be sent using an 802.11 "unspecified
2386  * reason", as is common, but @a rc will be set as a link-up
2387  * error to aid the user in debugging.
2388  */
2389 void net80211_deauthenticate ( struct net80211_device *dev, int rc )
2390 {
2391         net80211_send_disassoc ( dev, IEEE80211_REASON_UNSPECIFIED, 1 );
2392         dev->assoc_rc = rc;
2393         netdev_link_err ( dev->netdev, rc );
2394
2395         net80211_autoassociate ( dev );
2396 }
2397
2398
2399 /** Smoothing factor (1-7) for link quality calculation */
2400 #define LQ_SMOOTH       7
2401
2402 /**
2403  * Update link quality information based on received beacon
2404  *
2405  * @v dev       802.11 device
2406  * @v iob       I/O buffer containing beacon
2407  * @ret rc      Return status code
2408  */
2409 static void net80211_update_link_quality ( struct net80211_device *dev,
2410                                            struct io_buffer *iob )
2411 {
2412         struct ieee80211_frame *hdr = iob->data;
2413         struct ieee80211_beacon *beacon;
2414         u32 dt, rxi;
2415
2416         if ( ! ( dev->state & NET80211_ASSOCIATED ) )
2417                 return;
2418
2419         beacon = ( struct ieee80211_beacon * ) hdr->data;
2420         dt = ( u32 ) ( beacon->timestamp - dev->last_beacon_timestamp );
2421         rxi = dev->rx_beacon_interval;
2422
2423         rxi = ( LQ_SMOOTH * rxi ) + ( ( 8 - LQ_SMOOTH ) * dt );
2424         dev->rx_beacon_interval = rxi >> 3;
2425
2426         dev->last_beacon_timestamp = beacon->timestamp;
2427 }
2428
2429
2430 /**
2431  * Handle receipt of 802.11 management frame
2432  *
2433  * @v dev       802.11 device
2434  * @v iob       I/O buffer
2435  * @v signal    Signal strength of received frame
2436  */
2437 static void net80211_handle_mgmt ( struct net80211_device *dev,
2438                                    struct io_buffer *iob, int signal )
2439 {
2440         struct ieee80211_frame *hdr = iob->data;
2441         struct ieee80211_disassoc *disassoc;
2442         u16 stype = hdr->fc & IEEE80211_FC_SUBTYPE;
2443         int keep = 0;
2444         int is_deauth = ( stype == IEEE80211_STYPE_DEAUTH );
2445
2446         if ( ( hdr->fc & IEEE80211_FC_TYPE ) != IEEE80211_TYPE_MGMT ) {
2447                 free_iob ( iob );
2448                 return;         /* only handle management frames */
2449         }
2450
2451         switch ( stype ) {
2452                 /* We reconnect on deauthentication and disassociation. */
2453         case IEEE80211_STYPE_DEAUTH:
2454         case IEEE80211_STYPE_DISASSOC:
2455                 disassoc = ( struct ieee80211_disassoc * ) hdr->data;
2456                 net80211_set_state ( dev, is_deauth ? NET80211_AUTHENTICATED :
2457                                      NET80211_ASSOCIATED, 0,
2458                                      NET80211_IS_REASON | disassoc->reason );
2459                 DBGC ( dev, "802.11 %p %s: reason %d\n",
2460                        dev, is_deauth ? "deauthenticated" : "disassociated",
2461                        disassoc->reason );
2462
2463                 /* Try to reassociate, in case it's transient. */
2464                 net80211_autoassociate ( dev );
2465
2466                 break;
2467
2468                 /* We handle authentication and association. */
2469         case IEEE80211_STYPE_AUTH:
2470                 if ( ! ( dev->state & NET80211_AUTHENTICATED ) )
2471                         net80211_handle_auth ( dev, iob );
2472                 break;
2473
2474         case IEEE80211_STYPE_ASSOC_RESP:
2475         case IEEE80211_STYPE_REASSOC_RESP:
2476                 if ( ! ( dev->state & NET80211_ASSOCIATED ) )
2477                         net80211_handle_assoc_reply ( dev, iob );
2478                 break;
2479
2480                 /* We pass probes and beacons onto network scanning
2481                    code. Pass actions for future extensibility. */
2482         case IEEE80211_STYPE_BEACON:
2483                 net80211_update_link_quality ( dev, iob );
2484                 /* fall through */
2485         case IEEE80211_STYPE_PROBE_RESP:
2486         case IEEE80211_STYPE_ACTION:
2487                 if ( dev->keep_mgmt ) {
2488                         struct net80211_rx_info *rxinf;
2489                         rxinf = zalloc ( sizeof ( *rxinf ) );
2490                         if ( ! rxinf ) {
2491                                 DBGC ( dev, "802.11 %p out of memory\n", dev );
2492                                 break;
2493                         }
2494                         rxinf->signal = signal;
2495                         list_add_tail ( &iob->list, &dev->mgmt_queue );
2496                         list_add_tail ( &rxinf->list, &dev->mgmt_info_queue );
2497                         keep = 1;
2498                 }
2499                 break;
2500
2501         case IEEE80211_STYPE_PROBE_REQ:
2502                 /* Some nodes send these broadcast. Ignore them. */
2503                 break;
2504
2505         case IEEE80211_STYPE_ASSOC_REQ:
2506         case IEEE80211_STYPE_REASSOC_REQ:
2507                 /* We should never receive these, only send them. */
2508                 DBGC ( dev, "802.11 %p received strange management request "
2509                        "(%04x)\n", dev, stype );
2510                 break;
2511
2512         default:
2513                 DBGC ( dev, "802.11 %p received unimplemented management "
2514                        "packet (%04x)\n", dev, stype );
2515                 break;
2516         }
2517
2518         if ( ! keep )
2519                 free_iob ( iob );
2520 }
2521
2522 /* ---------- Packet handling functions ---------- */
2523
2524 /**
2525  * Free buffers used by 802.11 fragment cache entry
2526  *
2527  * @v dev       802.11 device
2528  * @v fcid      Fragment cache entry index
2529  *
2530  * After this function, the referenced entry will be marked unused.
2531  */
2532 static void net80211_free_frags ( struct net80211_device *dev, int fcid )
2533 {
2534         int j;
2535         struct net80211_frag_cache *frag = &dev->frags[fcid];
2536
2537         for ( j = 0; j < 16; j++ ) {
2538                 if ( frag->iob[j] ) {
2539                         free_iob ( frag->iob[j] );
2540                         frag->iob[j] = NULL;
2541                 }
2542         }
2543
2544         frag->seqnr = 0;
2545         frag->start_ticks = 0;
2546         frag->in_use = 0;
2547 }
2548
2549 /**
2550  * Accumulate 802.11 fragments into one I/O buffer
2551  *
2552  * @v dev       802.11 device
2553  * @v fcid      Fragment cache entry index
2554  * @v nfrags    Number of fragments received
2555  * @v size      Sum of sizes of all fragments, including headers
2556  * @ret iob     I/O buffer containing reassembled packet
2557  *
2558  * This function does not free the fragment buffers.
2559  */
2560 static struct io_buffer *net80211_accum_frags ( struct net80211_device *dev,
2561                                                 int fcid, int nfrags, int size )
2562 {
2563         struct net80211_frag_cache *frag = &dev->frags[fcid];
2564         int hdrsize = IEEE80211_TYP_FRAME_HEADER_LEN;
2565         int nsize = size - hdrsize * ( nfrags - 1 );
2566         int i;
2567
2568         struct io_buffer *niob = alloc_iob ( nsize );
2569         struct ieee80211_frame *hdr;
2570
2571         /* Add the header from the first one... */
2572         memcpy ( iob_put ( niob, hdrsize ), frag->iob[0]->data, hdrsize );
2573
2574         /* ... and all the data from all of them. */
2575         for ( i = 0; i < nfrags; i++ ) {
2576                 int len = iob_len ( frag->iob[i] ) - hdrsize;
2577                 memcpy ( iob_put ( niob, len ),
2578                          frag->iob[i]->data + hdrsize, len );
2579         }
2580
2581         /* Turn off the fragment bit. */
2582         hdr = niob->data;
2583         hdr->fc &= ~IEEE80211_FC_MORE_FRAG;
2584
2585         return niob;
2586 }
2587
2588 /**
2589  * Handle receipt of 802.11 fragment
2590  *
2591  * @v dev       802.11 device
2592  * @v iob       I/O buffer containing fragment
2593  * @v signal    Signal strength with which fragment was received
2594  */
2595 static void net80211_rx_frag ( struct net80211_device *dev,
2596                                struct io_buffer *iob, int signal )
2597 {
2598         struct ieee80211_frame *hdr = iob->data;
2599         int fragnr = IEEE80211_FRAG ( hdr->seq );
2600
2601         if ( fragnr == 0 && ( hdr->fc & IEEE80211_FC_MORE_FRAG ) ) {
2602                 /* start a frag cache entry */
2603                 int i, newest = -1;
2604                 u32 curr_ticks = currticks(), newest_ticks = 0;
2605                 u32 timeout = ticks_per_sec() * NET80211_FRAG_TIMEOUT;
2606
2607                 for ( i = 0; i < NET80211_NR_CONCURRENT_FRAGS; i++ ) {
2608                         if ( dev->frags[i].in_use == 0 )
2609                                 break;
2610
2611                         if ( dev->frags[i].start_ticks + timeout >=
2612                              curr_ticks ) {
2613                                 net80211_free_frags ( dev, i );
2614                                 break;
2615                         }
2616
2617                         if ( dev->frags[i].start_ticks > newest_ticks ) {
2618                                 newest = i;
2619                                 newest_ticks = dev->frags[i].start_ticks;
2620                         }
2621                 }
2622
2623                 /* If we're being sent more concurrent fragmented
2624                    packets than we can handle, drop the newest so the
2625                    older ones have time to complete. */
2626                 if ( i == NET80211_NR_CONCURRENT_FRAGS ) {
2627                         i = newest;
2628                         net80211_free_frags ( dev, i );
2629                 }
2630
2631                 dev->frags[i].in_use = 1;
2632                 dev->frags[i].seqnr = IEEE80211_SEQNR ( hdr->seq );
2633                 dev->frags[i].start_ticks = currticks();
2634                 dev->frags[i].iob[0] = iob;
2635                 return;
2636         } else {
2637                 int i;
2638                 for ( i = 0; i < NET80211_NR_CONCURRENT_FRAGS; i++ ) {
2639                         if ( dev->frags[i].in_use && dev->frags[i].seqnr ==
2640                              IEEE80211_SEQNR ( hdr->seq ) )
2641                                 break;
2642                 }
2643                 if ( i == NET80211_NR_CONCURRENT_FRAGS ) {
2644                         /* Drop non-first not-in-cache fragments */
2645                         DBGC ( dev, "802.11 %p dropped fragment fc=%04x "
2646                                "seq=%04x\n", dev, hdr->fc, hdr->seq );
2647                         free_iob ( iob );
2648                         return;
2649                 }
2650
2651                 dev->frags[i].iob[fragnr] = iob;
2652
2653                 if ( ! ( hdr->fc & IEEE80211_FC_MORE_FRAG ) ) {
2654                         int j, size = 0;
2655                         for ( j = 0; j < fragnr; j++ ) {
2656                                 size += iob_len ( dev->frags[i].iob[j] );
2657                                 if ( dev->frags[i].iob[j] == NULL )
2658                                         break;
2659                         }
2660                         if ( j == fragnr ) {
2661                                 /* We've got everything */
2662                                 struct io_buffer *niob =
2663                                     net80211_accum_frags ( dev, i, fragnr,
2664                                                            size );
2665                                 net80211_free_frags ( dev, i );
2666                                 net80211_rx ( dev, niob, signal, 0 );
2667                         } else {
2668                                 DBGC ( dev, "802.11 %p dropping fragmented "
2669                                        "packet due to out-of-order arrival, "
2670                                        "fc=%04x seq=%04x\n", dev, hdr->fc,
2671                                        hdr->seq );
2672                                 net80211_free_frags ( dev, i );
2673                         }
2674                 }
2675         }
2676 }
2677
2678 /**
2679  * Handle receipt of 802.11 frame
2680  *
2681  * @v dev       802.11 device
2682  * @v iob       I/O buffer
2683  * @v signal    Received signal strength
2684  * @v rate      Bitrate at which frame was received, in 100 kbps units
2685  *
2686  * If the rate or signal is unknown, 0 should be passed.
2687  */
2688 void net80211_rx ( struct net80211_device *dev, struct io_buffer *iob,
2689                    int signal, u16 rate )
2690 {
2691         struct ieee80211_frame *hdr = iob->data;
2692         u16 type = hdr->fc & IEEE80211_FC_TYPE;
2693         if ( ( hdr->fc & IEEE80211_FC_VERSION ) != IEEE80211_THIS_VERSION )
2694                 goto drop;      /* drop invalid-version packets */
2695
2696         if ( type == IEEE80211_TYPE_CTRL )
2697                 goto drop;      /* we don't handle control packets,
2698                                    the hardware does */
2699
2700         if ( dev->last_rx_seq == hdr->seq )
2701                 goto drop;      /* avoid duplicate packet */
2702         dev->last_rx_seq = hdr->seq;
2703
2704         if ( dev->hw->flags & NET80211_HW_RX_HAS_FCS ) {
2705                 /* discard the FCS */
2706                 iob_unput ( iob, 4 );
2707         }
2708
2709         /* Only decrypt packets from our BSSID, to avoid spurious errors */
2710         if ( ( hdr->fc & IEEE80211_FC_PROTECTED ) &&
2711              ! memcmp ( hdr->addr2, dev->bssid, ETH_ALEN ) ) {
2712                 /* Decrypt packet; record and drop if it fails */
2713                 struct io_buffer *niob;
2714                 struct net80211_crypto *crypto = dev->crypto;
2715
2716                 if ( ! dev->crypto ) {
2717                         DBGC ( dev, "802.11 %p cannot decrypt packet "
2718                                "without a cryptosystem\n", dev );
2719                         goto drop_crypt;
2720                 }
2721
2722                 if ( ( hdr->addr1[0] & 1 ) && dev->gcrypto ) {
2723                         /* Use group decryption if needed */
2724                         crypto = dev->gcrypto;
2725                 }
2726
2727                 niob = crypto->decrypt ( crypto, iob );
2728                 if ( ! niob ) {
2729                         DBGC ( dev, "802.11 %p decryption error\n", dev );
2730                         goto drop_crypt;
2731                 }
2732                 free_iob ( iob );
2733                 iob = niob;
2734                 hdr = iob->data;
2735         }
2736
2737         dev->last_signal = signal;
2738
2739         /* Fragments go into the frag cache or get dropped. */
2740         if ( IEEE80211_FRAG ( hdr->seq ) != 0
2741              || ( hdr->fc & IEEE80211_FC_MORE_FRAG ) ) {
2742                 net80211_rx_frag ( dev, iob, signal );
2743                 return;
2744         }
2745
2746         /* Management frames get handled, enqueued, or dropped. */
2747         if ( type == IEEE80211_TYPE_MGMT ) {
2748                 net80211_handle_mgmt ( dev, iob, signal );
2749                 return;
2750         }
2751
2752         /* Data frames get dropped or sent to the net_device. */
2753         if ( ( hdr->fc & IEEE80211_FC_SUBTYPE ) != IEEE80211_STYPE_DATA )
2754                 goto drop;      /* drop QoS, CFP, or null data packets */
2755
2756         /* Update rate-control algorithm */
2757         if ( dev->rctl )
2758                 rc80211_update_rx ( dev, hdr->fc & IEEE80211_FC_RETRY, rate );
2759
2760         /* Pass packet onward */
2761         if ( dev->state & NET80211_ASSOCIATED ) {
2762                 netdev_rx ( dev->netdev, iob );
2763                 return;
2764         }
2765
2766         /* No association? Drop it. */
2767         goto drop;
2768
2769  drop_crypt:
2770         netdev_rx_err ( dev->netdev, NULL, EINVAL_CRYPTO_REQUEST );
2771  drop:
2772         DBGC2 ( dev, "802.11 %p dropped packet fc=%04x seq=%04x\n", dev,
2773                 hdr->fc, hdr->seq );
2774         free_iob ( iob );
2775         return;
2776 }
2777
2778 /** Indicate an error in receiving a packet
2779  *
2780  * @v dev       802.11 device
2781  * @v iob       I/O buffer with received packet, or NULL
2782  * @v rc        Error code
2783  *
2784  * This logs the error with the wrapping net_device, and frees iob if
2785  * it is passed.
2786  */
2787 void net80211_rx_err ( struct net80211_device *dev,
2788                        struct io_buffer *iob, int rc )
2789 {
2790         netdev_rx_err ( dev->netdev, iob, rc );
2791 }
2792
2793 /** Indicate the completed transmission of a packet
2794  *
2795  * @v dev       802.11 device
2796  * @v iob       I/O buffer of transmitted packet
2797  * @v retries   Number of times this packet was retransmitted
2798  * @v rc        Error code, or 0 for success
2799  *
2800  * This logs an error with the wrapping net_device if one occurred,
2801  * and removes and frees the I/O buffer from its TX queue. The
2802  * provided retry information is used to tune our transmission rate.
2803  *
2804  * If the packet did not need to be retransmitted because it was
2805  * properly ACKed the first time, @a retries should be 0.
2806  */
2807 void net80211_tx_complete ( struct net80211_device *dev,
2808                             struct io_buffer *iob, int retries, int rc )
2809 {
2810         /* Update rate-control algorithm */
2811         if ( dev->rctl )
2812                 rc80211_update_tx ( dev, retries, rc );
2813
2814         /* Pass completion onward */
2815         netdev_tx_complete_err ( dev->netdev, iob, rc );
2816 }
2817
2818 /** Common 802.11 errors */
2819 struct errortab common_wireless_errors[] __errortab = {
2820         __einfo_errortab ( EINFO_EINVAL_CRYPTO_REQUEST ),
2821         __einfo_errortab ( EINFO_ECONNRESET_UNSPECIFIED ),
2822         __einfo_errortab ( EINFO_ECONNRESET_INACTIVITY ),
2823         __einfo_errortab ( EINFO_ECONNRESET_4WAY_TIMEOUT ),
2824         __einfo_errortab ( EINFO_ECONNRESET_8021X_FAILURE ),
2825         __einfo_errortab ( EINFO_ECONNREFUSED_FAILURE ),
2826         __einfo_errortab ( EINFO_ECONNREFUSED_ASSOC_DENIED ),
2827         __einfo_errortab ( EINFO_ECONNREFUSED_AUTH_ALGO_UNSUPP ),
2828 };