fix
[oweals/gnunet.git] / src / fs / gnunet-service-fs.c
index 44d787a964d080f3aec2355a940d2c32f02c618c..0f603651ea4bfc0680831763f5814c65edae62ac 100644 (file)
  * @author Christian Grothoff
  *
  * TODO:
- * - bound_priority should not charge if we are not loaded (excess-based economy)
- * - have a way to drop queries based on load (or just forward...)
  * - introduce random latency in processing
- * - consider more precise latency estimation (per-peer & request)
- * - better algorithm for priority selection for requests we initiate?
- * - tell other peers to stop migration if our PUTs fail (or if
- *   we don't support migration per configuration?)
  * - more statistics
  */
 #include "platform.h"
 #include <float.h>
 #include "gnunet_constants.h"
 #include "gnunet_core_service.h"
+#include "gnunet_dht_service.h"
 #include "gnunet_datastore_service.h"
+#include "gnunet_load_lib.h"
 #include "gnunet_peer_lib.h"
 #include "gnunet_protocols.h"
 #include "gnunet_signatures.h"
 
 #define DEBUG_FS GNUNET_NO
 
+/**
+ * Should we introduce random latency in processing?  Required for proper
+ * implementation of GAP, but can be disabled for performance evaluation of
+ * the basic routing algorithm.
+ */
+#define SUPPORT_DELAYS GNUNET_NO
+
 /**
  * Maximum number of outgoing messages we queue per peer.
  */
 #define MAX_QUEUE_PER_PEER 16
 
+/**
+ * Size for the hash map for DHT requests from the FS
+ * service.  Should be about the number of concurrent
+ * DHT requests we plan to make.
+ */
+#define FS_DHT_HT_SIZE 1024
+
 /**
  * How often do we flush trust values to disk?
  */
 #define TRUST_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
 
+/**
+ * How often do we at most PUT content into the DHT?
+ */
+#define MAX_DHT_PUT_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
 
 /**
  * Inverse of the probability that we will submit the same query
  */
 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 45)
 
-
-
 /**
  * Maximum number of requests (from other peers) that we're
  * willing to have pending at any given point in time.
- * FIXME: set from configuration.
  */
-static uint64_t max_pending_requests = (32 * 1024);
+static unsigned long long max_pending_requests = (32 * 1024);
 
 
 /**
@@ -135,6 +146,11 @@ struct PendingMessage
    */
   void *cont_cls;
 
+  /**
+   * Do not transmit this pending message until this deadline.
+   */
+  struct GNUNET_TIME_Absolute delay_until;
+
   /**
    * Size of the reply; actual reply message follows
    * at the end of this struct.
@@ -179,6 +195,18 @@ struct ConnectedPeer
    */ 
   struct GNUNET_TIME_Relative avg_delay;
 
+  /**
+   * Point in time until which this peer does not want us to migrate content
+   * to it.
+   */
+  struct GNUNET_TIME_Absolute migration_blocked;
+
+  /**
+   * Time until when we blocked this peer from migrating
+   * data to us.
+   */
+  struct GNUNET_TIME_Absolute last_migration_block;
+
   /**
    * Handle for an active request for transmission to this
    * peer, or NULL.
@@ -197,6 +225,23 @@ struct ConnectedPeer
    */
   struct PendingMessage *pending_messages_tail;
 
+  /**
+   * How long does it typically take for us to transmit a message
+   * to this peer?  (delay between the request being issued and
+   * the callback being invoked).
+   */
+  struct GNUNET_LOAD_Value *transmission_delay;
+
+  /**
+   * Time when the last transmission request was issued.
+   */
+  struct GNUNET_TIME_Absolute last_transmission_request_start;
+
+  /**
+   * ID of delay task for scheduling transmission.
+   */
+  GNUNET_SCHEDULER_TaskIdentifier delayed_transmission_request_task;
+
   /**
    * Average priority of successful replies.  Calculated
    * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
@@ -430,6 +475,11 @@ struct PendingRequest
    */
   struct GNUNET_CORE_InformationRequestContext *irc;
 
+  /**
+   * Reference to DHT get operation for this request (or NULL).
+   */
+  struct GNUNET_DHT_GetHandle *dht_get;
+
   /**
    * Hash code of all replies that we have seen so far (only valid
    * if client is not NULL since we only track replies like this for
@@ -558,12 +608,17 @@ struct PendingRequest
   /**
    * Remove this request after transmission of the current response.
    */
-  int16_t do_remove;
+  int8_t do_remove;
+
+  /**
+   * GNUNET_YES if we should not forward this request to other peers.
+   */
+  int8_t local_only;
 
   /**
    * GNUNET_YES if we should not forward this request to other peers.
    */
-  int16_t local_only;
+  int8_t forward_only;
 
 };
 
@@ -622,6 +677,15 @@ struct MigrationReadyBlock
  */
 static struct GNUNET_DATASTORE_Handle *dsh;
 
+/**
+ * Our block context.
+ */
+static struct GNUNET_BLOCK_Context *block_ctx;
+
+/**
+ * Our block configuration.
+ */
+static struct GNUNET_CONFIGURATION_Handle *block_cfg;
 
 /**
  * Our scheduler.
@@ -689,6 +753,16 @@ static struct MigrationReadyBlock *mig_tail;
  */
 static struct GNUNET_DATASTORE_QueueEntry *mig_qe;
 
+/**
+ * Request to datastore for DHT PUTs (or NULL).
+ */
+static struct GNUNET_DATASTORE_QueueEntry *dht_qe;
+
+/**
+ * Type we will request for the next DHT PUT round from the datastore.
+ */
+static enum GNUNET_BLOCK_Type dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
+
 /**
  * Where do we store trust information?
  */
@@ -699,12 +773,22 @@ static char *trustDirectory;
  */
 static GNUNET_SCHEDULER_TaskIdentifier mig_task;
 
+/**
+ * ID of task that collects blocks for DHT PUTs.
+ */
+static GNUNET_SCHEDULER_TaskIdentifier dht_task;
+
 /**
  * What is the maximum frequency at which we are allowed to
  * poll the datastore for migration content?
  */
 static struct GNUNET_TIME_Relative min_migration_delay;
 
+/**
+ * Handle for DHT operations.
+ */
+static struct GNUNET_DHT_Handle *dht_handle;
+
 /**
  * Size of the doubly-linked list of migration blocks.
  */
@@ -715,6 +799,12 @@ static unsigned int mig_size;
  */
 static int active_migration;
 
+/**
+ * How many entires with zero anonymity do we currently estimate
+ * to have in the database?
+ */
+static unsigned int zero_anonymity_count_estimate;
+
 /**
  * Typical priorities we're seeing from other peers right now.  Since
  * most priorities will be zero, this value is the weighted average of
@@ -727,6 +817,38 @@ static int active_migration;
  */
 static double current_priorities;
 
+/**
+ * Datastore 'GET' load tracking.
+ */
+static struct GNUNET_LOAD_Value *datastore_get_load;
+
+/**
+ * Datastore 'PUT' load tracking.
+ */
+static struct GNUNET_LOAD_Value *datastore_put_load;
+
+/**
+ * How long do requests typically stay in the routing table?
+ */
+static struct GNUNET_LOAD_Value *rt_entry_lifetime;
+
+/**
+ * We've just now completed a datastore request.  Update our
+ * datastore load calculations.
+ *
+ * @param start time when the datastore request was issued
+ */
+static void
+update_datastore_delays (struct GNUNET_TIME_Absolute start)
+{
+  struct GNUNET_TIME_Relative delay;
+
+  delay = GNUNET_TIME_absolute_get_duration (start);
+  GNUNET_LOAD_update (datastore_get_load,
+                     delay.value);
+}
+
+
 /**
  * Get the filename under which we would store the GNUNET_HELLO_Message
  * for the given host and protocol.
@@ -765,7 +887,6 @@ transmit_to_peer (void *cls,
 
 /* ******************* clean up functions ************************ */
 
-
 /**
  * Delete the given migration block.
  *
@@ -828,6 +949,8 @@ consider_migration (void *cls,
   unsigned int repl;
   
   /* consider 'cp' as a migration target for mb */
