+ /*
+ * We should never be called with state->state != NULL.
+ * Only pthreadpool_tevent_job_orphan() will call TALLOC_FREE(job)
+ * after detaching from the request state and pool list.
+ */
+ if (job->state != NULL) {
+ abort();
+ }
+
+ /*
+ * If the job is not finished (job->im still there)
+ * and it's still attached to the pool,
+ * we try to cancel it (before it was starts)
+ */
+ if (job->im != NULL && job->pool != NULL) {
+ size_t num;
+
+ num = pthreadpool_cancel_job(job->pool->pool, 0,
+ pthreadpool_tevent_job_fn,
+ job);
+ if (num != 0) {
+ /*
+ * It was not too late to cancel the request.
+ *
+ * We can remove job->im, as it will never be used.
+ */
+ TALLOC_FREE(job->im);
+ }
+ }
+
+ /*
+ * pthreadpool_tevent_job_orphan() already removed
+ * it from pool->jobs. And we don't need try
+ * pthreadpool_cancel_job() again.
+ */
+ job->pool = NULL;
+
+ if (job->im != NULL) {
+ /*
+ * state->im still there means, we need to wait for the
+ * immediate event to be triggered or just leak the memory.
+ */
+ return -1;
+ }
+
+ return 0;
+}
+
+static void pthreadpool_tevent_job_orphan(struct pthreadpool_tevent_job *job)
+{
+ /*
+ * We're the only function that sets
+ * job->state = NULL;
+ */
+ if (job->state == NULL) {
+ abort();