{
        struct dm_snapshot *s = (struct dm_snapshot *) ti->private;
 
+       /* Prevent further origin writes from using this snapshot. */
+       /* After this returns there can be no new kcopyd jobs. */
        unregister_snapshot(s);
 
+       kcopyd_client_destroy(s->kcopyd_client);
+
        exit_exception_table(&s->pending, pending_cache);
        exit_exception_table(&s->complete, exception_cache);
 
 
        dm_put_device(ti, s->origin);
        dm_put_device(ti, s->cow);
-       kcopyd_client_destroy(s->kcopyd_client);
+
        kfree(s);
 }
 
 
        struct page_list *pages;
        unsigned int nr_pages;
        unsigned int nr_free_pages;
+
+       wait_queue_head_t destroyq;
+       atomic_t nr_jobs;
 };
 
 static struct page_list *alloc_pl(void)
        int read_err = job->read_err;
        unsigned int write_err = job->write_err;
        kcopyd_notify_fn fn = job->fn;
+       struct kcopyd_client *kc = job->kc;
 
-       kcopyd_put_pages(job->kc, job->pages);
+       kcopyd_put_pages(kc, job->pages);
        mempool_free(job, _job_pool);
        fn(read_err, write_err, context);
+
+       if (atomic_dec_and_test(&kc->nr_jobs))
+               wake_up(&kc->destroyq);
+
        return 0;
 }
 
  */
 static void dispatch_job(struct kcopyd_job *job)
 {
+       atomic_inc(&job->kc->nr_jobs);
        push(&_pages_jobs, job);
        wake();
 }
                return r;
        }
 
+       init_waitqueue_head(&kc->destroyq);
+       atomic_set(&kc->nr_jobs, 0);
+
        client_add(kc);
        *result = kc;
        return 0;
 
 void kcopyd_client_destroy(struct kcopyd_client *kc)
 {
+       /* Wait for completion of all jobs submitted by this client. */
+       wait_event(kc->destroyq, !atomic_read(&kc->nr_jobs));
+
        dm_io_put(kc->nr_pages);
        client_free_pages(kc);
        client_del(kc);