nbd_close (struct nbd_handle *h)
{
  nbd_internal_set_error_context ("nbd_close");

  if (h == NULL)
    return;

  debug (h, "closing handle");

  /* Free user callbacks first. */
  nbd_unlocked_clear_debug_callback (h);

  free (h->bs_entries);
  nbd_internal_reset_size_and_flags (h);
  nbd_internal_free_option (h);
  free_cmd_list (h->cmds_to_issue);
  free_cmd_list (h->cmds_in_flight);
  free_cmd_list (h->cmds_done);
  string_vector_iter (&h->argv, (void *) free);
  free (h->argv.ptr);
  if (h->sa_sockpath) {
    if (h->pid > 0)
      kill (h->pid, SIGTERM);
    unlink (h->sa_sockpath);
    free (h->sa_sockpath);
  }
  if (h->sa_tmpdir) {
    rmdir (h->sa_tmpdir);
    free (h->sa_tmpdir);
  }
  free (h->hostname);
  free (h->port);
  if (h->result)
    freeaddrinfo (h->result);
  if (h->sock)
    h->sock->ops->close (h->sock);
  if (h->pid > 0)
    waitpid (h->pid, NULL, 0);

  free (h->export_name);
  free (h->tls_certificates);
  free (h->tls_username);
  free (h->tls_psk_file);
  string_vector_iter (&h->request_meta_contexts, (void *) free);
  free (h->request_meta_contexts.ptr);
  free (h->hname);
  pthread_mutex_destroy (&h->lock);
  free (h);
}
nbd_close (struct nbd_handle *h)
{
  nbd_internal_set_error_context ("nbd_close");

  if (h == NULL)
    return;

  debug (h, "closing handle");

   
  nbd_unlocked_clear_debug_callback (h);

  free (h->bs_entries);
  nbd_internal_reset_size_and_flags (h);
  nbd_internal_free_option (h);
  free_cmd_list (h->cmds_to_issue);
  free_cmd_list (h->cmds_in_flight);
  free_cmd_list (h->cmds_done);
  string_vector_iter (&h->argv, (void *) free);
  free (h->argv.ptr);
  if (h->sa_sockpath) {
    if (h->pid > 0)
      kill (h->pid, SIGTERM);
    unlink (h->sa_sockpath);
    free (h->sa_sockpath);
  }
  if (h->sa_tmpdir) {
    rmdir (h->sa_tmpdir);
    free (h->sa_tmpdir);
  }
  free (h->hostname);
  free (h->port);
  if (h->result)
    freeaddrinfo (h->result);
  if (h->sock)
    h->sock->ops->close (h->sock);
  if (h->pid > 0)
    waitpid (h->pid, NULL, 0);

  free (h->export_name);
  free (h->tls_certificates);
  free (h->tls_username);
  free (h->tls_psk_file);
  string_vector_iter (&h->request_meta_contexts, (void *) free);
  free (h->request_meta_contexts.ptr);
  free (h->hname);
  pthread_mutex_destroy (&h->lock);
  free (h);
}