+  if (GNUNET_TIME_absolute_get_remaining (cp->migration_blocked).value > 0)
+    return GNUNET_YES; /* peer has requested no migration! */
   if (mb != NULL)
     {
       GNUNET_PEER_resolve (cp->pid,
@@ -870,7 +993,7 @@ consider_migration (void *cls,
     }
 
   /* consider scheduling transmission to cp for content migration */
-  if (cp->cth != NULL)
+  if (cp->cth != NULL)        
     return GNUNET_YES; 
   msize = 0;
   pos = mig_head;
@@ -898,6 +1021,11 @@ consider_migration (void *cls,
              msize,
              GNUNET_h2s (key));
 #endif
+  if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
+    {
+      GNUNET_SCHEDULER_cancel (sched, cp->delayed_transmission_request_task);
+      cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
+    }
   cp->cth 
     = GNUNET_CORE_notify_transmit_ready (core,
                                         0, GNUNET_TIME_UNIT_FOREVER_REL,
@@ -921,6 +1049,19 @@ gather_migration_blocks (void *cls,
                         const struct GNUNET_SCHEDULER_TaskContext *tc);
 
 
+
+
+/**
+ * Task that is run periodically to obtain blocks for DHT PUTs.
+ * 
+ * @param cls type of blocks to gather
+ * @param tc scheduler context (unused)
+ */
+static void
+gather_dht_put_blocks (void *cls,
+                      const struct GNUNET_SCHEDULER_TaskContext *tc);
+
+
 /**
  * If the migration task is not currently running, consider
  * (re)scheduling it with the appropriate delay.
@@ -930,6 +1071,8 @@ consider_migration_gathering ()
 {
   struct GNUNET_TIME_Relative delay;
 
+  if (dsh == NULL)
+    return;
   if (mig_qe != NULL)
     return;
   if (mig_task != GNUNET_SCHEDULER_NO_TASK)
@@ -947,6 +1090,41 @@ consider_migration_gathering ()
 }
 
 
+/**
+ * If the DHT PUT gathering task is not currently running, consider
+ * (re)scheduling it with the appropriate delay.
+ */
+static void
+consider_dht_put_gathering (void *cls)
+{
+  struct GNUNET_TIME_Relative delay;
+
+  if (dsh == NULL)
+    return;
+  if (dht_qe != NULL)
+    return;
+  if (dht_task != GNUNET_SCHEDULER_NO_TASK)
+    return;
+  if (zero_anonymity_count_estimate > 0)
+    {
+      delay = GNUNET_TIME_relative_divide (GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY,
+                                          zero_anonymity_count_estimate);
+      delay = GNUNET_TIME_relative_min (delay,
+                                       MAX_DHT_PUT_FREQ);
+    }
+  else
+    {
+      /* if we have NO zero-anonymity content yet, wait 5 minutes for some to
+        (hopefully) appear */
+      delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5);
+    }
+  dht_task = GNUNET_SCHEDULER_add_delayed (sched,
+                                          delay,
+                                          &gather_dht_put_blocks,
+                                          cls);
+}
+
+
 /**
  * Process content offered for migration.
  *
@@ -964,7 +1142,7 @@ consider_migration_gathering ()
 static void
 process_migration_content (void *cls,
                           const GNUNET_HashCode * key,
-                          uint32_t size,
+                          size_t size,
                           const void *data,
                           enum GNUNET_BLOCK_Type type,
                           uint32_t priority,
@@ -981,7 +1159,7 @@ process_migration_content (void *cls,
        consider_migration_gathering ();
       return;
     }
-  if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
+  if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
     {
       if (GNUNET_OK !=
          GNUNET_FS_handle_on_demand_block (key, size, data,
@@ -989,7 +1167,9 @@ process_migration_content (void *cls,
                                            expiration, uid, 
                                            &process_migration_content,
                                            NULL))
-       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
+       {
+         GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
+       }
       return;
     }
 #if DEBUG_FS
@@ -1016,6 +1196,86 @@ process_migration_content (void *cls,
 }
 
 
+/**
+ * Function called upon completion of the DHT PUT operation.
+ */
+static void
+dht_put_continuation (void *cls,
+                     const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+  GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
+}
+
+
+/**
+ * Store content in DHT.
+ *
+ * @param cls closure
+ * @param key key for the content
+ * @param size number of bytes in data
+ * @param data content stored
+ * @param type type of the content
+ * @param priority priority of the content
+ * @param anonymity anonymity-level for the content
+ * @param expiration expiration time for the content
+ * @param uid unique identifier for the datum;
+ *        maybe 0 if no unique identifier is available
+ */
+static void
+process_dht_put_content (void *cls,
+                        const GNUNET_HashCode * key,
+                        size_t size,
+                        const void *data,
+                        enum GNUNET_BLOCK_Type type,
+                        uint32_t priority,
+                        uint32_t anonymity,
+                        struct GNUNET_TIME_Absolute
+                        expiration, uint64_t uid)
+{ 
+  static unsigned int counter;
+  static GNUNET_HashCode last_vhash;
+  static GNUNET_HashCode vhash;
+
+  if (key == NULL)
+    {
+      dht_qe = NULL;
+      consider_dht_put_gathering (cls);
+      return;
+    }
+  /* slightly funky code to estimate the total number of values with zero
+     anonymity from the maximum observed length of a monotonically increasing 
+     sequence of hashes over the contents */
+  GNUNET_CRYPTO_hash (data, size, &vhash);
+  if (GNUNET_CRYPTO_hash_cmp (&vhash, &last_vhash) <= 0)
+    {
+      if (zero_anonymity_count_estimate > 0)
+       zero_anonymity_count_estimate /= 2;
+      counter = 0;
+    }
+  last_vhash = vhash;
+  if (counter < 31)
+    counter++;
+  if (zero_anonymity_count_estimate < (1 << counter))
+    zero_anonymity_count_estimate = (1 << counter);
+#if DEBUG_FS
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+             "Retrieved block `%s' of type %u for DHT PUT\n",
+             GNUNET_h2s (key),
+             type);
+#endif
+  GNUNET_DHT_put (dht_handle,
+                 key,
+                 GNUNET_DHT_RO_NONE,
+                 type,
+                 size,
+                 data,
+                 expiration,
+                 GNUNET_TIME_UNIT_FOREVER_REL,
+                 &dht_put_continuation,
+                 cls);
+}
+
+
 /**
  * Task that is run periodically to obtain blocks for content
  * migration
@@ -1028,10 +1288,37 @@ gather_migration_blocks (void *cls,
                         const struct GNUNET_SCHEDULER_TaskContext *tc)
 {
   mig_task = GNUNET_SCHEDULER_NO_TASK;
-  mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, -1,
-                                       GNUNET_TIME_UNIT_FOREVER_REL,
-                                       &process_migration_content, NULL);
-  GNUNET_assert (mig_qe != NULL);
+  if (dsh != NULL)
+    {
+      mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, UINT_MAX,
+                                           GNUNET_TIME_UNIT_FOREVER_REL,
+                                           &process_migration_content, NULL);
+      GNUNET_assert (mig_qe != NULL);
+    }
+}
+
+
+/**
+ * Task that is run periodically to obtain blocks for DHT PUTs.
+ * 
+ * @param cls type of blocks to gather
+ * @param tc scheduler context (unused)
+ */
+static void
+gather_dht_put_blocks (void *cls,
+                      const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+  dht_task = GNUNET_SCHEDULER_NO_TASK;
+  if (dsh != NULL)
+    {
+      if (dht_put_type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
+       dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
+      dht_qe = GNUNET_DATASTORE_get_zero_anonymity (dsh, 0, UINT_MAX,
+                                                   GNUNET_TIME_UNIT_FOREVER_REL,
+                                                   dht_put_type++,
+                                                   &process_dht_put_content, NULL);
+      GNUNET_assert (dht_qe != NULL);
+    }
 }
 
 
@@ -1071,12 +1358,20 @@ destroy_pending_message (struct PendingMessage *pm,
   TransmissionContinuation cont;
   void *cont_cls;
 
-  GNUNET_assert (pml->pm == pm);
-  GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
   cont = pm->cont;
   cont_cls = pm->cont_cls;
-  destroy_pending_message_list_entry (pml);
-  cont (cont_cls, tpid);  
+  if (pml != NULL)
+    {
+      GNUNET_assert (pml->pm == pm);
+      GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
+      destroy_pending_message_list_entry (pml);
+    }
+  else
+    {
+      GNUNET_free (pm);
+    }
+  if (cont != NULL)
+    cont (cont_cls, tpid);  
 }
 
 
@@ -1111,17 +1406,24 @@ destroy_pending_request (struct PendingRequest *pr)
                                -1,
                                GNUNET_NO);
     }
-  /* might have already been removed from map in 'process_reply' (if
-     there was a unique reply) or never inserted if it was a
-     duplicate; hence ignore the return value here */
-  (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
-                                              &pr->query,
-                                              pr);
+  if (GNUNET_YES == 
+      GNUNET_CONTAINER_multihashmap_remove (query_request_map,
+                                           &pr->query,
+                                           pr))
+    {
+      GNUNET_LOAD_update (rt_entry_lifetime,
+                         GNUNET_TIME_absolute_get_duration (pr->start_time).value);
+    }
   if (pr->qe != NULL)
      {
       GNUNET_DATASTORE_cancel (pr->qe);
       pr->qe = NULL;
     }
