+static int first_free_afid(uint32_t *afids)
+{
+ int afid;
+
+ afid = AFID_MIN;
+ while (afid <= AFID_MAX && !~afids[AFID_AIDX(afid)])
+ afid += 32;
+ while (afid <= AFID_MAX && AFID_TEST(afids, afid))
+ afid++;
+ if (afid > AFID_MAX) {
+ ERROR("Can't compute a valid afid");
+ errno = EADDRNOTAVAIL;
+ afid = -1;
+ }
+ return afid;
+}
+
+static int get_new_afid()
+{
+ int afid;
+
+ /* ensure existing afid bitmap */
+ if (afids_array == NULL) {
+ afids_array = malloc(AFID_ACNT * sizeof(uint32_t));
+ if (afids_array == NULL || update_afids(afids_array) < 0)
+ return -1;
+ }
+
+ /* allocates the afid */
+ afid = first_free_afid(afids_array);
+ if (afid < 0 && errno == EADDRNOTAVAIL) {
+ /* no more ids, try to rescan */
+ memset(afids_array, 0, AFID_ACNT * sizeof(uint32_t));
+ if (update_afids(afids_array) >= 0)
+ afid = first_free_afid(afids_array);
+ }
+ if (afid >= 0)
+ AFID_SET(afids_array, afid);
+
+ return afid;
+}
+