root / firmware / microblaze / lib / arp_cache.c @ bb86022d
History | View | Annotate | Download (1.82 KB)
| 1 | 2b6c895b | Josh Blum | /* -*- c++ -*- */
|
|---|---|---|---|
| 2 | /*
|
||
| 3 | * Copyright 2009 Ettus Research LLC
|
||
| 4 | *
|
||
| 5 | * This program is free software: you can redistribute it and/or modify
|
||
| 6 | * it under the terms of the GNU General Public License as published by
|
||
| 7 | * the Free Software Foundation, either version 3 of the License, or
|
||
| 8 | * (at your option) any later version.
|
||
| 9 | *
|
||
| 10 | * This program is distributed in the hope that it will be useful,
|
||
| 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||
| 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||
| 13 | * GNU General Public License for more details.
|
||
| 14 | *
|
||
| 15 | * You should have received a copy of the GNU General Public License
|
||
| 16 | * along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||
| 17 | */
|
||
| 18 | #ifdef HAVE_CONFIG_H
|
||
| 19 | #include <config.h> |
||
| 20 | #endif
|
||
| 21 | #include "arp_cache.h" |
||
| 22 | #include <stddef.h> |
||
| 23 | |||
| 24 | typedef struct { |
||
| 25 | struct ip_addr ip;
|
||
| 26 | eth_mac_addr_t mac; |
||
| 27 | } arp_cache_t; |
||
| 28 | |||
| 29 | #define NENTRIES 8 // power-of-2 |
||
| 30 | |||
| 31 | static size_t nentries;
|
||
| 32 | static size_t victim;
|
||
| 33 | static arp_cache_t cache[NENTRIES];
|
||
| 34 | |||
| 35 | void
|
||
| 36 | arp_cache_init(void)
|
||
| 37 | {
|
||
| 38 | nentries = 0;
|
||
| 39 | victim = 0;
|
||
| 40 | } |
||
| 41 | |||
| 42 | // returns non-negative index if found, else -1
|
||
| 43 | static int |
||
| 44 | arp_cache_lookup(const struct ip_addr *ip) |
||
| 45 | {
|
||
| 46 | int i;
|
||
| 47 | for (i = 0; i < nentries; i++) |
||
| 48 | if (cache[i].ip.addr == ip->addr)
|
||
| 49 | return i;
|
||
| 50 | |||
| 51 | return -1; |
||
| 52 | } |
||
| 53 | |||
| 54 | static int |
||
| 55 | arp_cache_alloc(void)
|
||
| 56 | {
|
||
| 57 | if (nentries < NENTRIES)
|
||
| 58 | return nentries++;
|
||
| 59 | |||
| 60 | int i = victim;
|
||
| 61 | victim = (victim + 1) % NENTRIES;
|
||
| 62 | return i;
|
||
| 63 | } |
||
| 64 | |||
| 65 | void
|
||
| 66 | arp_cache_update(const struct ip_addr *ip, |
||
| 67 | const eth_mac_addr_t *mac)
|
||
| 68 | {
|
||
| 69 | int i = arp_cache_lookup(ip);
|
||
| 70 | if (i < 0){ |
||
| 71 | i = arp_cache_alloc(); |
||
| 72 | cache[i].ip = *ip; |
||
| 73 | cache[i].mac = *mac; |
||
| 74 | } |
||
| 75 | else {
|
||
| 76 | cache[i].mac = *mac; |
||
| 77 | } |
||
| 78 | } |
||
| 79 | |||
| 80 | bool
|
||
| 81 | arp_cache_lookup_mac(const struct ip_addr *ip, |
||
| 82 | eth_mac_addr_t *mac) |
||
| 83 | {
|
||
| 84 | int i = arp_cache_lookup(ip);
|
||
| 85 | if (i < 0) |
||
| 86 | return false; |
||
| 87 | |||
| 88 | *mac = cache[i].mac; |
||
| 89 | return true; |
||
| 90 | } |