+  if (pr->dht_get != NULL)
+    {
+      GNUNET_DHT_get_stop (pr->dht_get);
+      pr->dht_get = NULL;
+    }
   if (pr->client_request_list != NULL)
     {
       GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
@@ -1196,6 +1498,7 @@ peer_connect_handler (void *cls,
   uint32_t trust;
   
   cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
+  cp->transmission_delay = GNUNET_LOAD_value_init ();
   cp->pid = GNUNET_PEER_intern (peer);
 
   fn = get_trust_filename (peer);
@@ -1408,9 +1711,18 @@ peer_disconnect_handler (void *cls,
   GNUNET_PEER_change_rc (cp->pid, -1);
   GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
   if (NULL != cp->cth)
-    GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
+    {
+      GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
+      cp->cth = NULL;
+    }
+  if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
+    {
+      GNUNET_SCHEDULER_cancel (sched, cp->delayed_transmission_request_task);
+      cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
+    }
   while (NULL != (pm = cp->pending_messages_head))
     destroy_pending_message (pm, 0 /* delivery failed */);
+  GNUNET_LOAD_value_free (cp->transmission_delay);
   GNUNET_break (0 == cp->pending_requests);
   GNUNET_free (cp);
 }
@@ -1539,11 +1851,21 @@ shutdown_task (void *cls,
       GNUNET_DATASTORE_cancel (mig_qe);
       mig_qe = NULL;
     }
+  if (dht_qe != NULL)
+    {
+      GNUNET_DATASTORE_cancel (dht_qe);
+      dht_qe = NULL;
+    }
   if (GNUNET_SCHEDULER_NO_TASK != mig_task)
     {
       GNUNET_SCHEDULER_cancel (sched, mig_task);
       mig_task = GNUNET_SCHEDULER_NO_TASK;
     }
+  if (GNUNET_SCHEDULER_NO_TASK != dht_task)
+    {
+      GNUNET_SCHEDULER_cancel (sched, dht_task);
+      dht_task = GNUNET_SCHEDULER_NO_TASK;
+    }
   while (client_list != NULL)
     handle_client_disconnect (NULL,
                              client_list->client);
@@ -1559,6 +1881,8 @@ shutdown_task (void *cls,
   GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
   GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
   query_request_map = NULL;
+  GNUNET_LOAD_value_free (rt_entry_lifetime);
+  rt_entry_lifetime = NULL;
   GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
   GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
   peer_request_map = NULL;
@@ -1570,12 +1894,25 @@ shutdown_task (void *cls,
       GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
       stats = NULL;
     }
-  GNUNET_DATASTORE_disconnect (dsh,
-                              GNUNET_NO);
+  if (dsh != NULL)
+    {
+      GNUNET_DATASTORE_disconnect (dsh,
+                                  GNUNET_NO);
+      dsh = NULL;
+    }
   while (mig_head != NULL)
     delete_migration_block (mig_head);
   GNUNET_assert (0 == mig_size);
-  dsh = NULL;
+  GNUNET_DHT_disconnect (dht_handle);
+  dht_handle = NULL;
+  GNUNET_LOAD_value_free (datastore_get_load);
+  datastore_get_load = NULL;
+  GNUNET_LOAD_value_free (datastore_put_load);
+  datastore_put_load = NULL;
+  GNUNET_BLOCK_context_destroy (block_ctx);
+  block_ctx = NULL;
+  GNUNET_CONFIGURATION_destroy (block_cfg);
+  block_cfg = NULL;
   sched = NULL;
   cfg = NULL;  
   GNUNET_free_non_null (trustDirectory);
@@ -1586,6 +1923,39 @@ shutdown_task (void *cls,
 /* ******************* Utility functions  ******************** */
 
 
+/**
+ * We've had to delay a request for transmission to core, but now
+ * we should be ready.  Run it.
+ *
+ * @param cls the 'struct ConnectedPeer' for which a request was delayed
+ * @param tc task context (unused)
+ */
+static void
+delayed_transmission_request (void *cls,
+                             const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+  struct ConnectedPeer *cp = cls;
+  struct GNUNET_PeerIdentity pid;
+  struct PendingMessage *pm;
+
+  pm = cp->pending_messages_head;
+  cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
+  GNUNET_assert (cp->cth == NULL);
+  if (pm == NULL)
+    return;
+  GNUNET_PEER_resolve (cp->pid,
+                      &pid);
+  cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
+  cp->cth = GNUNET_CORE_notify_transmit_ready (core,
+                                              pm->priority,
+                                              GNUNET_CONSTANTS_SERVICE_TIMEOUT,
+                                              &pid,
+                                              pm->msize,
+                                              &transmit_to_peer,
+                                              cp);
+}
+
+
 /**
  * Transmit messages by copying it to the target buffer
  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
@@ -1605,13 +1975,16 @@ transmit_to_peer (void *cls,
 {
   struct ConnectedPeer *cp = cls;
   char *cbuf = buf;
-  struct GNUNET_PeerIdentity pid;
   struct PendingMessage *pm;
+  struct PendingMessage *next_pm;
+  struct GNUNET_TIME_Absolute now;
+  struct GNUNET_TIME_Relative min_delay;
   struct MigrationReadyBlock *mb;
   struct MigrationReadyBlock *next;
   struct PutMessage migm;
   size_t msize;
   unsigned int i;
+  struct GNUNET_PeerIdentity pid;
  
   cp->cth = NULL;
   if (NULL == buf)
@@ -1620,31 +1993,53 @@ transmit_to_peer (void *cls,
       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Dropping message, core too busy.\n");
 #endif
+      GNUNET_LOAD_update (cp->transmission_delay,
+                         UINT64_MAX);
       return 0;
-    }
+    }  
+  GNUNET_LOAD_update (cp->transmission_delay,
+                     GNUNET_TIME_absolute_get_duration (cp->last_transmission_request_start).value);
+  now = GNUNET_TIME_absolute_get ();
   msize = 0;
-  while ( (NULL != (pm = cp->pending_messages_head) ) &&
+  min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
+  next_pm = cp->pending_messages_head;
+  while ( (NULL != (pm = next_pm) ) &&
          (pm->msize <= size) )
     {
+      next_pm = pm->next;
+      if (pm->delay_until.value > now.value)
+       {
+         min_delay = GNUNET_TIME_relative_min (min_delay,
+                                               GNUNET_TIME_absolute_get_remaining (pm->delay_until));
+         continue;
+       }
       memcpy (&cbuf[msize], &pm[1], pm->msize);
       msize += pm->msize;
       size -= pm->msize;
+      if (NULL == pm->pml)
+       {
+         GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
+                                      cp->pending_messages_tail,
+                                      pm);
+         cp->pending_requests--;
+       }
       destroy_pending_message (pm, cp->pid);
     }
-  if (NULL != pm)
-    {
-      GNUNET_PEER_resolve (cp->pid,
-                          &pid);
-      cp->cth = GNUNET_CORE_notify_transmit_ready (core,
-                                                  pm->priority,
-                                                  GNUNET_CONSTANTS_SERVICE_TIMEOUT,
-                                                  &pid,
-                                                  pm->msize,
-                                                  &transmit_to_peer,
-                                                  cp);
+  if (pm != NULL)
+    min_delay = GNUNET_TIME_UNIT_ZERO;
+  if (NULL != cp->pending_messages_head)
+    {     
+      GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
+      cp->delayed_transmission_request_task
+       = GNUNET_SCHEDULER_add_delayed (sched,
+                                       min_delay,
+                                       &delayed_transmission_request,
+                                       cp);
     }
-  else
+  if (pm == NULL)
     {      
+      GNUNET_PEER_resolve (cp->pid,
+                          &pid);
       next = mig_head;
       while (NULL != (mb = next))
        {
@@ -1657,6 +2052,7 @@ transmit_to_peer (void *cls,
                  GNUNET_PEER_change_rc (mb->target_list[i], -1);
                  mb->target_list[i] = 0;
                  mb->used_targets++;
+                 memset (&migm, 0, sizeof (migm));
                  migm.header.size = htons (sizeof (migm) + mb->size);
                  migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
                  migm.type = htonl (mb->type);
@@ -1671,7 +2067,7 @@ transmit_to_peer (void *cls,
                  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                              "Pushing migration block `%s' (%u bytes) to `%s'\n",
                              GNUNET_h2s (&mb->query),
-                             mb->size,
+                             (unsigned int) mb->size,
                              GNUNET_i2s (&pid));
 #endif   
                  break;
@@ -1682,7 +2078,7 @@ transmit_to_peer (void *cls,
                  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                              "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
                              GNUNET_h2s (&mb->query),
-                             mb->size,
+                             (unsigned int) mb->size,
                              GNUNET_i2s (&pid));
 #endif   
                }
@@ -1700,9 +2096,9 @@ transmit_to_peer (void *cls,
     }
 #if DEBUG_FS
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-             "Transmitting %u bytes to peer %u\n",
-             msize,
-             cp->pid);
+             "Transmitting %u bytes to peer with PID %u\n",
+             (unsigned int) msize,
+             (unsigned int) cp->pid);
 #endif
   return msize;
 }
@@ -1726,14 +2122,17 @@ add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
 
   GNUNET_assert (pm->next == NULL);
   GNUNET_assert (pm->pml == NULL);    
-  pml = GNUNET_malloc (sizeof (struct PendingMessageList));
-  pml->req = pr;
-  pml->target = cp;
-  pml->pm = pm;
-  pm->pml = pml;  
-  GNUNET_CONTAINER_DLL_insert (pr->pending_head,
-                              pr->pending_tail,
-                              pml);
+  if (pr != NULL)
+    {
+      pml = GNUNET_malloc (sizeof (struct PendingMessageList));
+      pml->req = pr;
+      pml->target = cp;
+      pml->pm = pm;
+      pm->pml = pml;  
+      GNUNET_CONTAINER_DLL_insert (pr->pending_head,
+                                  pr->pending_tail,
+                                  pml);
+    }
   pos = cp->pending_messages_head;
   while ( (pos != NULL) &&
          (pm->priority < pos->priority) )
@@ -1747,8 +2146,17 @@ add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
     destroy_pending_message (cp->pending_messages_tail, 0);  
   GNUNET_PEER_resolve (cp->pid, &pid);
   if (NULL != cp->cth)
-    GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
+    {
+      GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
+      cp->cth = NULL;
+    }
+  if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
+    {
+      GNUNET_SCHEDULER_cancel (sched, cp->delayed_transmission_request_task);
+      cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
+    }
   /* need to schedule transmission */
+  cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
   cp->cth = GNUNET_CORE_notify_transmit_ready (core,
                                               cp->pending_messages_head->priority,
                                               MAX_TRANSMIT_DELAY,
@@ -1771,33 +2179,69 @@ add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
 
 
 /**
- * Mingle hash with the mingle_number to produce different bits.
+ * Test if the DATABASE (GET) load on this peer is too high
+ * to even consider processing the query at
+ * all.  
+ * 
+ * @return GNUNET_YES if the load is too high to do anything (load high)
+ *         GNUNET_NO to process normally (load normal)
+ *         GNUNET_SYSERR to process for free (load low)
  */
-static void
-mingle_hash (const GNUNET_HashCode * in,
-            int32_t mingle_number, 
-            GNUNET_HashCode * hc)
+static int
+test_get_load_too_high (uint32_t priority)
 {
-  GNUNET_HashCode m;
+  double ld;
 
-  GNUNET_CRYPTO_hash (&mingle_number, 
-                     sizeof (int32_t), 
-                     &m);
-  GNUNET_CRYPTO_hash_xor (&m, in, hc);
+  ld = GNUNET_LOAD_get_load (datastore_get_load);
+  if (ld < 1)
+    {
+      GNUNET_STATISTICS_update (stats,
+                               gettext_noop ("# requests done for free (low load)"),
+                               1,
+                               GNUNET_NO);
+      return GNUNET_SYSERR;
+    }
+  if (ld <= priority)
+    {
+      GNUNET_STATISTICS_update (stats,
+                               gettext_noop ("# requests done for a price (normal load)"),
+                               1,
+                               GNUNET_NO);
+      return GNUNET_NO;
+    }
+  GNUNET_STATISTICS_update (stats,
+                           gettext_noop ("# requests dropped due to high load"),
+                           1,
+                           GNUNET_NO);
+  return GNUNET_YES;
 }
 
 
+
+
 /**
- * Test if the load on this peer is too high
+ * Test if the DATABASE (PUT) load on this peer is too high
  * to even consider processing the query at
- * all.
+ * all.  
  * 
- * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
+ * @return GNUNET_YES if the load is too high to do anything (load high)
+ *         GNUNET_NO to process normally (load normal or low)
  */
 static int
-test_load_too_high ()
+test_put_load_too_high (uint32_t priority)
 {
-  return GNUNET_NO; // FIXME
+  double ld;
+
+  if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
+    return GNUNET_NO; /* very fast */
+  ld = GNUNET_LOAD_get_load (datastore_put_load);
+  if ( (ld < 1) || (ld < priority) )
+    return GNUNET_NO;
+  GNUNET_STATISTICS_update (stats,
+                           gettext_noop ("# storage requests dropped due to high load"),
+                           1,
+                           GNUNET_NO);
+  return GNUNET_YES;
 }
 
 
@@ -1949,7 +2393,9 @@ refresh_bloomfilter (struct PendingRequest *pr)
                                              BLOOMFILTER_K);
   for (i=0;i<pr->replies_seen_off;i++)
     {
-      mingle_hash (&pr->replies_seen[i], pr->mingle, &mhash);
+      GNUNET_BLOCK_mingle_hash (&pr->replies_seen[i],
+                               pr->mingle,
+                               &mhash);
       GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
     }
 }
@@ -2037,8 +2483,6 @@ target_reservation_cb (void *cls,
                                                     pr);
          return;  /* this target round failed */
        }
-      /* FIXME: if we are "quite" busy, we may still want to skip
-        this round; need more load detection code! */
       no_route = GNUNET_YES;
     }
   
@@ -2194,7 +2638,7 @@ target_peer_select_cb (void *cls,
                                        P2P_SUCCESS_LIST_SIZE);
       for (i=0;i<P2P_SUCCESS_LIST_SIZE;i++)
        if (cp->last_p2p_replies[i] == pr->cp->pid)
-         score += 1; /* likely successful based on hot path */
+         score += 1.0; /* likely successful based on hot path */
     }
   else
     {
@@ -2202,19 +2646,22 @@ target_peer_select_cb (void *cls,
                                        CS2P_SUCCESS_LIST_SIZE);
       for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
        if (cp->last_client_replies[i] == pr->client_request_list->client_list->client)
-         score += 1; /* likely successful based on hot path */
+         score += 1.0; /* likely successful based on hot path */
     }
   /* 3b) include latency */
   if (cp->avg_delay.value < 4 * TTL_DECREMENT)
-    score += 1; /* likely fast based on latency */
+    score += 1.0; /* likely fast based on latency */
   /* 3c) include priorities */
   if (cp->avg_priority <= pr->remaining_priority / 2.0)
-    score += 1; /* likely successful based on priorities */
+    score += 1.0; /* likely successful based on priorities */
   /* 3d) penalize for queue size */  
   score -= (2.0 * cp->pending_requests / (double) MAX_QUEUE_PER_PEER); 
   /* 3e) include peer proximity */
   score -= (2.0 * (GNUNET_CRYPTO_hash_distance_u32 (key,
                                                    &pr->query)) / (double) UINT32_MAX);
+  /* 4) super-bonus for being the known target */
+  if (pr->target_pid == cp->pid)
+    score += 100.0;
   /* store best-fit in closure */
 #if DEBUG_FS
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
@@ -2260,6 +2707,32 @@ bound_ttl (int32_t ttl_in, uint32_t prio)
 }
 
 
+/**
+ * Iterator called on each result obtained for a DHT
+ * operation that expects a reply
+ *
+ * @param cls closure
+ * @param exp when will this value expire
+ * @param key key of the result
+ * @param get_path NULL-terminated array of pointers
+ *                 to the peers on reverse GET path (or NULL if not recorded)
+ * @param put_path NULL-terminated array of pointers
+ *                 to the peers on the PUT path (or NULL if not recorded)
+ * @param type type of the result
+ * @param size number of bytes in data
+ * @param data pointer to the result data
+ */
+static void
+process_dht_reply (void *cls,
+                  struct GNUNET_TIME_Absolute exp,
+                  const GNUNET_HashCode * key,
+                  const struct GNUNET_PeerIdentity * const *get_path,
+                  const struct GNUNET_PeerIdentity * const *put_path,
+                  enum GNUNET_BLOCK_Type type,
+                  size_t size,
+                  const void *data);
+
+
 /**
  * We're processing a GET request and have decided
  * to forward it to other peers.  This function is called periodically
@@ -2293,6 +2766,24 @@ forward_request_task (void *cls,
     }
   if (GNUNET_YES == pr->local_only)
     return; /* configured to not do P2P search */
+  /* (0) try DHT */
+  if ( (0 == pr->anonymity_level) &&
+       (GNUNET_YES != pr->forward_only) &&
+       (pr->type != GNUNET_BLOCK_TYPE_FS_DBLOCK) &&
+       (pr->type != GNUNET_BLOCK_TYPE_FS_IBLOCK) )
+    {
+      pr->dht_get = GNUNET_DHT_get_start (dht_handle,
+                                         GNUNET_TIME_UNIT_FOREVER_REL,
+                                         pr->type,
+                                         &pr->query,
+                                         GNUNET_DHT_RO_NONE,
+                                         pr->bf,
+                                         pr->mingle,
+                                         pr->namespace,
+                                         (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
+                                         &process_dht_reply,
+                                         pr);
+    }
   /* (1) select target */
   psc.pr = pr;
   psc.target_score = -DBL_MAX;
@@ -2339,18 +2830,28 @@ forward_request_task (void *cls,
     }
 
   /* (3) reserve reply bandwidth */
-  cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
-                                         &psc.target.hashPubKey);
-  GNUNET_assert (NULL != cp);
-  pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
-                                               &psc.target,
-                                               GNUNET_CONSTANTS_SERVICE_TIMEOUT, 
-                                               GNUNET_BANDWIDTH_value_init (UINT32_MAX),
-                                               DBLOCK_SIZE * 2, 
-                                               cp->inc_preference,
-                                               &target_reservation_cb,
-                                               pr);
-  cp->inc_preference = 0;
+  if (GNUNET_NO == pr->forward_only)
+    {
+      cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
+                                             &psc.target.hashPubKey);
+      GNUNET_assert (NULL != cp);
+      pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
+                                                   &psc.target,
+                                                   GNUNET_CONSTANTS_SERVICE_TIMEOUT, 
+                                                   GNUNET_BANDWIDTH_value_init (UINT32_MAX),
+                                                   DBLOCK_SIZE * 2, 
+                                                   cp->inc_preference,
+                                                   &target_reservation_cb,
+                                                   pr);
+      cp->inc_preference = 0;
+    }
+  else
+    {
+      /* force forwarding */
+      static struct GNUNET_BANDWIDTH_Value32NBO zerobw;
+      target_reservation_cb (pr, &psc.target,
+                            zerobw, zerobw, 0, 0.0);
+    }
 }
 
 
@@ -2372,14 +2873,14 @@ transmit_reply_continuation (void *cls,
   
   switch (pr->type)
     {
-    case GNUNET_BLOCK_TYPE_DBLOCK:
-    case GNUNET_BLOCK_TYPE_IBLOCK:
+    case GNUNET_BLOCK_TYPE_FS_DBLOCK:
+    case GNUNET_BLOCK_TYPE_FS_IBLOCK:
       /* only one reply expected, done with the request! */
       destroy_pending_request (pr);
       break;
     case GNUNET_BLOCK_TYPE_ANY:
-    case GNUNET_BLOCK_TYPE_KBLOCK:
-    case GNUNET_BLOCK_TYPE_SBLOCK:
+    case GNUNET_BLOCK_TYPE_FS_KBLOCK:
+    case GNUNET_BLOCK_TYPE_FS_SBLOCK:
       break;
     default:
       GNUNET_break (0);
@@ -2457,7 +2958,7 @@ struct ProcessReplyClosure
   const void *data;
 
   /**
-   * Who gave us this reply? NULL for local host.
+   * Who gave us this reply? NULL for local host (or DHT)
    */
   struct ConnectedPeer *sender;
 
@@ -2471,12 +2972,6 @@ struct ProcessReplyClosure
    */
   size_t size;
 
-  /**
-   * Namespace that this reply belongs to
-   * (if it is of type SBLOCK).
-   */
-  GNUNET_HashCode namespace;
-
   /**
    * Type of the block.
    */
@@ -2487,10 +2982,20 @@ struct ProcessReplyClosure
    */
   uint32_t priority;
 
+  /**
+   * Evaluation result (returned).
+   */
+  enum GNUNET_BLOCK_EvaluationResult eval;
+
   /**
    * Did we finish processing the associated request?
    */ 
   int finished;
+
+  /**
+   * Did we find a matching request?
+   */
+  int request_found;
 };
 
 
@@ -2515,8 +3020,6 @@ process_reply (void *cls,
   struct PutMessage *pm;
   struct ConnectedPeer *cp;
   struct GNUNET_TIME_Relative cur_delay;
-  GNUNET_HashCode chash;
-  GNUNET_HashCode mhash;
   size_t msize;
 
 #if DEBUG_FS
@@ -2531,8 +3034,6 @@ process_reply (void *cls,
                            GNUNET_NO);
   if (prq->sender != NULL)
     {
-      /* FIXME: should we be more precise here and not use
-        "start_time" but a peer-specific time stamp? */
       cur_delay = GNUNET_TIME_absolute_get_duration (pr->start_time);
       prq->sender->avg_delay.value
        = (prq->sender->avg_delay.value * 
@@ -2562,14 +3063,19 @@ process_reply (void *cls,
          GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
        }
     }
-  GNUNET_CRYPTO_hash (prq->data,
-                     prq->size,
-                     &chash);
-  switch (prq->type)
+  prq->eval = GNUNET_BLOCK_evaluate (block_ctx,
+                                    prq->type,
+                                    key,
+                                    &pr->bf,
+                                    pr->mingle,
+                                    pr->namespace, (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
+                                    prq->data,
+                                    prq->size);
+  switch (prq->eval)
     {
-    case GNUNET_BLOCK_TYPE_DBLOCK:
-    case GNUNET_BLOCK_TYPE_IBLOCK:
-      /* only possible reply, stop requesting! */
+    case GNUNET_BLOCK_EVALUATION_OK_MORE:
+      break;
+    case GNUNET_BLOCK_EVALUATION_OK_LAST:
       while (NULL != pr->pending_head)
        destroy_pending_message_list_entry (pr->pending_head);
       if (pr->qe != NULL)
@@ -2577,7 +3083,7 @@ process_reply (void *cls,
          if (pr->client_request_list != NULL)
            GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client, 
                                        GNUNET_YES);
-         GNUNET_DATASTORE_cancel (pr->qe);
+         GNUNET_DATASTORE_cancel (pr->qe);
          pr->qe = NULL;
        }
       pr->do_remove = GNUNET_YES;
@@ -2591,67 +3097,61 @@ process_reply (void *cls,
                    GNUNET_CONTAINER_multihashmap_remove (query_request_map,
                                                          key,
                                                          pr));
+      GNUNET_LOAD_update (rt_entry_lifetime,
+                         GNUNET_TIME_absolute_get_duration (pr->start_time).value);
       break;
-    case GNUNET_BLOCK_TYPE_SBLOCK:
-      if (pr->namespace == NULL)
-       {
-         GNUNET_break (0);
-         return GNUNET_YES;
-       }
-      if (0 != memcmp (pr->namespace,
-                      &prq->namespace,
-                      sizeof (GNUNET_HashCode)))
-       {
-         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
-                     _("Reply mismatched in terms of namespace.  Discarded.\n"));
-         return GNUNET_YES; /* wrong namespace */      
-       }
-      /* then: fall-through! */
-    case GNUNET_BLOCK_TYPE_KBLOCK:
-    case GNUNET_BLOCK_TYPE_NBLOCK:
-      if (pr->bf != NULL) 
-       {
-         mingle_hash (&chash, pr->mingle, &mhash);
-         if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
-                                                              &mhash))
-           {
-             GNUNET_STATISTICS_update (stats,
-                                       gettext_noop ("# duplicate replies discarded (bloomfilter)"),
-                                       1,
-                                       GNUNET_NO);
-#if DEBUG_FS
-             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-                         "Duplicate response `%s', discarding.\n",
-                         GNUNET_h2s (&mhash));
-#endif
-             return GNUNET_YES; /* duplicate */
-           }
+    case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
+      GNUNET_STATISTICS_update (stats,
+                               gettext_noop ("# duplicate replies discarded (bloomfilter)"),
+                               1,
+                               GNUNET_NO);
 #if DEBUG_FS
-         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-                     "New response `%s', adding to filter.\n",
-                     GNUNET_h2s (&mhash));
+      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                 "Duplicate response `%s', discarding.\n",
+                 GNUNET_h2s (&mhash));
 #endif
-       }
-      if (pr->client_request_list != NULL)
-       {
-         if (pr->replies_seen_size == pr->replies_seen_off)
-           GNUNET_array_grow (pr->replies_seen,
-                              pr->replies_seen_size,
-                              pr->replies_seen_size * 2 + 4);  
-           pr->replies_seen[pr->replies_seen_off++] = chash;         
-       }
-      if ( (pr->bf == NULL) ||
-          (pr->client_request_list != NULL) )
-       refresh_bloomfilter (pr);
-      GNUNET_CONTAINER_bloomfilter_add (pr->bf,
-                                       &mhash);
-      break;
-    default:
+      return GNUNET_YES; /* duplicate */
+    case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
+      return GNUNET_YES; /* wrong namespace */ 
+    case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
+      GNUNET_break (0);
+      return GNUNET_YES;
+    case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
       GNUNET_break (0);
       return GNUNET_YES;
+    case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
+      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+                 _("Unsupported block type %u\n"),
+                 prq->type);
+      return GNUNET_NO;
+    }
+  if (pr->client_request_list != NULL)
+    {
+      if (pr->replies_seen_size == pr->replies_seen_off)
+       GNUNET_array_grow (pr->replies_seen,
+                          pr->replies_seen_size,
+                          pr->replies_seen_size * 2 + 4);      
+      GNUNET_CRYPTO_hash (prq->data,
+                         prq->size,
+                         &pr->replies_seen[pr->replies_seen_off++]);         
+      refresh_bloomfilter (pr);
+    }
+  if (NULL == prq->sender)
+    {
+#if DEBUG_FS
+      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                 "Found result for query `%s' in local datastore\n",
+                 GNUNET_h2s (key));
+#endif
+      GNUNET_STATISTICS_update (stats,
+                               gettext_noop ("# results found locally"),
+                               1,
+                               GNUNET_NO);      
     }
   prq->priority += pr->remaining_priority;
   pr->remaining_priority = 0;
+  pr->results_found++;
+  prq->request_found = GNUNET_YES;
   if (NULL != pr->client_request_list)
     {
       GNUNET_STATISTICS_update (stats,
@@ -2710,6 +3210,12 @@ process_reply (void *cls,
       reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
       reply->cont = &transmit_reply_continuation;
       reply->cont_cls = pr;
+#if SUPPORT_DELAYS
+      reply->delay_until 
+       = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
+                                                                          GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
+                                                                                                    TTL_DECREMENT)));
+#endif
       reply->msize = msize;
       reply->priority = UINT32_MAX; /* send replies first! */
       pm = (struct PutMessage*) &reply[1];
@@ -2724,6 +3230,44 @@ process_reply (void *cls,
 }
 
 
+/**
+ * Iterator called on each result obtained for a DHT
+ * operation that expects a reply
+ *
+ * @param cls closure
+ * @param exp when will this value expire
+ * @param key key of the result
+ * @param get_path NULL-terminated array of pointers
+ *                 to the peers on reverse GET path (or NULL if not recorded)
+ * @param put_path NULL-terminated array of pointers
+ *                 to the peers on the PUT path (or NULL if not recorded)
+ * @param type type of the result
+ * @param size number of bytes in data
+ * @param data pointer to the result data
+ */
+static void
+process_dht_reply (void *cls,
+                  struct GNUNET_TIME_Absolute exp,
+                  const GNUNET_HashCode * key,
+                  const struct GNUNET_PeerIdentity * const *get_path,
+                  const struct GNUNET_PeerIdentity * const *put_path,
+                  enum GNUNET_BLOCK_Type type,
+                  size_t size,
+                  const void *data)
+{
+  struct PendingRequest *pr = cls;
+  struct ProcessReplyClosure prq;
+
+  memset (&prq, 0, sizeof (prq));
+  prq.data = data;
+  prq.expiration = exp;
+  prq.size = size;  
+  prq.type = type;
+  process_reply (&prq, key, pr);
+}
+
+
+
 /**
  * Continuation called to notify client about result of the
  * operation.
@@ -2737,7 +3281,19 @@ put_migration_continuation (void *cls,
                            int success,
                            const char *msg)
 {
-  /* FIXME */
+  struct GNUNET_TIME_Absolute *start = cls;
+  struct GNUNET_TIME_Relative delay;
+  
+  delay = GNUNET_TIME_absolute_get_duration (*start);
+  GNUNET_free (start);
+  GNUNET_LOAD_update (datastore_put_load,
+                     delay.value);
+  if (GNUNET_OK == success)
+    return;
+  GNUNET_STATISTICS_update (stats,
+                           gettext_noop ("# datastore 'put' failures"),
+                           1,
+                           GNUNET_NO);
 }
 
 
@@ -2767,7 +3323,12 @@ handle_p2p_put (void *cls,
   struct GNUNET_TIME_Absolute expiration;
   GNUNET_HashCode query;
   struct ProcessReplyClosure prq;
-  const struct SBlock *sb;
+  struct GNUNET_TIME_Absolute *start;
+  struct GNUNET_TIME_Relative block_time;  
+  double putl;
+  struct ConnectedPeer *cp; 
+  struct PendingMessage *pm;
+  struct MigrationStopMessage *msm;
 
   msize = ntohs (message->size);
   if (msize < sizeof (struct PutMessage))
@@ -2780,25 +3341,18 @@ handle_p2p_put (void *cls,
   type = ntohl (put->type);
   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
 
+  if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
+    return GNUNET_SYSERR;
   if (GNUNET_OK !=
-      GNUNET_BLOCK_check_block (type,
-                               &put[1],
-                               dsize,
-                               &query))
+      GNUNET_BLOCK_get_key (block_ctx,
+                           type,
+                           &put[1],
+                           dsize,
+                           &query))
     {
       GNUNET_break_op (0);
       return GNUNET_SYSERR;
     }
-  if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
-    return GNUNET_SYSERR;
-  if (GNUNET_BLOCK_TYPE_SBLOCK == type)
-    { 
-      sb = (const struct SBlock*) &put[1];
-      GNUNET_CRYPTO_hash (&sb->subspace,
-                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
-                         &prq.namespace);
-    }
-
 #if DEBUG_FS
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Received result for query `%s' from peer `%4s'\n",
@@ -2821,6 +3375,7 @@ handle_p2p_put (void *cls,
   prq.expiration = expiration;
   prq.priority = 0;
   prq.finished = GNUNET_NO;
+  prq.request_found = GNUNET_NO;
   GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
                                              &query,
                                              &process_reply,
@@ -2830,14 +3385,17 @@ handle_p2p_put (void *cls,
       prq.sender->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
       prq.sender->trust += prq.priority;
     }
-  if (GNUNET_YES == active_migration)
-    {
+  if ( (GNUNET_YES == active_migration) &&
+       (GNUNET_NO == test_put_load_too_high (prq.priority)) )
+    {      
 #if DEBUG_FS
       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Replicating result for query `%s' with priority %u\n",
                  GNUNET_h2s (&query),
                  prq.priority);
 #endif
+      start = GNUNET_malloc (sizeof (struct GNUNET_TIME_Absolute));
+      *start = GNUNET_TIME_absolute_get ();
       GNUNET_DATASTORE_put (dsh,
                            0, &query, dsize, &put[1],
                            type, prq.priority, 1 /* anonymity */, 
@@ -2845,12 +3403,77 @@ handle_p2p_put (void *cls,
                            1 + prq.priority, MAX_DATASTORE_QUEUE,
                            GNUNET_CONSTANTS_SERVICE_TIMEOUT,
                            &put_migration_continuation, 
-                           NULL);
+                           start);
+    }
+  putl = GNUNET_LOAD_get_load (datastore_put_load);
+  if ( (GNUNET_NO == prq.request_found) &&
+       ( (GNUNET_YES != active_migration) ||
+                (putl > 2.0) ) )
+    {
+      cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
+                                             &other->hashPubKey);
+      if (GNUNET_TIME_absolute_get_duration (cp->last_migration_block).value < 5000)
+       return GNUNET_OK; /* already blocked */
+      /* We're too busy; send MigrationStop message! */
+      if (GNUNET_YES != active_migration) 
+       putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
+      block_time = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
+                                                 5000 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
+                                                                                  (unsigned int) (60000 * putl * putl)));
+      
+      cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
+      pm = GNUNET_malloc (sizeof (struct PendingMessage) + 
+                         sizeof (struct MigrationStopMessage));
+      pm->msize = sizeof (struct MigrationStopMessage);
+      pm->priority = UINT32_MAX;
+      msm = (struct MigrationStopMessage*) &pm[1];
+      msm->header.size = htons (sizeof (struct MigrationStopMessage));
+      msm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
+      msm->duration = GNUNET_TIME_relative_hton (block_time);
+      add_to_pending_messages_for_peer (cp,
+                                       pm,
+                                       NULL);
     }
   return GNUNET_OK;
 }
 
 
+/**
+ * Handle P2P "MIGRATION_STOP" message.
+ *
+ * @param cls closure, always NULL
+ * @param other the other peer involved (sender or receiver, NULL
+ *        for loopback messages where we are both sender and receiver)
+ * @param message the actual message
+ * @param latency reported latency of the connection with 'other'
+ * @param distance reported distance (DV) to 'other' 
+ * @return GNUNET_OK to keep the connection open,
+ *         GNUNET_SYSERR to close it (signal serious error)
+ */
+static int
+handle_p2p_migration_stop (void *cls,
+                          const struct GNUNET_PeerIdentity *other,
+                          const struct GNUNET_MessageHeader *message,
+                          struct GNUNET_TIME_Relative latency,
+                          uint32_t distance)
+{
+  struct ConnectedPeer *cp; 
+  const struct MigrationStopMessage *msm;
+
+  msm = (const struct MigrationStopMessage*) message;
+  cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
+                                         &other->hashPubKey);
+  if (cp == NULL)
+    {
+      GNUNET_break (0);
+      return GNUNET_OK;
+    }
+  cp->migration_blocked = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (msm->duration));
+  return GNUNET_OK;
+}
+
+
+
 /* **************************** P2P GET Handling ************************ */
 
 
@@ -2924,7 +3547,7 @@ check_duplicate_request_client (void *cls,
 static void
 process_local_reply (void *cls,
                     const GNUNET_HashCode * key,
-                    uint32_t size,
+                    size_t size,
                     const void *data,
                     enum GNUNET_BLOCK_Type type,
                     uint32_t priority,
@@ -2936,10 +3559,8 @@ process_local_reply (void *cls,
   struct PendingRequest *pr = cls;
   struct ProcessReplyClosure prq;
   struct CheckDuplicateRequestClosure cdrc;
-  const struct SBlock *sb;
-  GNUNET_HashCode dhash;
-  GNUNET_HashCode mhash;
   GNUNET_HashCode query;
+  unsigned int old_rf;
   
   if (NULL == key)
     {
@@ -2986,7 +3607,7 @@ process_local_reply (void *cls,
              GNUNET_h2s (key),
              type);
 #endif
-  if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
+  if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
     {
 #if DEBUG_FS
       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
@@ -3002,56 +3623,22 @@ process_local_reply (void *cls,
                                            &process_local_reply,
                                            pr))
       if (pr->qe != NULL)
-       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
-      return;
-    }
-  /* check for duplicates */
-  GNUNET_CRYPTO_hash (data, size, &dhash);
-  mingle_hash (&dhash, 
-              pr->mingle,
-              &mhash);
-  if ( (pr->bf != NULL) &&
-       (GNUNET_YES ==
-       GNUNET_CONTAINER_bloomfilter_test (pr->bf,
-                                          &mhash)) )
-    {      
-#if DEBUG_FS
-      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-                 "Result from datastore filtered by bloomfilter (duplicate).\n");
-#endif
-      GNUNET_STATISTICS_update (stats,
-                               gettext_noop ("# results filtered by query bloomfilter"),
-                               1,
-                               GNUNET_NO);
-      if (pr->qe != NULL)
-       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
+       {
+         GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
+       }
       return;
     }
-#if DEBUG_FS
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-             "Found result for query `%s' in local datastore\n",
-             GNUNET_h2s (key));
-#endif
-  GNUNET_STATISTICS_update (stats,
-                           gettext_noop ("# results found locally"),
-                           1,
-                           GNUNET_NO);
-  pr->results_found++;
+  old_rf = pr->results_found;
   memset (&prq, 0, sizeof (prq));
   prq.data = data;
   prq.expiration = expiration;
   prq.size = size;  
-  if (GNUNET_BLOCK_TYPE_SBLOCK == type)
-    { 
-      sb = (const struct SBlock*) data;
-      GNUNET_CRYPTO_hash (&sb->subspace,
-                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
-                         &prq.namespace);
-    }
-  if (GNUNET_OK != GNUNET_BLOCK_check_block (type,
-                                            data,
-                                            size,
-                                            &query))
+  if (GNUNET_OK != 
+      GNUNET_BLOCK_get_key (block_ctx,
+                           type,
+                           data,
+                           size,
+                           &query))
     {
       GNUNET_break (0);
       GNUNET_DATASTORE_remove (dsh,
@@ -3066,19 +3653,22 @@ process_local_reply (void *cls,
   prq.type = type;
   prq.priority = priority;  
   prq.finished = GNUNET_NO;
+  prq.request_found = GNUNET_NO;
+  if ( (old_rf == 0) &&
+       (pr->results_found == 0) )
+    update_datastore_delays (pr->start_time);
   process_reply (&prq, key, pr);
   if (prq.finished == GNUNET_YES)
     return;
   if (pr->qe == NULL)
     return; /* done here */
-  if ( (type == GNUNET_BLOCK_TYPE_DBLOCK) ||
-       (type == GNUNET_BLOCK_TYPE_IBLOCK) ) 
+  if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
     {
       GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
       return;
     }
   if ( (pr->client_request_list == NULL) &&
-       ( (GNUNET_YES == test_load_too_high()) ||
+       ( (GNUNET_YES == test_get_load_too_high (0)) ||
         (pr->results_found > 5 + 2 * pr->priority) ) )
     {
 #if DEBUG_FS > 2
@@ -3104,15 +3694,18 @@ process_local_reply (void *cls,
  * @param cp the peer making the request
  * @return effective priority
  */
-static uint32_t
+static int32_t
 bound_priority (uint32_t prio_in,
                struct ConnectedPeer *cp)
 {
 #define N ((double)128.0)
   uint32_t ret;
   double rret;
-  /* FIXME: check if load is low and we
-     hence should not charge... */
+  int ld;
+
+  ld = test_get_load_too_high (0);
+  if (ld == GNUNET_SYSERR)
+    return 0; /* excess resources */
   ret = change_host_trust (cp, prio_in);
   if (ret > 0)
     {
@@ -3123,6 +3716,18 @@ bound_priority (uint32_t prio_in,
       current_priorities 
        = (current_priorities * (N-1) + rret)/N;
     }
+  if ( (ld == GNUNET_YES) && (ret > 0) )
+    {
+      /* try with charging */
+      ld = test_get_load_too_high (ret);
+    }
+  if (ld == GNUNET_YES)
+    {
+      /* undo charge */
+      if (ret != 0)
+       change_host_trust (cp, -ret);
+      return -1; /* not enough resources */
+    }
 #undef N
   return ret;
 }
@@ -3189,6 +3794,7 @@ handle_p2p_get (void *cls,
   uint32_t bm;
   size_t bfsize;
   uint32_t ttl_decrement;
+  int32_t priority;
   enum GNUNET_BLOCK_Type type;
   int have_ns;
 
@@ -3200,18 +3806,6 @@ handle_p2p_get (void *cls,
     }
   gm = (const struct GetMessage*) message;
   type = ntohl (gm->type);
-  switch (type)
-    {
-    case GNUNET_BLOCK_TYPE_ANY:
-    case GNUNET_BLOCK_TYPE_DBLOCK:
-    case GNUNET_BLOCK_TYPE_IBLOCK:
-    case GNUNET_BLOCK_TYPE_KBLOCK:
-    case GNUNET_BLOCK_TYPE_SBLOCK:
-      break;
-    default:
-      GNUNET_break_op (0);
-      return GNUNET_SYSERR;
-    }
   bm = ntohl (gm->hash_bitmap);
   bits = 0;
   while (bm > 0)
@@ -3228,12 +3822,6 @@ handle_p2p_get (void *cls,
   opt = (const GNUNET_HashCode*) &gm[1];
   bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
   bm = ntohl (gm->hash_bitmap);
-  if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
-       (type != GNUNET_BLOCK_TYPE_SBLOCK) )
-    {
-      GNUNET_break_op (0);
-      return GNUNET_SYSERR;      
-    }
   bits = 0;
   cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
                                           &other->hashPubKey);
@@ -3274,7 +3862,8 @@ handle_p2p_get (void *cls,
   /* note that we can really only check load here since otherwise
      peers could find out that we are overloaded by not being
      disconnected after sending us a malformed query... */
-  if (GNUNET_YES == test_load_too_high ())
+  priority = bound_priority (ntohl (gm->priority), cps);
+  if (priority < 0)
     {
 #if DEBUG_FS
       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
@@ -3287,7 +3876,6 @@ handle_p2p_get (void *cls,
                                GNUNET_NO);
       return GNUNET_OK;
     }
-
 #if DEBUG_FS 
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
@@ -3304,13 +3892,21 @@ handle_p2p_get (void *cls,
       pr->namespace = (GNUNET_HashCode*) &pr[1];
       memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
     }
+  if ( (GNUNET_LOAD_get_load (cp->transmission_delay) > 3) ||
+       (GNUNET_LOAD_get_average (cp->transmission_delay) > 
+       GNUNET_CONSTANTS_MAX_CORK_DELAY.value * 2 + GNUNET_LOAD_get_average (rt_entry_lifetime)) )
+    {
+      /* don't have BW to send to peer, or would likely take longer than we have for it,
+        so at best indirect the query */
+      priority = 0;
+      pr->forward_only = GNUNET_YES;
+    }
   pr->type = type;
   pr->mingle = ntohl (gm->filter_mutator);
   if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
     pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
-
   pr->anonymity_level = 1;
-  pr->priority = bound_priority (ntohl (gm->priority), cps);
+  pr->priority = (uint32_t) priority;
   pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
   pr->query = gm->query;
   /* decrement ttl (always) */
@@ -3413,26 +4009,33 @@ handle_p2p_get (void *cls,
   /* calculate change in traffic preference */
   cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
   /* process locally */
-  if (type == GNUNET_BLOCK_TYPE_DBLOCK)
+  if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
     type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
   timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
                                           (pr->priority + 1)); 
-  pr->qe = GNUNET_DATASTORE_get (dsh,
-                                &gm->query,
-                                type,                         
-                                pr->priority + 1,
-                                MAX_DATASTORE_QUEUE,                            
-                                timeout,
-                                &process_local_reply,
-                                pr);
+  if (GNUNET_YES != pr->forward_only)
+    pr->qe = GNUNET_DATASTORE_get (dsh,
+                                  &gm->query,
+                                  type,                               
+                                  pr->priority + 1,
+                                  MAX_DATASTORE_QUEUE,                          
+                                  timeout,
+                                  &process_local_reply,
+                                  pr);
+  else
+    GNUNET_STATISTICS_update (stats,
+                             gettext_noop ("# requests forwarded due to high load"),
+                             1,
+                             GNUNET_NO);
 
-  /* Are multiple results possible?  If so, start processing remotely now! */
+  /* Are multiple results possible (and did we look locally)?  If so, start processing remotely now! */
   switch (pr->type)
     {
-    case GNUNET_BLOCK_TYPE_DBLOCK:
-    case GNUNET_BLOCK_TYPE_IBLOCK:
+    case GNUNET_BLOCK_TYPE_FS_DBLOCK:
+    case GNUNET_BLOCK_TYPE_FS_IBLOCK:
       /* only one result, wait for datastore */
-      break;
+      if (GNUNET_YES != pr->forward_only)
+       break;
     default:
       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
        pr->task = GNUNET_SCHEDULER_add_now (sched,
@@ -3444,6 +4047,7 @@ handle_p2p_get (void *cls,
   if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
     {
       pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
+      GNUNET_assert (pr != NULL);
       destroy_pending_request (pr);
     }
   return GNUNET_OK;
@@ -3496,22 +4100,6 @@ handle_start_search (void *cls,
              GNUNET_h2s (&sm->query),
              (unsigned int) type);
 #endif
-  switch (type)
-    {
-    case GNUNET_BLOCK_TYPE_ANY:
-    case GNUNET_BLOCK_TYPE_DBLOCK:
-    case GNUNET_BLOCK_TYPE_IBLOCK:
-    case GNUNET_BLOCK_TYPE_KBLOCK:
-    case GNUNET_BLOCK_TYPE_SBLOCK:
-    case GNUNET_BLOCK_TYPE_NBLOCK:
-      break;
-    default:
-      GNUNET_break (0);
-      GNUNET_SERVER_receive_done (client,
-                                 GNUNET_SYSERR);
-      return;
-    }  
-
   cl = client_list;
   while ( (cl != NULL) &&
          (cl->client != client) )
@@ -3525,8 +4113,8 @@ handle_start_search (void *cls,
       client_list = cl;
     }
   /* detect duplicate KBLOCK requests */
-  if ( (type == GNUNET_BLOCK_TYPE_KBLOCK) ||
-       (type == GNUNET_BLOCK_TYPE_NBLOCK) ||
+  if ( (type == GNUNET_BLOCK_TYPE_FS_KBLOCK) ||
+       (type == GNUNET_BLOCK_TYPE_FS_NBLOCK) ||
        (type == GNUNET_BLOCK_TYPE_ANY) )
     {
       crl = cl->rl_head;
@@ -3568,7 +4156,7 @@ handle_start_search (void *cls,
                            1,
                            GNUNET_NO);
   pr = GNUNET_malloc (sizeof (struct PendingRequest) + 
-                     ((type == GNUNET_BLOCK_TYPE_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
+                     ((type == GNUNET_BLOCK_TYPE_FS_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
   crl = GNUNET_malloc (sizeof (struct ClientRequestList));
   memset (crl, 0, sizeof (struct ClientRequestList));
   crl->client_list = cl;
@@ -3586,6 +4174,7 @@ handle_start_search (void *cls,
          sc * sizeof (GNUNET_HashCode));
   pr->replies_seen_off = sc;
   pr->anonymity_level = ntohl (sm->anonymity_level); 
+  pr->start_time = GNUNET_TIME_absolute_get ();
   refresh_bloomfilter (pr);
   pr->query = sm->query;
   if (0 == (1 & ntohl (sm->options)))
@@ -3594,14 +4183,14 @@ handle_start_search (void *cls,
     pr->local_only = GNUNET_YES;
   switch (type)
     {
-    case GNUNET_BLOCK_TYPE_DBLOCK:
-    case GNUNET_BLOCK_TYPE_IBLOCK:
+    case GNUNET_BLOCK_TYPE_FS_DBLOCK:
+    case GNUNET_BLOCK_TYPE_FS_IBLOCK:
       if (0 != memcmp (&sm->target,
                       &all_zeros,
                       sizeof (GNUNET_HashCode)))
        pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
       break;
-    case GNUNET_BLOCK_TYPE_SBLOCK:
+    case GNUNET_BLOCK_TYPE_FS_SBLOCK:
       pr->namespace = (GNUNET_HashCode*) &pr[1];
       memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
       break;
@@ -3613,7 +4202,7 @@ handle_start_search (void *cls,
                                                   &sm->query,
                                                   pr,
                                                   GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
-  if (type == GNUNET_BLOCK_TYPE_DBLOCK)
+  if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
     type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
   pr->qe = GNUNET_DATASTORE_get (dsh,
                                 &sm->query,
@@ -3645,6 +4234,9 @@ main_init (struct GNUNET_SCHEDULER_Handle *s,
        GNUNET_MESSAGE_TYPE_FS_GET, 0 },
       { &handle_p2p_put, 
        GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
+      { &handle_p2p_migration_stop, 
+       GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP,
+       sizeof (struct MigrationStopMessage) },
       { NULL, 0, 0 }
     };
   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
@@ -3658,14 +4250,35 @@ main_init (struct GNUNET_SCHEDULER_Handle *s,
      0 },
     {NULL, NULL, 0, 0}
   };
+  unsigned long long enc = 128;
 
   sched = s;
   cfg = c;
   stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
-  min_migration_delay = GNUNET_TIME_UNIT_SECONDS; // FIXME: get from config
-  connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
-  query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
-  peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
+  min_migration_delay = GNUNET_TIME_UNIT_SECONDS;
+  if ( (GNUNET_OK !=
+       GNUNET_CONFIGURATION_get_value_number (cfg,
+                                              "fs",
+                                              "MAX_PENDING_REQUESTS",
+                                              &max_pending_requests)) ||
+       (GNUNET_OK !=
+       GNUNET_CONFIGURATION_get_value_number (cfg,
+                                              "fs",
+                                              "EXPECTED_NEIGHBOUR_COUNT",
+                                              &enc)) ||
+       (GNUNET_OK != 
+       GNUNET_CONFIGURATION_get_value_time (cfg,
+                                            "fs",
+                                            "MIN_MIGRATION_DELAY",
+                                            &min_migration_delay)) )
+    {
+      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
+                 _("Configuration fails to specify certain parameters, assuming default values."));
+    }
+  connected_peers = GNUNET_CONTAINER_multihashmap_create (enc); 
+  query_request_map = GNUNET_CONTAINER_multihashmap_create (max_pending_requests);
+  rt_entry_lifetime = GNUNET_LOAD_value_init ();
+  peer_request_map = GNUNET_CONTAINER_multihashmap_create (enc);
   requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); 
   core = GNUNET_CORE_connect (sched,
                              cfg,
@@ -3687,6 +4300,8 @@ main_init (struct GNUNET_SCHEDULER_Handle *s,
       connected_peers = NULL;
       GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
       query_request_map = NULL;
+      GNUNET_LOAD_value_free (rt_entry_lifetime);
+      rt_entry_lifetime = NULL;
       GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
       requests_by_expiration_heap = NULL;
       GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
@@ -3705,6 +4320,7 @@ main_init (struct GNUNET_SCHEDULER_Handle *s,
                  _("Content migration is enabled, will start to gather data\n"));
       consider_migration_gathering ();
     }
+  consider_dht_put_gathering (NULL);
   GNUNET_SERVER_disconnect_notify (server, 
                                   &handle_client_disconnect,
                                   NULL);
@@ -3752,12 +4368,34 @@ run (void *cls,
       GNUNET_SCHEDULER_shutdown (sched);
       return;
     }
+  datastore_get_load = GNUNET_LOAD_value_init ();
+  datastore_put_load = GNUNET_LOAD_value_init ();
+  block_cfg = GNUNET_CONFIGURATION_create ();
+  GNUNET_CONFIGURATION_set_value_string (block_cfg,
+                                        "block",
+                                        "PLUGINS",
+                                        "fs");
+  block_ctx = GNUNET_BLOCK_context_create (block_cfg);
+  GNUNET_assert (NULL != block_ctx);
+  dht_handle = GNUNET_DHT_connect (sched,
+                                  cfg,
+                                  FS_DHT_HT_SIZE);
   if ( (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg, dsh)) ||
        (GNUNET_OK != main_init (sched, server, cfg)) )
     {    
       GNUNET_SCHEDULER_shutdown (sched);
       GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
       dsh = NULL;
+      GNUNET_DHT_disconnect (dht_handle);
+      dht_handle = NULL;
+      GNUNET_BLOCK_context_destroy (block_ctx);
+      block_ctx = NULL;
+      GNUNET_CONFIGURATION_destroy (block_cfg);
+      block_cfg = NULL;
+      GNUNET_LOAD_value_free (datastore_get_load);
+      datastore_get_load = NULL;
+      GNUNET_LOAD_value_free (datastore_put_load);
+      datastore_put_load = NULL;
       return;   
     }
 }