5d6a8002052897df3695067f55226f68159b1f0b
[mirror/scst/.git] / scst / src / scst_lib.c
1 /*
2  *  scst_lib.c
3  *
4  *  Copyright (C) 2004 - 2008 Vladislav Bolkhovitin <vst@vlnb.net>
5  *  Copyright (C) 2004 - 2005 Leonid Stoljar
6  *  Copyright (C) 2007 - 2008 CMS Distribution Limited
7  *
8  *  This program is free software; you can redistribute it and/or
9  *  modify it under the terms of the GNU General Public License
10  *  as published by the Free Software Foundation, version 2
11  *  of the License.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  *  GNU General Public License for more details.
17  */
18
19 #include <linux/init.h>
20 #include <linux/kernel.h>
21 #include <linux/errno.h>
22 #include <linux/list.h>
23 #include <linux/spinlock.h>
24 #include <linux/slab.h>
25 #include <linux/sched.h>
26 #include <linux/kthread.h>
27 #include <linux/cdrom.h>
28 #include <linux/unistd.h>
29 #include <linux/string.h>
30
31 #include "scst.h"
32 #include "scst_priv.h"
33 #include "scst_mem.h"
34
35 #include "scst_cdbprobe.h"
36
37 static void scst_free_tgt_dev(struct scst_tgt_dev *tgt_dev);
38 static void scst_check_internal_sense(struct scst_device *dev, int result,
39         uint8_t *sense, int sense_len);
40 static void scst_alloc_set_UA(struct scst_tgt_dev *tgt_dev,
41         const uint8_t *sense, int sense_len, int head);
42 static void scst_free_all_UA(struct scst_tgt_dev *tgt_dev);
43 static void scst_release_space(struct scst_cmd *cmd);
44 static void scst_sess_free_tgt_devs(struct scst_session *sess);
45 static void scst_unblock_cmds(struct scst_device *dev);
46
47 #ifdef CONFIG_SCST_DEBUG_TM
48 static void tm_dbg_init_tgt_dev(struct scst_tgt_dev *tgt_dev,
49         struct scst_acg_dev *acg_dev);
50 static void tm_dbg_deinit_tgt_dev(struct scst_tgt_dev *tgt_dev);
51 #else
52 static inline void tm_dbg_init_tgt_dev(struct scst_tgt_dev *tgt_dev,
53         struct scst_acg_dev *acg_dev) {}
54 static inline void tm_dbg_deinit_tgt_dev(struct scst_tgt_dev *tgt_dev) {}
55 #endif /* CONFIG_SCST_DEBUG_TM */
56
57 int scst_alloc_sense(struct scst_cmd *cmd, int atomic)
58 {
59         int res = 0;
60         gfp_t gfp_mask = atomic ? GFP_ATOMIC : (GFP_KERNEL|__GFP_NOFAIL);
61
62         TRACE_ENTRY();
63
64         sBUG_ON(cmd->sense != NULL);
65
66         cmd->sense = mempool_alloc(scst_sense_mempool, gfp_mask);
67         if (cmd->sense == NULL) {
68                 PRINT_CRIT_ERROR("Sense memory allocation failed (op %x). "
69                         "The sense data will be lost!!", cmd->cdb[0]);
70                 res = -ENOMEM;
71                 goto out;
72         }
73
74         memset(cmd->sense, 0, SCST_SENSE_BUFFERSIZE);
75
76 out:
77         TRACE_EXIT_RES(res);
78         return res;
79 }
80 EXPORT_SYMBOL(scst_alloc_sense);
81
82 int scst_alloc_set_sense(struct scst_cmd *cmd, int atomic,
83         const uint8_t *sense, unsigned int len)
84 {
85         int res;
86
87         TRACE_ENTRY();
88
89         res = scst_alloc_sense(cmd, atomic);
90         if (res != 0) {
91                 PRINT_BUFFER("Lost sense", sense, len);
92                 goto out;
93         }
94
95         memcpy(cmd->sense, sense, min((int)len, (int)SCST_SENSE_BUFFERSIZE));
96         TRACE_BUFFER("Sense set", cmd->sense, SCST_SENSE_BUFFERSIZE);
97
98 out:
99         TRACE_EXIT_RES(res);
100         return res;
101 }
102 EXPORT_SYMBOL(scst_alloc_set_sense);
103
104 void scst_set_cmd_error_status(struct scst_cmd *cmd, int status)
105 {
106         TRACE_ENTRY();
107
108         cmd->status = status;
109         cmd->host_status = DID_OK;
110
111         cmd->dbl_ua_orig_resp_data_len = cmd->resp_data_len;
112         cmd->dbl_ua_orig_data_direction = cmd->data_direction;
113
114         cmd->data_direction = SCST_DATA_NONE;
115         cmd->resp_data_len = 0;
116         cmd->is_send_status = 1;
117
118         cmd->completed = 1;
119
120         TRACE_EXIT();
121         return;
122 }
123 EXPORT_SYMBOL(scst_set_cmd_error_status);
124
125 void scst_set_cmd_error(struct scst_cmd *cmd, int key, int asc, int ascq)
126 {
127         int rc;
128
129         TRACE_ENTRY();
130
131         scst_set_cmd_error_status(cmd, SAM_STAT_CHECK_CONDITION);
132
133         rc = scst_alloc_sense(cmd, 1);
134         if (rc != 0) {
135                 PRINT_ERROR("Lost sense data (key %x, asc %x, ascq %x)",
136                         key, asc, ascq);
137                 goto out;
138         }
139
140         scst_set_sense(cmd->sense, SCST_SENSE_BUFFERSIZE, key, asc, ascq);
141         TRACE_BUFFER("Sense set", cmd->sense, SCST_SENSE_BUFFERSIZE);
142
143 out:
144         TRACE_EXIT();
145         return;
146 }
147 EXPORT_SYMBOL(scst_set_cmd_error);
148
149 void scst_set_sense(uint8_t *buffer, int len, int key,
150         int asc, int ascq)
151 {
152         memset(buffer, 0, len);
153         buffer[0] = 0x70;       /* Error Code                   */
154         buffer[2] = key;        /* Sense Key                    */
155         buffer[7] = 0x0a;       /* Additional Sense Length      */
156         buffer[12] = asc;       /* ASC                          */
157         buffer[13] = ascq;      /* ASCQ                         */
158         TRACE_BUFFER("Sense set", buffer, len);
159         return;
160 }
161 EXPORT_SYMBOL(scst_set_sense);
162
163 static void scst_set_cmd_error_sense(struct scst_cmd *cmd, uint8_t *sense,
164         unsigned int len)
165 {
166         TRACE_ENTRY();
167
168         scst_set_cmd_error_status(cmd, SAM_STAT_CHECK_CONDITION);
169         scst_alloc_set_sense(cmd, 1, sense, len);
170
171         TRACE_EXIT();
172         return;
173 }
174
175 void scst_set_busy(struct scst_cmd *cmd)
176 {
177         int c = atomic_read(&cmd->sess->sess_cmd_count);
178
179         TRACE_ENTRY();
180
181         if ((c <= 1) || (cmd->sess->init_phase != SCST_SESS_IPH_READY)) {
182                 scst_set_cmd_error_status(cmd, SAM_STAT_BUSY);
183                 TRACE(TRACE_MGMT_MINOR, "Sending BUSY status to initiator %s "
184                         "(cmds count %d, queue_type %x, sess->init_phase %d)",
185                         cmd->sess->initiator_name, c,
186                         cmd->queue_type, cmd->sess->init_phase);
187         } else {
188                 scst_set_cmd_error_status(cmd, SAM_STAT_TASK_SET_FULL);
189                 TRACE(TRACE_MGMT_MINOR, "Sending QUEUE_FULL status to "
190                         "initiator %s (cmds count %d, queue_type %x, "
191                         "sess->init_phase %d)", cmd->sess->initiator_name, c,
192                         cmd->queue_type, cmd->sess->init_phase);
193         }
194
195         TRACE_EXIT();
196         return;
197 }
198 EXPORT_SYMBOL(scst_set_busy);
199
200 int scst_get_cmd_abnormal_done_state(const struct scst_cmd *cmd)
201 {
202         int res;
203
204         TRACE_ENTRY();
205
206         switch (cmd->state) {
207         case SCST_CMD_STATE_INIT_WAIT:
208         case SCST_CMD_STATE_INIT:
209         case SCST_CMD_STATE_PRE_PARSE:
210         case SCST_CMD_STATE_DEV_PARSE:
211                 res = SCST_CMD_STATE_PRE_XMIT_RESP;
212                 break;
213
214         default:
215                 res = SCST_CMD_STATE_PRE_DEV_DONE;
216                 break;
217         }
218
219         TRACE_EXIT_RES(res);
220         return res;
221 }
222 EXPORT_SYMBOL(scst_get_cmd_abnormal_done_state);
223
224 void scst_set_cmd_abnormal_done_state(struct scst_cmd *cmd)
225 {
226         TRACE_ENTRY();
227
228 #ifdef CONFIG_SCST_EXTRACHECKS
229         switch (cmd->state) {
230         case SCST_CMD_STATE_PRE_XMIT_RESP:
231         case SCST_CMD_STATE_XMIT_RESP:
232         case SCST_CMD_STATE_FINISHED:
233         case SCST_CMD_STATE_XMIT_WAIT:
234                 PRINT_CRIT_ERROR("Wrong cmd state %x (cmd %p, op %x)",
235                         cmd->state, cmd, cmd->cdb[0]);
236                 sBUG();
237         }
238 #endif
239
240         cmd->state = scst_get_cmd_abnormal_done_state(cmd);
241
242         EXTRACHECKS_BUG_ON((cmd->state != SCST_CMD_STATE_PRE_XMIT_RESP) &&
243                            (cmd->tgt_dev == NULL));
244
245         TRACE_EXIT();
246         return;
247 }
248 EXPORT_SYMBOL(scst_set_cmd_abnormal_done_state);
249
250 void scst_set_resp_data_len(struct scst_cmd *cmd, int resp_data_len)
251 {
252         int i, l;
253
254         TRACE_ENTRY();
255
256         scst_check_restore_sg_buff(cmd);
257         cmd->resp_data_len = resp_data_len;
258
259         if (resp_data_len == cmd->bufflen)
260                 goto out;
261
262         l = 0;
263         for (i = 0; i < cmd->sg_cnt; i++) {
264                 l += cmd->sg[i].length;
265                 if (l >= resp_data_len) {
266                         int left = resp_data_len - (l - cmd->sg[i].length);
267 #ifdef CONFIG_SCST_DEBUG
268                         TRACE(TRACE_SG_OP|TRACE_MEMORY, "cmd %p (tag %llu), "
269                                 "resp_data_len %d, i %d, cmd->sg[i].length %d, "
270                                 "left %d",
271                                 cmd, (long long unsigned int)cmd->tag,
272                                 resp_data_len, i,
273                                 cmd->sg[i].length, left);
274 #endif
275                         cmd->orig_sg_cnt = cmd->sg_cnt;
276                         cmd->orig_sg_entry = i;
277                         cmd->orig_entry_len = cmd->sg[i].length;
278                         cmd->sg_cnt = (left > 0) ? i+1 : i;
279                         cmd->sg[i].length = left;
280                         cmd->sg_buff_modified = 1;
281                         break;
282                 }
283         }
284
285 out:
286         TRACE_EXIT();
287         return;
288 }
289 EXPORT_SYMBOL(scst_set_resp_data_len);
290
291 /* Called under scst_mutex and suspended activity */
292 int scst_alloc_device(gfp_t gfp_mask, struct scst_device **out_dev)
293 {
294         struct scst_device *dev;
295         int res = 0;
296         static int dev_num; /* protected by scst_mutex */
297
298         TRACE_ENTRY();
299
300         dev = kzalloc(sizeof(*dev), gfp_mask);
301         if (dev == NULL) {
302                 TRACE(TRACE_OUT_OF_MEM, "%s",
303                         "Allocation of scst_device failed");
304                 res = -ENOMEM;
305                 goto out;
306         }
307
308         dev->handler = &scst_null_devtype;
309         dev->p_cmd_lists = &scst_main_cmd_lists;
310         atomic_set(&dev->dev_cmd_count, 0);
311         atomic_set(&dev->write_cmd_count, 0);
312         scst_init_mem_lim(&dev->dev_mem_lim);
313         spin_lock_init(&dev->dev_lock);
314         atomic_set(&dev->on_dev_count, 0);
315         INIT_LIST_HEAD(&dev->blocked_cmd_list);
316         INIT_LIST_HEAD(&dev->dev_tgt_dev_list);
317         INIT_LIST_HEAD(&dev->dev_acg_dev_list);
318         INIT_LIST_HEAD(&dev->threads_list);
319         init_waitqueue_head(&dev->on_dev_waitQ);
320         dev->dev_double_ua_possible = 1;
321         dev->queue_alg = SCST_CONTR_MODE_QUEUE_ALG_UNRESTRICTED_REORDER;
322         dev->dev_num = dev_num++;
323
324         *out_dev = dev;
325
326 out:
327         TRACE_EXIT_RES(res);
328         return res;
329 }
330
331 /* Called under scst_mutex and suspended activity */
332 void scst_free_device(struct scst_device *dev)
333 {
334         TRACE_ENTRY();
335
336 #ifdef CONFIG_SCST_EXTRACHECKS
337         if (!list_empty(&dev->dev_tgt_dev_list) ||
338             !list_empty(&dev->dev_acg_dev_list)) {
339                 PRINT_CRIT_ERROR("%s: dev_tgt_dev_list or dev_acg_dev_list "
340                         "is not empty!", __func__);
341                 sBUG();
342         }
343 #endif
344
345         kfree(dev);
346
347         TRACE_EXIT();
348         return;
349 }
350
351 void scst_init_mem_lim(struct scst_mem_lim *mem_lim)
352 {
353         atomic_set(&mem_lim->alloced_pages, 0);
354         mem_lim->max_allowed_pages =
355                 ((uint64_t)scst_max_dev_cmd_mem << 10) >> (PAGE_SHIFT - 10);
356 }
357 EXPORT_SYMBOL(scst_init_mem_lim);
358
359 static struct scst_acg_dev *scst_alloc_acg_dev(struct scst_acg *acg,
360                                         struct scst_device *dev, uint64_t lun)
361 {
362         struct scst_acg_dev *res;
363
364         TRACE_ENTRY();
365
366 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 17)
367         res = kmem_cache_alloc(scst_acgd_cachep, GFP_KERNEL);
368 #else
369         res = kmem_cache_zalloc(scst_acgd_cachep, GFP_KERNEL);
370 #endif
371         if (res == NULL) {
372                 TRACE(TRACE_OUT_OF_MEM,
373                       "%s", "Allocation of scst_acg_dev failed");
374                 goto out;
375         }
376 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 17)
377         memset(res, 0, sizeof(*res));
378 #endif
379
380         res->dev = dev;
381         res->acg = acg;
382         res->lun = lun;
383
384 out:
385         TRACE_EXIT_HRES(res);
386         return res;
387 }
388
389 /* The activity supposed to be suspended and scst_mutex held */
390 static void scst_free_acg_dev(struct scst_acg_dev *acg_dev)
391 {
392         TRACE_ENTRY();
393
394         TRACE_DBG("Removing acg_dev %p from acg_dev_list and dev_acg_dev_list",
395                 acg_dev);
396         list_del(&acg_dev->acg_dev_list_entry);
397         list_del(&acg_dev->dev_acg_dev_list_entry);
398
399         kmem_cache_free(scst_acgd_cachep, acg_dev);
400
401         TRACE_EXIT();
402         return;
403 }
404
405 /* The activity supposed to be suspended and scst_mutex held */
406 struct scst_acg *scst_alloc_add_acg(const char *acg_name)
407 {
408         struct scst_acg *acg;
409
410         TRACE_ENTRY();
411
412         acg = kzalloc(sizeof(*acg), GFP_KERNEL);
413         if (acg == NULL) {
414                 TRACE(TRACE_OUT_OF_MEM, "%s", "Allocation of acg failed");
415                 goto out;
416         }
417
418         INIT_LIST_HEAD(&acg->acg_dev_list);
419         INIT_LIST_HEAD(&acg->acg_sess_list);
420         INIT_LIST_HEAD(&acg->acn_list);
421         acg->acg_name = acg_name;
422
423         TRACE_DBG("Adding acg %s to scst_acg_list", acg_name);
424         list_add_tail(&acg->scst_acg_list_entry, &scst_acg_list);
425
426 out:
427         TRACE_EXIT_HRES(acg);
428         return acg;
429 }
430
431 /* The activity supposed to be suspended and scst_mutex held */
432 int scst_destroy_acg(struct scst_acg *acg)
433 {
434         struct scst_acn *n, *nn;
435         struct scst_acg_dev *acg_dev, *acg_dev_tmp;
436         int res = 0;
437
438         TRACE_ENTRY();
439
440         if (!list_empty(&acg->acg_sess_list)) {
441                 PRINT_ERROR("%s: acg_sess_list is not empty!", __func__);
442                 res = -EBUSY;
443                 goto out;
444         }
445
446         TRACE_DBG("Removing acg %s from scst_acg_list", acg->acg_name);
447         list_del(&acg->scst_acg_list_entry);
448
449         /* Freeing acg_devs */
450         list_for_each_entry_safe(acg_dev, acg_dev_tmp, &acg->acg_dev_list,
451                         acg_dev_list_entry) {
452                 struct scst_tgt_dev *tgt_dev, *tt;
453                 list_for_each_entry_safe(tgt_dev, tt,
454                                  &acg_dev->dev->dev_tgt_dev_list,
455                                  dev_tgt_dev_list_entry) {
456                         if (tgt_dev->acg_dev == acg_dev)
457                                 scst_free_tgt_dev(tgt_dev);
458                 }
459                 scst_free_acg_dev(acg_dev);
460         }
461
462         /* Freeing names */
463         list_for_each_entry_safe(n, nn, &acg->acn_list,
464                         acn_list_entry) {
465                 list_del(&n->acn_list_entry);
466                 kfree(n->name);
467                 kfree(n);
468         }
469         INIT_LIST_HEAD(&acg->acn_list);
470
471         kfree(acg);
472 out:
473         TRACE_EXIT_RES(res);
474         return res;
475 }
476
477 /*
478  * scst_mutex supposed to be held, there must not be parallel activity in this
479  * session.
480  */
481 static struct scst_tgt_dev *scst_alloc_add_tgt_dev(struct scst_session *sess,
482         struct scst_acg_dev *acg_dev)
483 {
484         int ini_sg, ini_unchecked_isa_dma, ini_use_clustering;
485         struct scst_tgt_dev *tgt_dev;
486         struct scst_device *dev = acg_dev->dev;
487         struct list_head *sess_tgt_dev_list_head;
488         struct scst_tgt_template *vtt = sess->tgt->tgtt;
489         int rc, i;
490
491         TRACE_ENTRY();
492
493 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 17)
494         tgt_dev = kmem_cache_alloc(scst_tgtd_cachep, GFP_KERNEL);
495 #else
496         tgt_dev = kmem_cache_zalloc(scst_tgtd_cachep, GFP_KERNEL);
497 #endif
498         if (tgt_dev == NULL) {
499                 TRACE(TRACE_OUT_OF_MEM, "%s",
500                       "Allocation of scst_tgt_dev failed");
501                 goto out;
502         }
503 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 17)
504         memset(tgt_dev, 0, sizeof(*tgt_dev));
505 #endif
506
507         tgt_dev->dev = dev;
508         tgt_dev->lun = acg_dev->lun;
509         tgt_dev->acg_dev = acg_dev;
510         tgt_dev->sess = sess;
511         atomic_set(&tgt_dev->tgt_dev_cmd_count, 0);
512
513         scst_sgv_pool_use_norm(tgt_dev);
514
515         if (dev->scsi_dev != NULL) {
516                 ini_sg = dev->scsi_dev->host->sg_tablesize;
517                 ini_unchecked_isa_dma = dev->scsi_dev->host->unchecked_isa_dma;
518                 ini_use_clustering = (dev->scsi_dev->host->use_clustering ==
519                                 ENABLE_CLUSTERING);
520         } else {
521                 ini_sg = (1 << 15) /* infinite */;
522                 ini_unchecked_isa_dma = 0;
523                 ini_use_clustering = 0;
524         }
525         tgt_dev->max_sg_cnt = min(ini_sg, sess->tgt->sg_tablesize);
526
527         if ((sess->tgt->tgtt->use_clustering || ini_use_clustering) &&
528             !sess->tgt->tgtt->no_clustering)
529                 scst_sgv_pool_use_norm_clust(tgt_dev);
530
531         if (sess->tgt->tgtt->unchecked_isa_dma || ini_unchecked_isa_dma)
532                 scst_sgv_pool_use_dma(tgt_dev);
533
534         if (dev->scsi_dev != NULL) {
535                 TRACE_MGMT_DBG("host=%d, channel=%d, id=%d, lun=%d, "
536                       "SCST lun=%lld", dev->scsi_dev->host->host_no,
537                       dev->scsi_dev->channel, dev->scsi_dev->id,
538                       dev->scsi_dev->lun,
539                       (long long unsigned int)tgt_dev->lun);
540         } else {
541                 TRACE_MGMT_DBG("Virtual device %s on SCST lun=%lld",
542                                dev->virt_name,
543                                (long long unsigned int)tgt_dev->lun);
544         }
545
546         spin_lock_init(&tgt_dev->tgt_dev_lock);
547         INIT_LIST_HEAD(&tgt_dev->UA_list);
548         spin_lock_init(&tgt_dev->thr_data_lock);
549         INIT_LIST_HEAD(&tgt_dev->thr_data_list);
550         spin_lock_init(&tgt_dev->sn_lock);
551         INIT_LIST_HEAD(&tgt_dev->deferred_cmd_list);
552         INIT_LIST_HEAD(&tgt_dev->skipped_sn_list);
553         tgt_dev->expected_sn = 1;
554         tgt_dev->num_free_sn_slots = ARRAY_SIZE(tgt_dev->sn_slots)-1;
555         tgt_dev->cur_sn_slot = &tgt_dev->sn_slots[0];
556         for (i = 0; i < (int)ARRAY_SIZE(tgt_dev->sn_slots); i++)
557                 atomic_set(&tgt_dev->sn_slots[i], 0);
558
559         if (dev->handler->parse_atomic &&
560             (sess->tgt->tgtt->preprocessing_done == NULL)) {
561                 if (sess->tgt->tgtt->rdy_to_xfer_atomic)
562                         __set_bit(SCST_TGT_DEV_AFTER_INIT_WR_ATOMIC,
563                                 &tgt_dev->tgt_dev_flags);
564                 if (dev->handler->exec_atomic)
565                         __set_bit(SCST_TGT_DEV_AFTER_INIT_OTH_ATOMIC,
566                                 &tgt_dev->tgt_dev_flags);
567         }
568         if (dev->handler->exec_atomic) {
569                 if (sess->tgt->tgtt->rdy_to_xfer_atomic)
570                         __set_bit(SCST_TGT_DEV_AFTER_RESTART_WR_ATOMIC,
571                                 &tgt_dev->tgt_dev_flags);
572                 __set_bit(SCST_TGT_DEV_AFTER_RESTART_OTH_ATOMIC,
573                                 &tgt_dev->tgt_dev_flags);
574                 __set_bit(SCST_TGT_DEV_AFTER_RX_DATA_ATOMIC,
575                         &tgt_dev->tgt_dev_flags);
576         }
577         if (dev->handler->dev_done_atomic &&
578             sess->tgt->tgtt->xmit_response_atomic) {
579                 __set_bit(SCST_TGT_DEV_AFTER_EXEC_ATOMIC,
580                         &tgt_dev->tgt_dev_flags);
581         }
582
583         spin_lock_bh(&scst_temp_UA_lock);
584         scst_set_sense(scst_temp_UA, sizeof(scst_temp_UA),
585                 SCST_LOAD_SENSE(scst_sense_reset_UA));
586         scst_alloc_set_UA(tgt_dev, scst_temp_UA, sizeof(scst_temp_UA), 0);
587         spin_unlock_bh(&scst_temp_UA_lock);
588
589         tm_dbg_init_tgt_dev(tgt_dev, acg_dev);
590
591         if (vtt->threads_num > 0) {
592                 rc = 0;
593                 if (dev->handler->threads_num > 0)
594                         rc = scst_add_dev_threads(dev, vtt->threads_num);
595                 else if (dev->handler->threads_num == 0)
596                         rc = scst_add_cmd_threads(vtt->threads_num);
597                 if (rc != 0)
598                         goto out_free;
599         }
600
601         if (dev->handler && dev->handler->attach_tgt) {
602                 TRACE_DBG("Calling dev handler's attach_tgt(%p)",
603                       tgt_dev);
604                 rc = dev->handler->attach_tgt(tgt_dev);
605                 TRACE_DBG("%s", "Dev handler's attach_tgt() returned");
606                 if (rc != 0) {
607                         PRINT_ERROR("Device handler's %s attach_tgt() "
608                             "failed: %d", dev->handler->name, rc);
609                         goto out_thr_free;
610                 }
611         }
612
613         spin_lock_bh(&dev->dev_lock);
614         list_add_tail(&tgt_dev->dev_tgt_dev_list_entry, &dev->dev_tgt_dev_list);
615         if (dev->dev_reserved)
616                 __set_bit(SCST_TGT_DEV_RESERVED, &tgt_dev->tgt_dev_flags);
617         spin_unlock_bh(&dev->dev_lock);
618
619         sess_tgt_dev_list_head =
620                 &sess->sess_tgt_dev_list_hash[HASH_VAL(tgt_dev->lun)];
621         list_add_tail(&tgt_dev->sess_tgt_dev_list_entry,
622                       sess_tgt_dev_list_head);
623
624 out:
625         TRACE_EXIT();
626         return tgt_dev;
627
628 out_thr_free:
629         if (vtt->threads_num > 0) {
630                 if (dev->handler->threads_num > 0)
631                         scst_del_dev_threads(dev, vtt->threads_num);
632                 else if (dev->handler->threads_num == 0)
633                         scst_del_cmd_threads(vtt->threads_num);
634         }
635
636 out_free:
637         kmem_cache_free(scst_tgtd_cachep, tgt_dev);
638         tgt_dev = NULL;
639         goto out;
640 }
641
642 static void scst_clear_reservation(struct scst_tgt_dev *tgt_dev);
643
644 /* No locks supposed to be held, scst_mutex - held */
645 void scst_nexus_loss(struct scst_tgt_dev *tgt_dev)
646 {
647         TRACE_ENTRY();
648
649         scst_clear_reservation(tgt_dev);
650
651         /* With activity suspended the lock isn't needed, but let's be safe */
652         spin_lock_bh(&tgt_dev->tgt_dev_lock);
653         scst_free_all_UA(tgt_dev);
654         spin_unlock_bh(&tgt_dev->tgt_dev_lock);
655
656         spin_lock_bh(&scst_temp_UA_lock);
657         scst_set_sense(scst_temp_UA, sizeof(scst_temp_UA),
658                 SCST_LOAD_SENSE(scst_sense_nexus_loss_UA));
659         scst_check_set_UA(tgt_dev, scst_temp_UA, sizeof(scst_temp_UA), 0);
660         spin_unlock_bh(&scst_temp_UA_lock);
661
662         TRACE_EXIT();
663         return;
664 }
665
666 /*
667  * scst_mutex supposed to be held, there must not be parallel activity in this
668  * session.
669  */
670 static void scst_free_tgt_dev(struct scst_tgt_dev *tgt_dev)
671 {
672         struct scst_device *dev = tgt_dev->dev;
673         struct scst_tgt_template *vtt = tgt_dev->sess->tgt->tgtt;
674
675         TRACE_ENTRY();
676
677         tm_dbg_deinit_tgt_dev(tgt_dev);
678
679         spin_lock_bh(&dev->dev_lock);
680         list_del(&tgt_dev->dev_tgt_dev_list_entry);
681         spin_unlock_bh(&dev->dev_lock);
682
683         list_del(&tgt_dev->sess_tgt_dev_list_entry);
684
685         scst_clear_reservation(tgt_dev);
686         scst_free_all_UA(tgt_dev);
687
688         if (dev->handler && dev->handler->detach_tgt) {
689                 TRACE_DBG("Calling dev handler's detach_tgt(%p)",
690                       tgt_dev);
691                 dev->handler->detach_tgt(tgt_dev);
692                 TRACE_DBG("%s", "Dev handler's detach_tgt() returned");
693         }
694
695         if (vtt->threads_num > 0) {
696                 if (dev->handler->threads_num > 0)
697                         scst_del_dev_threads(dev, vtt->threads_num);
698                 else if (dev->handler->threads_num == 0)
699                         scst_del_cmd_threads(vtt->threads_num);
700         }
701
702         kmem_cache_free(scst_tgtd_cachep, tgt_dev);
703
704         TRACE_EXIT();
705         return;
706 }
707
708 /* scst_mutex supposed to be held */
709 int scst_sess_alloc_tgt_devs(struct scst_session *sess)
710 {
711         int res = 0;
712         struct scst_acg_dev *acg_dev;
713         struct scst_tgt_dev *tgt_dev;
714
715         TRACE_ENTRY();
716
717         list_for_each_entry(acg_dev, &sess->acg->acg_dev_list,
718                         acg_dev_list_entry) {
719                 tgt_dev = scst_alloc_add_tgt_dev(sess, acg_dev);
720                 if (tgt_dev == NULL) {
721                         res = -ENOMEM;
722                         goto out_free;
723                 }
724         }
725
726 out:
727         TRACE_EXIT();
728         return res;
729
730 out_free:
731         scst_sess_free_tgt_devs(sess);
732         goto out;
733 }
734
735 /*
736  * scst_mutex supposed to be held, there must not be parallel activity in this
737  * session.
738  */
739 static void scst_sess_free_tgt_devs(struct scst_session *sess)
740 {
741         int i;
742         struct scst_tgt_dev *tgt_dev, *t;
743
744         TRACE_ENTRY();
745
746         /* The session is going down, no users, so no locks */
747         for (i = 0; i < TGT_DEV_HASH_SIZE; i++) {
748                 struct list_head *sess_tgt_dev_list_head =
749                         &sess->sess_tgt_dev_list_hash[i];
750                 list_for_each_entry_safe(tgt_dev, t, sess_tgt_dev_list_head,
751                                 sess_tgt_dev_list_entry) {
752                         scst_free_tgt_dev(tgt_dev);
753                 }
754                 INIT_LIST_HEAD(sess_tgt_dev_list_head);
755         }
756
757         TRACE_EXIT();
758         return;
759 }
760
761 /* The activity supposed to be suspended and scst_mutex held */
762 int scst_acg_add_dev(struct scst_acg *acg, struct scst_device *dev,
763                      uint64_t lun, int read_only)
764 {
765         int res = 0;
766         struct scst_acg_dev *acg_dev;
767         struct scst_tgt_dev *tgt_dev;
768         struct scst_session *sess;
769         LIST_HEAD(tmp_tgt_dev_list);
770
771         TRACE_ENTRY();
772
773         INIT_LIST_HEAD(&tmp_tgt_dev_list);
774
775 #ifdef CONFIG_SCST_EXTRACHECKS
776         list_for_each_entry(acg_dev, &acg->acg_dev_list, acg_dev_list_entry) {
777                 if (acg_dev->dev == dev) {
778                         PRINT_ERROR("Device is already in group %s",
779                                 acg->acg_name);
780                         res = -EINVAL;
781                         goto out;
782                 }
783         }
784 #endif
785
786         acg_dev = scst_alloc_acg_dev(acg, dev, lun);
787         if (acg_dev == NULL) {
788                 res = -ENOMEM;
789                 goto out;
790         }
791         acg_dev->rd_only_flag = read_only;
792
793         TRACE_DBG("Adding acg_dev %p to acg_dev_list and dev_acg_dev_list",
794                 acg_dev);
795         list_add_tail(&acg_dev->acg_dev_list_entry, &acg->acg_dev_list);
796         list_add_tail(&acg_dev->dev_acg_dev_list_entry, &dev->dev_acg_dev_list);
797
798         list_for_each_entry(sess, &acg->acg_sess_list, acg_sess_list_entry) {
799                 tgt_dev = scst_alloc_add_tgt_dev(sess, acg_dev);
800                 if (tgt_dev == NULL) {
801                         res = -ENOMEM;
802                         goto out_free;
803                 }
804                 list_add_tail(&tgt_dev->extra_tgt_dev_list_entry,
805                               &tmp_tgt_dev_list);
806         }
807
808 out:
809         if (res == 0) {
810                 if (dev->virt_name != NULL) {
811                         PRINT_INFO("Added device %s to group %s (LUN %lld, "
812                                 "rd_only %d)", dev->virt_name, acg->acg_name,
813                                 (long long unsigned int)lun,
814                                 read_only);
815                 } else {
816                         PRINT_INFO("Added device %d:%d:%d:%d to group %s (LUN "
817                                 "%lld, rd_only %d)",
818                                 dev->scsi_dev->host->host_no,
819                                 dev->scsi_dev->channel, dev->scsi_dev->id,
820                                 dev->scsi_dev->lun, acg->acg_name,
821                                 (long long unsigned int)lun,
822                                 read_only);
823                 }
824         }
825
826         TRACE_EXIT_RES(res);
827         return res;
828
829 out_free:
830         list_for_each_entry(tgt_dev, &tmp_tgt_dev_list,
831                          extra_tgt_dev_list_entry) {
832                 scst_free_tgt_dev(tgt_dev);
833         }
834         scst_free_acg_dev(acg_dev);
835         goto out;
836 }
837
838 /* The activity supposed to be suspended and scst_mutex held */
839 int scst_acg_remove_dev(struct scst_acg *acg, struct scst_device *dev)
840 {
841         int res = 0;
842         struct scst_acg_dev *acg_dev = NULL, *a;
843         struct scst_tgt_dev *tgt_dev, *tt;
844
845         TRACE_ENTRY();
846
847         list_for_each_entry(a, &acg->acg_dev_list, acg_dev_list_entry) {
848                 if (a->dev == dev) {
849                         acg_dev = a;
850                         break;
851                 }
852         }
853
854         if (acg_dev == NULL) {
855                 PRINT_ERROR("Device is not found in group %s", acg->acg_name);
856                 res = -EINVAL;
857                 goto out;
858         }
859
860         list_for_each_entry_safe(tgt_dev, tt, &dev->dev_tgt_dev_list,
861                          dev_tgt_dev_list_entry) {
862                 if (tgt_dev->acg_dev == acg_dev)
863                         scst_free_tgt_dev(tgt_dev);
864         }
865         scst_free_acg_dev(acg_dev);
866
867 out:
868         if (res == 0) {
869                 if (dev->virt_name != NULL) {
870                         PRINT_INFO("Removed device %s from group %s",
871                                 dev->virt_name, acg->acg_name);
872                 } else {
873                         PRINT_INFO("Removed device %d:%d:%d:%d from group %s",
874                                 dev->scsi_dev->host->host_no,
875                                 dev->scsi_dev->channel, dev->scsi_dev->id,
876                                 dev->scsi_dev->lun, acg->acg_name);
877                 }
878         }
879
880         TRACE_EXIT_RES(res);
881         return res;
882 }
883
884 /* scst_mutex supposed to be held */
885 int scst_acg_add_name(struct scst_acg *acg, const char *name)
886 {
887         int res = 0;
888         struct scst_acn *n;
889         int len;
890         char *nm;
891
892         TRACE_ENTRY();
893
894         list_for_each_entry(n, &acg->acn_list, acn_list_entry)
895         {
896                 if (strcmp(n->name, name) == 0) {
897                         PRINT_ERROR("Name %s already exists in group %s",
898                                 name, acg->acg_name);
899                         res = -EINVAL;
900                         goto out;
901                 }
902         }
903
904         n = kmalloc(sizeof(*n), GFP_KERNEL);
905         if (n == NULL) {
906                 PRINT_ERROR("%s", "Unable to allocate scst_acn");
907                 res = -ENOMEM;
908                 goto out;
909         }
910
911         len = strlen(name);
912         nm = kmalloc(len + 1, GFP_KERNEL);
913         if (nm == NULL) {
914                 PRINT_ERROR("%s", "Unable to allocate scst_acn->name");
915                 res = -ENOMEM;
916                 goto out_free;
917         }
918
919         strcpy(nm, name);
920         n->name = nm;
921
922         list_add_tail(&n->acn_list_entry, &acg->acn_list);
923
924 out:
925         if (res == 0)
926                 PRINT_INFO("Added name %s to group %s", name, acg->acg_name);
927
928         TRACE_EXIT_RES(res);
929         return res;
930
931 out_free:
932         kfree(n);
933         goto out;
934 }
935
936 /* scst_mutex supposed to be held */
937 int scst_acg_remove_name(struct scst_acg *acg, const char *name)
938 {
939         int res = -EINVAL;
940         struct scst_acn *n;
941
942         TRACE_ENTRY();
943
944         list_for_each_entry(n, &acg->acn_list, acn_list_entry)
945         {
946                 if (strcmp(n->name, name) == 0) {
947                         list_del(&n->acn_list_entry);
948                         kfree(n->name);
949                         kfree(n);
950                         res = 0;
951                         break;
952                 }
953         }
954
955         if (res == 0) {
956                 PRINT_INFO("Removed name %s from group %s", name,
957                         acg->acg_name);
958         } else {
959                 PRINT_ERROR("Unable to find name %s in group %s", name,
960                         acg->acg_name);
961         }
962
963         TRACE_EXIT_RES(res);
964         return res;
965 }
966
967 static struct scst_cmd *scst_create_prepare_internal_cmd(
968         struct scst_cmd *orig_cmd, int bufsize)
969 {
970         struct scst_cmd *res;
971         gfp_t gfp_mask = scst_cmd_atomic(orig_cmd) ? GFP_ATOMIC : GFP_KERNEL;
972
973         TRACE_ENTRY();
974
975         res = scst_alloc_cmd(gfp_mask);
976         if (res == NULL)
977                 goto out;
978
979         res->cmd_lists = orig_cmd->cmd_lists;
980         res->sess = orig_cmd->sess;
981         res->atomic = scst_cmd_atomic(orig_cmd);
982         res->internal = 1;
983         res->tgtt = orig_cmd->tgtt;
984         res->tgt = orig_cmd->tgt;
985         res->dev = orig_cmd->dev;
986         res->tgt_dev = orig_cmd->tgt_dev;
987         res->lun = orig_cmd->lun;
988         res->queue_type = SCST_CMD_QUEUE_HEAD_OF_QUEUE;
989         res->data_direction = SCST_DATA_UNKNOWN;
990         res->orig_cmd = orig_cmd;
991         res->bufflen = bufsize;
992
993         res->state = SCST_CMD_STATE_PRE_PARSE;
994
995 out:
996         TRACE_EXIT_HRES((unsigned long)res);
997         return res;
998 }
999
1000 static void scst_free_internal_cmd(struct scst_cmd *cmd)
1001 {
1002         TRACE_ENTRY();
1003
1004         __scst_cmd_put(cmd);
1005
1006         TRACE_EXIT();
1007         return;
1008 }
1009
1010 int scst_prepare_request_sense(struct scst_cmd *orig_cmd)
1011 {
1012         int res = 0;
1013 #define sbuf_size 252
1014         static const uint8_t request_sense[6] =
1015             { REQUEST_SENSE, 0, 0, 0, sbuf_size, 0 };
1016         struct scst_cmd *rs_cmd;
1017
1018         TRACE_ENTRY();
1019
1020         rs_cmd = scst_create_prepare_internal_cmd(orig_cmd, sbuf_size);
1021         if (rs_cmd == NULL)
1022                 goto out_error;
1023
1024         memcpy(rs_cmd->cdb, request_sense, sizeof(request_sense));
1025         rs_cmd->cdb_len = sizeof(request_sense);
1026         rs_cmd->data_direction = SCST_DATA_READ;
1027         rs_cmd->expected_data_direction = rs_cmd->data_direction;
1028         rs_cmd->expected_transfer_len = sbuf_size;
1029         rs_cmd->expected_values_set = 1;
1030
1031         TRACE(TRACE_MGMT_MINOR, "Adding REQUEST SENSE cmd %p to head of active "
1032                 "cmd list ", rs_cmd);
1033         spin_lock_irq(&rs_cmd->cmd_lists->cmd_list_lock);
1034         list_add(&rs_cmd->cmd_list_entry, &rs_cmd->cmd_lists->active_cmd_list);
1035         spin_unlock_irq(&rs_cmd->cmd_lists->cmd_list_lock);
1036         wake_up(&rs_cmd->cmd_lists->cmd_list_waitQ);
1037
1038 out:
1039         TRACE_EXIT_RES(res);
1040         return res;
1041
1042 out_error:
1043         res = -1;
1044         goto out;
1045 #undef sbuf_size
1046 }
1047
1048 struct scst_cmd *scst_complete_request_sense(struct scst_cmd *req_cmd)
1049 {
1050         struct scst_cmd *orig_cmd = req_cmd->orig_cmd;
1051         uint8_t *buf;
1052         int len;
1053
1054         TRACE_ENTRY();
1055
1056         sBUG_ON(orig_cmd == NULL);
1057
1058         len = scst_get_buf_first(req_cmd, &buf);
1059
1060         if (scsi_status_is_good(req_cmd->status) && (len > 0) &&
1061             SCST_SENSE_VALID(buf) && (!SCST_NO_SENSE(buf))) {
1062                 PRINT_BUFF_FLAG(TRACE_SCSI, "REQUEST SENSE returned",
1063                         buf, len);
1064                 scst_alloc_set_sense(orig_cmd, scst_cmd_atomic(req_cmd), buf,
1065                         len);
1066         } else {
1067                 PRINT_ERROR("%s", "Unable to get the sense via "
1068                         "REQUEST SENSE, returning HARDWARE ERROR");
1069                 scst_set_cmd_error(orig_cmd,
1070                         SCST_LOAD_SENSE(scst_sense_hardw_error));
1071         }
1072
1073         if (len > 0)
1074                 scst_put_buf(req_cmd, buf);
1075
1076         scst_free_internal_cmd(req_cmd);
1077
1078         TRACE_EXIT_HRES((unsigned long)orig_cmd);
1079         return orig_cmd;
1080 }
1081
1082 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 18)
1083 static void scst_req_done(struct scsi_cmnd *scsi_cmd)
1084 {
1085         struct scsi_request *req;
1086
1087         TRACE_ENTRY();
1088
1089         if (scsi_cmd && (req = scsi_cmd->sc_request)) {
1090                 if (req) {
1091                         if (req->sr_bufflen)
1092                                 kfree(req->sr_buffer);
1093                         scsi_release_request(req);
1094                 }
1095         }
1096
1097         TRACE_EXIT();
1098         return;
1099 }
1100
1101 static void scst_send_release(struct scst_device *dev)
1102 {
1103         struct scsi_request *req;
1104         struct scsi_device *scsi_dev;
1105         uint8_t cdb[6];
1106
1107         TRACE_ENTRY();
1108
1109         if (dev->scsi_dev == NULL)
1110                 goto out;
1111
1112         scsi_dev = dev->scsi_dev;
1113
1114         req = scsi_allocate_request(scsi_dev, GFP_KERNEL);
1115         if (req == NULL) {
1116                 PRINT_ERROR("Allocation of scsi_request failed: unable "
1117                             "to RELEASE device %d:%d:%d:%d",
1118                             scsi_dev->host->host_no, scsi_dev->channel,
1119                             scsi_dev->id, scsi_dev->lun);
1120                 goto out;
1121         }
1122
1123         memset(cdb, 0, sizeof(cdb));
1124         cdb[0] = RELEASE;
1125         cdb[1] = (scsi_dev->scsi_level <= SCSI_2) ?
1126             ((scsi_dev->lun << 5) & 0xe0) : 0;
1127         memcpy(req->sr_cmnd, cdb, sizeof(cdb));
1128         req->sr_cmd_len = sizeof(cdb);
1129         req->sr_data_direction = SCST_DATA_NONE;
1130         req->sr_use_sg = 0;
1131         req->sr_bufflen = 0;
1132         req->sr_buffer = NULL;
1133         req->sr_request->rq_disk = dev->rq_disk;
1134         req->sr_sense_buffer[0] = 0;
1135
1136         TRACE(TRACE_DEBUG | TRACE_SCSI, "Sending RELEASE req %p to SCSI "
1137                 "mid-level", req);
1138         scst_do_req(req, req->sr_cmnd, (void *)req->sr_buffer, req->sr_bufflen,
1139                     scst_req_done, 15, 3);
1140
1141 out:
1142         TRACE_EXIT();
1143         return;
1144 }
1145 #else /* LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 18) */
1146 static void scst_send_release(struct scst_device *dev)
1147 {
1148         struct scsi_device *scsi_dev;
1149         unsigned char cdb[6];
1150         unsigned char *sense;
1151         int rc, i;
1152
1153         TRACE_ENTRY();
1154
1155         if (dev->scsi_dev == NULL)
1156                 goto out;
1157
1158         /* We can't afford missing RELEASE due to memory shortage */
1159         sense = kmalloc(SCST_SENSE_BUFFERSIZE, GFP_KERNEL|__GFP_NOFAIL);
1160
1161         scsi_dev = dev->scsi_dev;
1162
1163         for (i = 0; i < 5; i++) {
1164                 memset(cdb, 0, sizeof(cdb));
1165                 cdb[0] = RELEASE;
1166                 cdb[1] = (scsi_dev->scsi_level <= SCSI_2) ?
1167                     ((scsi_dev->lun << 5) & 0xe0) : 0;
1168
1169                 memset(sense, 0, SCST_SENSE_BUFFERSIZE);
1170
1171                 TRACE(TRACE_DEBUG | TRACE_SCSI, "%s", "Sending RELEASE req to "
1172                         "SCSI mid-level");
1173                 rc = scsi_execute(scsi_dev, cdb, SCST_DATA_NONE, NULL, 0,
1174                                 sense, 15, 0, 0);
1175                 TRACE_DBG("MODE_SENSE done: %x", rc);
1176
1177                 if (scsi_status_is_good(rc)) {
1178                         break;
1179                 } else {
1180                         PRINT_ERROR("RELEASE failed: %d", rc);
1181                         PRINT_BUFFER("RELEASE sense", sense,
1182                                 SCST_SENSE_BUFFERSIZE);
1183                         scst_check_internal_sense(dev, rc,
1184                                         sense, SCST_SENSE_BUFFERSIZE);
1185                 }
1186         }
1187
1188         kfree(sense);
1189
1190 out:
1191         TRACE_EXIT();
1192         return;
1193 }
1194 #endif /* LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 18) */
1195
1196 /* scst_mutex supposed to be held */
1197 static void scst_clear_reservation(struct scst_tgt_dev *tgt_dev)
1198 {
1199         struct scst_device *dev = tgt_dev->dev;
1200         int release = 0;
1201
1202         TRACE_ENTRY();
1203
1204         spin_lock_bh(&dev->dev_lock);
1205         if (dev->dev_reserved &&
1206             !test_bit(SCST_TGT_DEV_RESERVED, &tgt_dev->tgt_dev_flags)) {
1207                 /* This is one who holds the reservation */
1208                 struct scst_tgt_dev *tgt_dev_tmp;
1209                 list_for_each_entry(tgt_dev_tmp, &dev->dev_tgt_dev_list,
1210                                     dev_tgt_dev_list_entry) {
1211                         clear_bit(SCST_TGT_DEV_RESERVED,
1212                                     &tgt_dev_tmp->tgt_dev_flags);
1213                 }
1214                 dev->dev_reserved = 0;
1215                 release = 1;
1216         }
1217         spin_unlock_bh(&dev->dev_lock);
1218
1219         if (release)
1220                 scst_send_release(dev);
1221
1222         TRACE_EXIT();
1223         return;
1224 }
1225
1226 struct scst_session *scst_alloc_session(struct scst_tgt *tgt, gfp_t gfp_mask,
1227         const char *initiator_name)
1228 {
1229         struct scst_session *sess;
1230         int i;
1231         int len;
1232         char *nm;
1233
1234         TRACE_ENTRY();
1235
1236 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 17)
1237         sess = kmem_cache_alloc(scst_sess_cachep, gfp_mask);
1238 #else
1239         sess = kmem_cache_zalloc(scst_sess_cachep, gfp_mask);
1240 #endif
1241         if (sess == NULL) {
1242                 TRACE(TRACE_OUT_OF_MEM, "%s",
1243                       "Allocation of scst_session failed");
1244                 goto out;
1245         }
1246 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 17)
1247         memset(sess, 0, sizeof(*sess));
1248 #endif
1249
1250         sess->init_phase = SCST_SESS_IPH_INITING;
1251         sess->shut_phase = SCST_SESS_SPH_READY;
1252         atomic_set(&sess->refcnt, 0);
1253         for (i = 0; i < TGT_DEV_HASH_SIZE; i++) {
1254                 struct list_head *sess_tgt_dev_list_head =
1255                          &sess->sess_tgt_dev_list_hash[i];
1256                 INIT_LIST_HEAD(sess_tgt_dev_list_head);
1257         }
1258         spin_lock_init(&sess->sess_list_lock);
1259         INIT_LIST_HEAD(&sess->search_cmd_list);
1260         sess->tgt = tgt;
1261         INIT_LIST_HEAD(&sess->init_deferred_cmd_list);
1262         INIT_LIST_HEAD(&sess->init_deferred_mcmd_list);
1263
1264 #ifdef CONFIG_SCST_MEASURE_LATENCY
1265         spin_lock_init(&sess->meas_lock);
1266 #endif
1267
1268         len = strlen(initiator_name);
1269         nm = kmalloc(len + 1, gfp_mask);
1270         if (nm == NULL) {
1271                 PRINT_ERROR("%s", "Unable to allocate sess->initiator_name");
1272                 goto out_free;
1273         }
1274
1275         strcpy(nm, initiator_name);
1276         sess->initiator_name = nm;
1277
1278 out:
1279         TRACE_EXIT();
1280         return sess;
1281
1282 out_free:
1283         kmem_cache_free(scst_sess_cachep, sess);
1284         sess = NULL;
1285         goto out;
1286 }
1287
1288 void scst_free_session(struct scst_session *sess)
1289 {
1290         TRACE_ENTRY();
1291
1292         mutex_lock(&scst_mutex);
1293
1294         TRACE_DBG("Removing sess %p from the list", sess);
1295         list_del(&sess->sess_list_entry);
1296         TRACE_DBG("Removing session %p from acg %s", sess, sess->acg->acg_name);
1297         list_del(&sess->acg_sess_list_entry);
1298
1299         scst_sess_free_tgt_devs(sess);
1300
1301         wake_up_all(&sess->tgt->unreg_waitQ);
1302
1303         mutex_unlock(&scst_mutex);
1304
1305         kfree(sess->initiator_name);
1306         kmem_cache_free(scst_sess_cachep, sess);
1307
1308         TRACE_EXIT();
1309         return;
1310 }
1311
1312 void scst_free_session_callback(struct scst_session *sess)
1313 {
1314         struct completion *c;
1315
1316         TRACE_ENTRY();
1317
1318         TRACE_DBG("Freeing session %p", sess);
1319
1320         c = sess->shutdown_compl;
1321
1322         if (sess->unreg_done_fn) {
1323                 TRACE_DBG("Calling unreg_done_fn(%p)", sess);
1324                 sess->unreg_done_fn(sess);
1325                 TRACE_DBG("%s", "unreg_done_fn() returned");
1326         }
1327         scst_free_session(sess);
1328
1329         if (c)
1330                 complete_all(c);
1331
1332         TRACE_EXIT();
1333         return;
1334 }
1335
1336 void scst_sched_session_free(struct scst_session *sess)
1337 {
1338         unsigned long flags;
1339
1340         TRACE_ENTRY();
1341
1342         if (sess->shut_phase != SCST_SESS_SPH_SHUTDOWN) {
1343                 PRINT_CRIT_ERROR("session %p is going to shutdown with unknown "
1344                         "shut phase %lx", sess, sess->shut_phase);
1345                 sBUG();
1346         }
1347
1348         spin_lock_irqsave(&scst_mgmt_lock, flags);
1349         TRACE_DBG("Adding sess %p to scst_sess_shut_list", sess);
1350         list_add_tail(&sess->sess_shut_list_entry, &scst_sess_shut_list);
1351         spin_unlock_irqrestore(&scst_mgmt_lock, flags);
1352
1353         wake_up(&scst_mgmt_waitQ);
1354
1355         TRACE_EXIT();
1356         return;
1357 }
1358
1359 void scst_cmd_get(struct scst_cmd *cmd)
1360 {
1361         __scst_cmd_get(cmd);
1362 }
1363 EXPORT_SYMBOL(scst_cmd_get);
1364
1365 void scst_cmd_put(struct scst_cmd *cmd)
1366 {
1367         __scst_cmd_put(cmd);
1368 }
1369 EXPORT_SYMBOL(scst_cmd_put);
1370
1371 struct scst_cmd *scst_alloc_cmd(gfp_t gfp_mask)
1372 {
1373         struct scst_cmd *cmd;
1374
1375         TRACE_ENTRY();
1376
1377 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 17)
1378         cmd = kmem_cache_alloc(scst_cmd_cachep, gfp_mask);
1379 #else
1380         cmd = kmem_cache_zalloc(scst_cmd_cachep, gfp_mask);
1381 #endif
1382         if (cmd == NULL) {
1383                 TRACE(TRACE_OUT_OF_MEM, "%s", "Allocation of scst_cmd failed");
1384                 goto out;
1385         }
1386 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 17)
1387         memset(cmd, 0, sizeof(*cmd));
1388 #endif
1389
1390         cmd->state = SCST_CMD_STATE_INIT_WAIT;
1391         cmd->start_time = jiffies;
1392         atomic_set(&cmd->cmd_ref, 1);
1393         cmd->cmd_lists = &scst_main_cmd_lists;
1394         INIT_LIST_HEAD(&cmd->mgmt_cmd_list);
1395         cmd->queue_type = SCST_CMD_QUEUE_SIMPLE;
1396         cmd->timeout = SCST_DEFAULT_TIMEOUT;
1397         cmd->retries = 0;
1398         cmd->data_len = -1;
1399         cmd->is_send_status = 1;
1400         cmd->resp_data_len = -1;
1401
1402         cmd->dbl_ua_orig_data_direction = SCST_DATA_UNKNOWN;
1403         cmd->dbl_ua_orig_resp_data_len = -1;
1404
1405 out:
1406         TRACE_EXIT();
1407         return cmd;
1408 }
1409
1410 static void scst_destroy_put_cmd(struct scst_cmd *cmd)
1411 {
1412         scst_sess_put(cmd->sess);
1413
1414         /*
1415          * At this point tgt_dev can be dead, but the pointer remains non-NULL
1416          */
1417         if (likely(cmd->tgt_dev != NULL))
1418                 __scst_put();
1419
1420         scst_destroy_cmd(cmd);
1421         return;
1422 }
1423
1424 /* No locks supposed to be held */
1425 void scst_free_cmd(struct scst_cmd *cmd)
1426 {
1427         int destroy = 1;
1428
1429         TRACE_ENTRY();
1430
1431         TRACE_DBG("Freeing cmd %p (tag %llu)",
1432                   cmd, (long long unsigned int)cmd->tag);
1433
1434         if (unlikely(test_bit(SCST_CMD_ABORTED, &cmd->cmd_flags))) {
1435                 TRACE_MGMT_DBG("Freeing aborted cmd %p (scst_cmd_count %d)",
1436                         cmd, atomic_read(&scst_cmd_count));
1437         }
1438
1439         sBUG_ON(cmd->inc_blocking || cmd->needs_unblocking ||
1440                 cmd->dec_on_dev_needed);
1441
1442 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 18)
1443 #if defined(CONFIG_SCST_EXTRACHECKS)
1444         if (cmd->scsi_req) {
1445                 PRINT_ERROR("%s: %s", __func__, "Cmd with unfreed "
1446                         "scsi_req!");
1447                 scst_release_request(cmd);
1448         }
1449 #endif
1450 #endif
1451
1452         /*
1453          * Target driver can already free sg buffer before calling
1454          * scst_tgt_cmd_done(). E.g., scst_local has to do that.
1455          */
1456         if (!cmd->tgt_data_buf_alloced)
1457                 scst_check_restore_sg_buff(cmd);
1458
1459         if (unlikely(cmd->internal)) {
1460                 if (cmd->bufflen > 0)
1461                         scst_release_space(cmd);
1462                 scst_destroy_cmd(cmd);
1463                 goto out;
1464         }
1465
1466         if (cmd->tgtt->on_free_cmd != NULL) {
1467                 TRACE_DBG("Calling target's on_free_cmd(%p)", cmd);
1468                 cmd->tgtt->on_free_cmd(cmd);
1469                 TRACE_DBG("%s", "Target's on_free_cmd() returned");
1470         }
1471
1472         if (likely(cmd->dev != NULL)) {
1473                 struct scst_dev_type *handler = cmd->dev->handler;
1474                 if (handler->on_free_cmd != NULL) {
1475                         TRACE_DBG("Calling dev handler %s on_free_cmd(%p)",
1476                               handler->name, cmd);
1477                         handler->on_free_cmd(cmd);
1478                         TRACE_DBG("Dev handler %s on_free_cmd() returned",
1479                                 handler->name);
1480                 }
1481         }
1482
1483         scst_release_space(cmd);
1484
1485         if (unlikely(cmd->sense != NULL)) {
1486                 TRACE_MEM("Releasing sense %p (cmd %p)", cmd->sense, cmd);
1487                 mempool_free(cmd->sense, scst_sense_mempool);
1488                 cmd->sense = NULL;
1489         }
1490
1491         if (likely(cmd->tgt_dev != NULL)) {
1492 #ifdef CONFIG_SCST_EXTRACHECKS
1493                 if (unlikely(!cmd->sent_for_exec)) {
1494                         PRINT_ERROR("Finishing not executed cmd %p (opcode "
1495                             "%d, target %s, lun %lld, sn %ld, expected_sn %ld)",
1496                             cmd, cmd->cdb[0], cmd->tgtt->name,
1497                             (long long unsigned int)cmd->lun,
1498                             cmd->sn, cmd->tgt_dev->expected_sn);
1499                         scst_unblock_deferred(cmd->tgt_dev, cmd);
1500                 }
1501 #endif
1502
1503                 if (unlikely(cmd->out_of_sn)) {
1504                         TRACE_SN("Out of SN cmd %p (tag %llu, sn %ld), "
1505                                 "destroy=%d", cmd,
1506                                 (long long unsigned int)cmd->tag,
1507                                 cmd->sn, destroy);
1508                         destroy = test_and_set_bit(SCST_CMD_CAN_BE_DESTROYED,
1509                                         &cmd->cmd_flags);
1510                 }
1511         }
1512
1513         if (likely(destroy))
1514                 scst_destroy_put_cmd(cmd);
1515
1516 out:
1517         TRACE_EXIT();
1518         return;
1519 }
1520
1521 /* No locks supposed to be held. */
1522 void scst_check_retries(struct scst_tgt *tgt)
1523 {
1524         int need_wake_up = 0;
1525
1526         TRACE_ENTRY();
1527
1528         /*
1529          * We don't worry about overflow of finished_cmds, because we check
1530          * only for its change.
1531          */
1532         atomic_inc(&tgt->finished_cmds);
1533         /* See comment in scst_queue_retry_cmd() */
1534         smp_mb__after_atomic_inc();
1535         if (unlikely(tgt->retry_cmds > 0)) {
1536                 struct scst_cmd *c, *tc;
1537                 unsigned long flags;
1538
1539                 TRACE_RETRY("Checking retry cmd list (retry_cmds %d)",
1540                       tgt->retry_cmds);
1541
1542                 spin_lock_irqsave(&tgt->tgt_lock, flags);
1543                 list_for_each_entry_safe(c, tc, &tgt->retry_cmd_list,
1544                                 cmd_list_entry) {
1545                         tgt->retry_cmds--;
1546
1547                         TRACE_RETRY("Moving retry cmd %p to head of active "
1548                                 "cmd list (retry_cmds left %d)",
1549                                 c, tgt->retry_cmds);
1550                         spin_lock(&c->cmd_lists->cmd_list_lock);
1551                         list_move(&c->cmd_list_entry,
1552                                   &c->cmd_lists->active_cmd_list);
1553                         wake_up(&c->cmd_lists->cmd_list_waitQ);
1554                         spin_unlock(&c->cmd_lists->cmd_list_lock);
1555
1556                         need_wake_up++;
1557                         if (need_wake_up >= 2) /* "slow start" */
1558                                 break;
1559                 }
1560                 spin_unlock_irqrestore(&tgt->tgt_lock, flags);
1561         }
1562
1563         TRACE_EXIT();
1564         return;
1565 }
1566
1567 void scst_tgt_retry_timer_fn(unsigned long arg)
1568 {
1569         struct scst_tgt *tgt = (struct scst_tgt *)arg;
1570         unsigned long flags;
1571
1572         TRACE_RETRY("Retry timer expired (retry_cmds %d)", tgt->retry_cmds);
1573
1574         spin_lock_irqsave(&tgt->tgt_lock, flags);
1575         tgt->retry_timer_active = 0;
1576         spin_unlock_irqrestore(&tgt->tgt_lock, flags);
1577
1578         scst_check_retries(tgt);
1579
1580         TRACE_EXIT();
1581         return;
1582 }
1583
1584 struct scst_mgmt_cmd *scst_alloc_mgmt_cmd(gfp_t gfp_mask)
1585 {
1586         struct scst_mgmt_cmd *mcmd;
1587
1588         TRACE_ENTRY();
1589
1590         mcmd = mempool_alloc(scst_mgmt_mempool, gfp_mask);
1591         if (mcmd == NULL) {
1592                 PRINT_CRIT_ERROR("%s", "Allocation of management command "
1593                         "failed, some commands and their data could leak");
1594                 goto out;
1595         }
1596         memset(mcmd, 0, sizeof(*mcmd));
1597
1598 out:
1599         TRACE_EXIT();
1600         return mcmd;
1601 }
1602
1603 void scst_free_mgmt_cmd(struct scst_mgmt_cmd *mcmd)
1604 {
1605         unsigned long flags;
1606
1607         TRACE_ENTRY();
1608
1609         spin_lock_irqsave(&mcmd->sess->sess_list_lock, flags);
1610         atomic_dec(&mcmd->sess->sess_cmd_count);
1611         spin_unlock_irqrestore(&mcmd->sess->sess_list_lock, flags);
1612
1613         scst_sess_put(mcmd->sess);
1614
1615         if (mcmd->mcmd_tgt_dev != NULL)
1616                 __scst_put();
1617
1618         mempool_free(mcmd, scst_mgmt_mempool);
1619
1620         TRACE_EXIT();
1621         return;
1622 }
1623
1624 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 18)
1625 int scst_alloc_request(struct scst_cmd *cmd)
1626 {
1627         int res = 0;
1628         struct scsi_request *req;
1629         int gm = scst_cmd_atomic(cmd) ? GFP_ATOMIC : GFP_KERNEL;
1630
1631         TRACE_ENTRY();
1632
1633         /* cmd->dev->scsi_dev must be non-NULL here */
1634         req = scsi_allocate_request(cmd->dev->scsi_dev, gm);
1635         if (req == NULL) {
1636                 TRACE(TRACE_OUT_OF_MEM, "%s",
1637                       "Allocation of scsi_request failed");
1638                 res = -ENOMEM;
1639                 goto out;
1640         }
1641
1642         cmd->scsi_req = req;
1643
1644         memcpy(req->sr_cmnd, cmd->cdb, cmd->cdb_len);
1645         req->sr_cmd_len = cmd->cdb_len;
1646         req->sr_data_direction = cmd->data_direction;
1647         req->sr_use_sg = cmd->sg_cnt;
1648         req->sr_bufflen = cmd->bufflen;
1649         req->sr_buffer = cmd->sg;
1650         req->sr_request->rq_disk = cmd->dev->rq_disk;
1651         req->sr_sense_buffer[0] = 0;
1652
1653         cmd->scsi_req->upper_private_data = cmd;
1654
1655 out:
1656         TRACE_EXIT();
1657         return res;
1658 }
1659
1660 void scst_release_request(struct scst_cmd *cmd)
1661 {
1662         scsi_release_request(cmd->scsi_req);
1663         cmd->scsi_req = NULL;
1664 }
1665 #endif
1666
1667 int scst_alloc_space(struct scst_cmd *cmd)
1668 {
1669         gfp_t gfp_mask;
1670         int res = -ENOMEM;
1671         int atomic = scst_cmd_atomic(cmd);
1672         int flags;
1673         struct scst_tgt_dev *tgt_dev = cmd->tgt_dev;
1674
1675         TRACE_ENTRY();
1676
1677         gfp_mask = tgt_dev->gfp_mask | (atomic ? GFP_ATOMIC : GFP_KERNEL);
1678
1679         flags = atomic ? SCST_POOL_NO_ALLOC_ON_CACHE_MISS : 0;
1680         if (cmd->no_sgv)
1681                 flags |= SCST_POOL_ALLOC_NO_CACHED;
1682
1683         cmd->sg = sgv_pool_alloc(tgt_dev->pool, cmd->bufflen, gfp_mask, flags,
1684                         &cmd->sg_cnt, &cmd->sgv, &cmd->dev->dev_mem_lim, NULL);
1685         if (cmd->sg == NULL)
1686                 goto out;
1687
1688         if (unlikely(cmd->sg_cnt > tgt_dev->max_sg_cnt)) {
1689                 static int ll;
1690                 if (ll < 10) {
1691                         PRINT_INFO("Unable to complete command due to "
1692                                 "SG IO count limitation (requested %d, "
1693                                 "available %d, tgt lim %d)", cmd->sg_cnt,
1694                                 tgt_dev->max_sg_cnt, cmd->tgt->sg_tablesize);
1695                         ll++;
1696                 }
1697                 goto out_sg_free;
1698         }
1699
1700         res = 0;
1701
1702 out:
1703         TRACE_EXIT();
1704         return res;
1705
1706 out_sg_free:
1707         sgv_pool_free(cmd->sgv, &cmd->dev->dev_mem_lim);
1708         cmd->sgv = NULL;
1709         cmd->sg = NULL;
1710         cmd->sg_cnt = 0;
1711         goto out;
1712 }
1713
1714 static void scst_release_space(struct scst_cmd *cmd)
1715 {
1716         TRACE_ENTRY();
1717
1718         if (cmd->sgv == NULL)
1719                 goto out;
1720
1721         if (cmd->tgt_data_buf_alloced || cmd->dh_data_buf_alloced) {
1722                 TRACE_MEM("%s", "*data_buf_alloced set, returning");
1723                 goto out;
1724         }
1725
1726         sgv_pool_free(cmd->sgv, &cmd->dev->dev_mem_lim);
1727
1728         cmd->sgv = NULL;
1729         cmd->sg_cnt = 0;
1730         cmd->sg = NULL;
1731         cmd->bufflen = 0;
1732         cmd->data_len = 0;
1733
1734 out:
1735         TRACE_EXIT();
1736         return;
1737 }
1738
1739 void scst_copy_sg(struct scst_cmd *cmd, enum scst_sg_copy_dir copy_dir)
1740 {
1741         struct scatterlist *src_sg, *dst_sg;
1742         unsigned int src_sg_cnt, src_len, dst_len, src_offs, dst_offs;
1743         struct page *src, *dst;
1744         unsigned int s, d, to_copy;
1745
1746         TRACE_ENTRY();
1747
1748         if (copy_dir == SCST_SG_COPY_FROM_TARGET) {
1749                 src_sg = cmd->tgt_sg;
1750                 src_sg_cnt = cmd->tgt_sg_cnt;
1751                 dst_sg = cmd->sg;
1752                 to_copy = cmd->bufflen;
1753         } else {
1754                 src_sg = cmd->sg;
1755                 src_sg_cnt = cmd->sg_cnt;
1756                 dst_sg = cmd->tgt_sg;
1757                 to_copy = cmd->resp_data_len;
1758         }
1759
1760         TRACE_MEM("cmd %p, copy_dir %d, src_sg %p, src_sg_cnt %d, dst_sg %p, "
1761                 "to_copy %d", cmd, copy_dir, src_sg, src_sg_cnt, dst_sg,
1762                 to_copy);
1763
1764         dst = sg_page(dst_sg);
1765         dst_len = dst_sg->length;
1766         dst_offs = dst_sg->offset;
1767
1768         s = 0;
1769         d = 0;
1770         src_offs = 0;
1771         while (s < src_sg_cnt) {
1772                 src = sg_page(&src_sg[s]);
1773                 src_len = src_sg[s].length;
1774                 src_offs += src_sg[s].offset;
1775
1776                 do {
1777                         unsigned int n;
1778
1779                         /*
1780                          * Himem pages are not allowed here, see the
1781                          * corresponding #warning in scst_main.c. Correct
1782                          * your target driver or dev handler to not alloc
1783                          * such pages!
1784                          */
1785                         EXTRACHECKS_BUG_ON(PageHighMem(dst) ||
1786                                            PageHighMem(src));
1787
1788                         TRACE_MEM("cmd %p, to_copy %d, src %p, src_len %d, "
1789                                 "src_offs %d, dst %p, dst_len %d, dst_offs %d",
1790                                 cmd, to_copy, src, src_len, src_offs, dst,
1791                                 dst_len, dst_offs);
1792
1793                         if ((src_offs == 0) && (dst_offs == 0) &&
1794                             (src_len >= PAGE_SIZE) && (dst_len >= PAGE_SIZE)) {
1795                                 copy_page(page_address(dst), page_address(src));
1796                                 n = PAGE_SIZE;
1797                         } else {
1798                                 n = min(PAGE_SIZE - dst_offs,
1799                                         PAGE_SIZE - src_offs);
1800                                 n = min(n, src_len);
1801                                 n = min(n, dst_len);
1802                                 memcpy(page_address(dst) + dst_offs,
1803                                        page_address(src) + src_offs, n);
1804                                 dst_offs -= min(n, dst_offs);
1805                                 src_offs -= min(n, src_offs);
1806                         }
1807
1808                         TRACE_MEM("cmd %p, n %d, s %d", cmd, n, s);
1809
1810                         to_copy -= n;
1811                         if (to_copy <= 0)
1812                                 goto out;
1813
1814                         src_len -= n;
1815                         dst_len -= n;
1816                         if (dst_len == 0) {
1817                                 d++;
1818                                 dst = sg_page(&dst_sg[d]);
1819                                 dst_len = dst_sg[d].length;
1820                                 dst_offs += dst_sg[d].offset;
1821                         }
1822                 } while (src_len > 0);
1823
1824                 s++;
1825         }
1826
1827 out:
1828         TRACE_EXIT();
1829         return;
1830 }
1831
1832 static const int SCST_CDB_LENGTH[8] = { 6, 10, 10, -1, 16, 12, -1, -1 };
1833
1834 #define SCST_CDB_GROUP(opcode)   ((opcode >> 5) & 0x7)
1835 #define SCST_GET_CDB_LEN(opcode) SCST_CDB_LENGTH[SCST_CDB_GROUP(opcode)]
1836
1837 int scst_get_cdb_len(const uint8_t *cdb)
1838 {
1839         return SCST_GET_CDB_LEN(cdb[0]);
1840 }
1841
1842 /* get_trans_len_x extract x bytes from cdb as length starting from off */
1843
1844 /* for special commands */
1845 static int get_trans_len_block_limit(struct scst_cmd *cmd, uint8_t off)
1846 {
1847         cmd->bufflen = 6;
1848         return 0;
1849 }
1850
1851 static int get_trans_len_read_capacity(struct scst_cmd *cmd, uint8_t off)
1852 {
1853         cmd->bufflen = READ_CAP_LEN;
1854         return 0;
1855 }
1856
1857 static int get_trans_len_single(struct scst_cmd *cmd, uint8_t off)
1858 {
1859         cmd->bufflen = 1;
1860         return 0;
1861 }
1862
1863 static int get_trans_len_read_pos(struct scst_cmd *cmd, uint8_t off)
1864 {
1865         uint8_t *p = (uint8_t *)cmd->cdb + off;
1866         int res = 0;
1867
1868         cmd->bufflen = 0;
1869         cmd->bufflen |= ((u32)p[0]) << 8;
1870         cmd->bufflen |= ((u32)p[1]);
1871
1872         switch (cmd->cdb[1] & 0x1f) {
1873         case 0:
1874         case 1:
1875         case 6:
1876                 if (cmd->bufflen != 0) {
1877                         PRINT_ERROR("READ POSITION: Invalid non-zero (%d) "
1878                                 "allocation length for service action %x",
1879                                 cmd->bufflen, cmd->cdb[1] & 0x1f);
1880                         goto out_inval;
1881                 }
1882                 break;
1883         }
1884
1885         switch (cmd->cdb[1] & 0x1f) {
1886         case 0:
1887         case 1:
1888                 cmd->bufflen = 20;
1889                 break;
1890         case 6:
1891                 cmd->bufflen = 32;
1892                 break;
1893         case 8:
1894                 cmd->bufflen = max(28, cmd->bufflen);
1895                 break;
1896         default:
1897                 PRINT_ERROR("READ POSITION: Invalid service action %x",
1898                         cmd->cdb[1] & 0x1f);
1899                 goto out_inval;
1900         }
1901
1902 out:
1903         return res;
1904
1905 out_inval:
1906         scst_set_cmd_error(cmd,
1907                 SCST_LOAD_SENSE(scst_sense_invalid_field_in_cdb));
1908         res = 1;
1909         goto out;
1910 }
1911
1912 static int get_trans_len_1(struct scst_cmd *cmd, uint8_t off)
1913 {
1914         cmd->bufflen = (u32)cmd->cdb[off];
1915         return 0;
1916 }
1917
1918 static int get_trans_len_1_256(struct scst_cmd *cmd, uint8_t off)
1919 {
1920         cmd->bufflen = (u32)cmd->cdb[off];
1921         if (cmd->bufflen == 0)
1922                 cmd->bufflen = 256;
1923         return 0;
1924 }
1925
1926 static int get_trans_len_2(struct scst_cmd *cmd, uint8_t off)
1927 {
1928         const uint8_t *p = cmd->cdb + off;
1929
1930         cmd->bufflen = 0;
1931         cmd->bufflen |= ((u32)p[0]) << 8;
1932         cmd->bufflen |= ((u32)p[1]);
1933
1934         return 0;
1935 }
1936
1937 static int get_trans_len_3(struct scst_cmd *cmd, uint8_t off)
1938 {
1939         const uint8_t *p = cmd->cdb + off;
1940
1941         cmd->bufflen = 0;
1942         cmd->bufflen |= ((u32)p[0]) << 16;
1943         cmd->bufflen |= ((u32)p[1]) << 8;
1944         cmd->bufflen |= ((u32)p[2]);
1945
1946         return 0;
1947 }
1948
1949 static int get_trans_len_4(struct scst_cmd *cmd, uint8_t off)
1950 {
1951         const uint8_t *p = cmd->cdb + off;
1952
1953         cmd->bufflen = 0;
1954         cmd->bufflen |= ((u32)p[0]) << 24;
1955         cmd->bufflen |= ((u32)p[1]) << 16;
1956         cmd->bufflen |= ((u32)p[2]) << 8;
1957         cmd->bufflen |= ((u32)p[3]);
1958
1959         return 0;
1960 }
1961
1962 static int get_trans_len_none(struct scst_cmd *cmd, uint8_t off)
1963 {
1964         cmd->bufflen = 0;
1965         return 0;
1966 }
1967
1968 int scst_get_cdb_info(struct scst_cmd *cmd)
1969 {
1970         int dev_type = cmd->dev->handler->type;
1971         int i, res = 0;
1972         uint8_t op;
1973         const struct scst_sdbops *ptr = NULL;
1974
1975         TRACE_ENTRY();
1976
1977         op = cmd->cdb[0];       /* get clear opcode */
1978
1979         TRACE_DBG("opcode=%02x, cdblen=%d bytes, tblsize=%d, "
1980                 "dev_type=%d", op, SCST_GET_CDB_LEN(op), SCST_CDB_TBL_SIZE,
1981                 dev_type);
1982
1983         i = scst_scsi_op_list[op];
1984         while (i < SCST_CDB_TBL_SIZE && scst_scsi_op_table[i].ops == op) {
1985                 if (scst_scsi_op_table[i].devkey[dev_type] != SCST_CDB_NOTSUPP) {
1986                         ptr = &scst_scsi_op_table[i];
1987                         TRACE_DBG("op = 0x%02x+'%c%c%c%c%c%c%c%c%c%c'+<%s>",
1988                               ptr->ops, ptr->devkey[0], /* disk     */
1989                               ptr->devkey[1],   /* tape     */
1990                               ptr->devkey[2],   /* printer */
1991                               ptr->devkey[3],   /* cpu      */
1992                               ptr->devkey[4],   /* cdr      */
1993                               ptr->devkey[5],   /* cdrom    */
1994                               ptr->devkey[6],   /* scanner */
1995                               ptr->devkey[7],   /* worm     */
1996                               ptr->devkey[8],   /* changer */
1997                               ptr->devkey[9],   /* commdev */
1998                               ptr->op_name);
1999                         TRACE_DBG("direction=%d flags=%d off=%d",
2000                               ptr->direction,
2001                               ptr->flags,
2002                               ptr->off);
2003                         break;
2004                 }
2005                 i++;
2006         }
2007
2008         if (ptr == NULL) {
2009                 /* opcode not found or now not used !!! */
2010                 TRACE(TRACE_SCSI, "Unknown opcode 0x%x for type %d", op,
2011                       dev_type);
2012                 res = -1;
2013                 cmd->op_flags = SCST_INFO_INVALID;
2014                 goto out;
2015         }
2016
2017         cmd->cdb_len = SCST_GET_CDB_LEN(op);
2018         cmd->op_name = ptr->op_name;
2019         cmd->data_direction = ptr->direction;
2020         cmd->op_flags = ptr->flags;
2021         res = (*ptr->get_trans_len)(cmd, ptr->off);
2022
2023         if (cmd->bufflen == 0) {
2024                 /*
2025                  * According to SPC bufflen 0 for data transfer commands isn't
2026                  * an error, so we need to fix the transfer direction.
2027                  */
2028                 cmd->data_direction = SCST_DATA_NONE;
2029         }
2030
2031 out:
2032         TRACE_EXIT();
2033         return res;
2034 }
2035 EXPORT_SYMBOL(scst_get_cdb_info);
2036
2037 /*
2038  * Routine to extract a lun number from an 8-byte LUN structure
2039  * in network byte order (BE).
2040  * (see SAM-2, Section 4.12.3 page 40)
2041  * Supports 2 types of lun unpacking: peripheral and logical unit.
2042  */
2043 uint64_t scst_unpack_lun(const uint8_t *lun, int len)
2044 {
2045         uint64_t res = NO_SUCH_LUN;
2046         int address_method;
2047
2048         TRACE_ENTRY();
2049
2050         TRACE_BUFF_FLAG(TRACE_DEBUG, "Raw LUN", lun, len);
2051
2052         if (unlikely(len < 2)) {
2053                 PRINT_ERROR("Illegal lun length %d, expected 2 bytes or "
2054                         "more", len);
2055                 goto out;
2056         }
2057
2058         if (len > 2) {
2059                 switch (len) {
2060                 case 8:
2061                         if ((*((uint64_t *)lun) &
2062                           __constant_cpu_to_be64(0x0000FFFFFFFFFFFFLL)) != 0)
2063                                 goto out_err;
2064                         break;
2065                 case 4:
2066                         if (*((uint16_t *)&lun[2]) != 0)
2067                                 goto out_err;
2068                         break;
2069                 case 6:
2070                         if (*((uint32_t *)&lun[2]) != 0)
2071                                 goto out_err;
2072                         break;
2073                 default:
2074                         goto out_err;
2075                 }
2076         }
2077
2078         address_method = (*lun) >> 6;   /* high 2 bits of byte 0 */
2079         switch (address_method) {
2080         case 0: /* peripheral device addressing method */
2081 #if 0
2082                 if (*lun) {
2083                         PRINT_ERROR("Illegal BUS INDENTIFIER in LUN "
2084                              "peripheral device addressing method 0x%02x, "
2085                              "expected 0", *lun);
2086                         break;
2087                 }
2088                 res = *(lun + 1);
2089                 break;
2090 #else
2091                 /*
2092                  * Looks like it's legal to use it as flat space addressing
2093                  * method as well
2094                  */
2095
2096                 /* go through */
2097 #endif
2098
2099         case 1: /* flat space addressing method */
2100                 res = *(lun + 1) | (((*lun) & 0x3f) << 8);
2101                 break;
2102
2103         case 2: /* logical unit addressing method */
2104                 if (*lun & 0x3f) {
2105                         PRINT_ERROR("Illegal BUS NUMBER in LUN logical unit "
2106                                     "addressing method 0x%02x, expected 0",
2107                                     *lun & 0x3f);
2108                         break;
2109                 }
2110                 if (*(lun + 1) & 0xe0) {
2111                         PRINT_ERROR("Illegal TARGET in LUN logical unit "
2112                                     "addressing method 0x%02x, expected 0",
2113                                     (*(lun + 1) & 0xf8) >> 5);
2114                         break;
2115                 }
2116                 res = *(lun + 1) & 0x1f;
2117                 break;
2118
2119         case 3: /* extended logical unit addressing method */
2120         default:
2121                 PRINT_ERROR("Unimplemented LUN addressing method %u",
2122                             address_method);
2123                 break;
2124         }
2125
2126 out:
2127         TRACE_EXIT_RES((int)res);
2128         return res;
2129
2130 out_err:
2131         PRINT_ERROR("%s", "Multi-level LUN unimplemented");
2132         goto out;
2133 }
2134
2135 int scst_calc_block_shift(int sector_size)
2136 {
2137         int block_shift = 0;
2138         int t;
2139
2140         if (sector_size == 0)
2141                 sector_size = 512;
2142
2143         t = sector_size;
2144         while (1) {
2145                 if ((t & 1) != 0)
2146                         break;
2147                 t >>= 1;
2148                 block_shift++;
2149         }
2150         if (block_shift < 9) {
2151                 PRINT_ERROR("Wrong sector size %d", sector_size);
2152                 block_shift = -1;
2153         }
2154
2155         TRACE_EXIT_RES(block_shift);
2156         return block_shift;
2157 }
2158 EXPORT_SYMBOL(scst_calc_block_shift);
2159
2160 int scst_sbc_generic_parse(struct scst_cmd *cmd,
2161         int (*get_block_shift)(struct scst_cmd *cmd))
2162 {
2163         int res = 0;
2164
2165         TRACE_ENTRY();
2166
2167         /*
2168          * SCST sets good defaults for cmd->data_direction and cmd->bufflen,
2169          * therefore change them only if necessary
2170          */
2171
2172         TRACE_DBG("op_name <%s> direct %d flags %d transfer_len %d",
2173               cmd->op_name, cmd->data_direction, cmd->op_flags, cmd->bufflen);
2174
2175         switch (cmd->cdb[0]) {
2176         case SERVICE_ACTION_IN:
2177                 if ((cmd->cdb[1] & 0x1f) == SAI_READ_CAPACITY_16) {
2178                         cmd->bufflen = READ_CAP16_LEN;
2179                         cmd->data_direction = SCST_DATA_READ;
2180                 }
2181                 break;
2182         case VERIFY_6:
2183         case VERIFY:
2184         case VERIFY_12:
2185         case VERIFY_16:
2186                 if ((cmd->cdb[1] & BYTCHK) == 0) {
2187                         cmd->data_len = cmd->bufflen << get_block_shift(cmd);
2188                         cmd->bufflen = 0;
2189                         goto set_timeout;
2190                 } else
2191                         cmd->data_len = 0;
2192                 break;
2193         default:
2194                 /* It's all good */
2195                 break;
2196         }
2197
2198         if (cmd->op_flags & SCST_TRANSFER_LEN_TYPE_FIXED) {
2199                 /*
2200                  * No need for locks here, since *_detach() can not be
2201                  * called, when there are existing commands.
2202                  */
2203                 cmd->bufflen = cmd->bufflen << get_block_shift(cmd);
2204         }
2205
2206 set_timeout:
2207         if ((cmd->op_flags & (SCST_SMALL_TIMEOUT | SCST_LONG_TIMEOUT)) == 0)
2208                 cmd->timeout = SCST_GENERIC_DISK_REG_TIMEOUT;
2209         else if (cmd->op_flags & SCST_SMALL_TIMEOUT)
2210                 cmd->timeout = SCST_GENERIC_DISK_SMALL_TIMEOUT;
2211         else if (cmd->op_flags & SCST_LONG_TIMEOUT)
2212                 cmd->timeout = SCST_GENERIC_DISK_LONG_TIMEOUT;
2213
2214         TRACE_DBG("res %d, bufflen %d, data_len %d, direct %d",
2215               res, cmd->bufflen, cmd->data_len, cmd->data_direction);
2216
2217         TRACE_EXIT_RES(res);
2218         return res;
2219 }
2220 EXPORT_SYMBOL(scst_sbc_generic_parse);
2221
2222 int scst_cdrom_generic_parse(struct scst_cmd *cmd,
2223         int (*get_block_shift)(struct scst_cmd *cmd))
2224 {
2225         int res = 0;
2226
2227         TRACE_ENTRY();
2228
2229         /*
2230          * SCST sets good defaults for cmd->data_direction and cmd->bufflen,
2231          * therefore change them only if necessary
2232          */
2233
2234         TRACE_DBG("op_name <%s> direct %d flags %d transfer_len %d",
2235               cmd->op_name, cmd->data_direction, cmd->op_flags, cmd->bufflen);
2236
2237         cmd->cdb[1] &= 0x1f;
2238
2239         switch (cmd->cdb[0]) {
2240         case VERIFY_6:
2241         case VERIFY:
2242         case VERIFY_12:
2243         case VERIFY_16:
2244                 if ((cmd->cdb[1] & BYTCHK) == 0) {
2245                         cmd->data_len = cmd->bufflen << get_block_shift(cmd);
2246                         cmd->bufflen = 0;
2247                         goto set_timeout;
2248                 }
2249                 break;
2250         default:
2251                 /* It's all good */
2252                 break;
2253         }
2254
2255         if (cmd->op_flags & SCST_TRANSFER_LEN_TYPE_FIXED)
2256                 cmd->bufflen = cmd->bufflen << get_block_shift(cmd);
2257
2258 set_timeout:
2259         if ((cmd->op_flags & (SCST_SMALL_TIMEOUT | SCST_LONG_TIMEOUT)) == 0)
2260                 cmd->timeout = SCST_GENERIC_CDROM_REG_TIMEOUT;
2261         else if (cmd->op_flags & SCST_SMALL_TIMEOUT)
2262                 cmd->timeout = SCST_GENERIC_CDROM_SMALL_TIMEOUT;
2263         else if (cmd->op_flags & SCST_LONG_TIMEOUT)
2264                 cmd->timeout = SCST_GENERIC_CDROM_LONG_TIMEOUT;
2265
2266         TRACE_DBG("res=%d, bufflen=%d, direct=%d", res, cmd->bufflen,
2267                 cmd->data_direction);
2268
2269         TRACE_EXIT();
2270         return res;
2271 }
2272 EXPORT_SYMBOL(scst_cdrom_generic_parse);
2273
2274 int scst_modisk_generic_parse(struct scst_cmd *cmd,
2275         int (*get_block_shift)(struct scst_cmd *cmd))
2276 {
2277         int res = 0;
2278
2279         TRACE_ENTRY();
2280
2281         /*
2282          * SCST sets good defaults for cmd->data_direction and cmd->bufflen,
2283          * therefore change them only if necessary
2284          */
2285
2286         TRACE_DBG("op_name <%s> direct %d flags %d transfer_len %d",
2287               cmd->op_name, cmd->data_direction, cmd->op_flags, cmd->bufflen);
2288
2289         cmd->cdb[1] &= 0x1f;
2290
2291         switch (cmd->cdb[0]) {
2292         case VERIFY_6:
2293         case VERIFY:
2294         case VERIFY_12:
2295         case VERIFY_16:
2296                 if ((cmd->cdb[1] & BYTCHK) == 0) {
2297                         cmd->data_len = cmd->bufflen << get_block_shift(cmd);
2298                         cmd->bufflen = 0;
2299                         goto set_timeout;
2300                 }
2301                 break;
2302         default:
2303                 /* It's all good */
2304                 break;
2305         }
2306
2307         if (cmd->op_flags & SCST_TRANSFER_LEN_TYPE_FIXED)
2308                 cmd->bufflen = cmd->bufflen << get_block_shift(cmd);
2309
2310 set_timeout:
2311         if ((cmd->op_flags & (SCST_SMALL_TIMEOUT | SCST_LONG_TIMEOUT)) == 0)
2312                 cmd->timeout = SCST_GENERIC_MODISK_REG_TIMEOUT;
2313         else if (cmd->op_flags & SCST_SMALL_TIMEOUT)
2314                 cmd->timeout = SCST_GENERIC_MODISK_SMALL_TIMEOUT;
2315         else if (cmd->op_flags & SCST_LONG_TIMEOUT)
2316                 cmd->timeout = SCST_GENERIC_MODISK_LONG_TIMEOUT;
2317
2318         TRACE_DBG("res=%d, bufflen=%d, direct=%d", res, cmd->bufflen,
2319                 cmd->data_direction);
2320
2321         TRACE_EXIT_RES(res);
2322         return res;
2323 }
2324 EXPORT_SYMBOL(scst_modisk_generic_parse);
2325
2326 int scst_tape_generic_parse(struct scst_cmd *cmd,
2327         int (*get_block_size)(struct scst_cmd *cmd))
2328 {
2329         int res = 0;
2330
2331         TRACE_ENTRY();
2332
2333         /*
2334          * SCST sets good defaults for cmd->data_direction and cmd->bufflen,
2335          * therefore change them only if necessary
2336          */
2337
2338         TRACE_DBG("op_name <%s> direct %d flags %d transfer_len %d",
2339               cmd->op_name, cmd->data_direction, cmd->op_flags, cmd->bufflen);
2340
2341         if (cmd->cdb[0] == READ_POSITION) {
2342                 int tclp = cmd->cdb[1] & 4;
2343                 int long_bit = cmd->cdb[1] & 2;
2344                 int bt = cmd->cdb[1] & 1;
2345
2346                 if ((tclp == long_bit) && (!bt || !long_bit)) {
2347                         cmd->bufflen =
2348                             tclp ? POSITION_LEN_LONG : POSITION_LEN_SHORT;
2349                         cmd->data_direction = SCST_DATA_READ;
2350                 } else {
2351                         cmd->bufflen = 0;
2352                         cmd->data_direction = SCST_DATA_NONE;
2353                 }
2354         }
2355
2356         if (cmd->op_flags & SCST_TRANSFER_LEN_TYPE_FIXED & cmd->cdb[1])
2357                 cmd->bufflen = cmd->bufflen * get_block_size(cmd);
2358
2359         if ((cmd->op_flags & (SCST_SMALL_TIMEOUT | SCST_LONG_TIMEOUT)) == 0)
2360                 cmd->timeout = SCST_GENERIC_TAPE_REG_TIMEOUT;
2361         else if (cmd->op_flags & SCST_SMALL_TIMEOUT)
2362                 cmd->timeout = SCST_GENERIC_TAPE_SMALL_TIMEOUT;
2363         else if (cmd->op_flags & SCST_LONG_TIMEOUT)
2364                 cmd->timeout = SCST_GENERIC_TAPE_LONG_TIMEOUT;
2365
2366         TRACE_EXIT_RES(res);
2367         return res;
2368 }
2369 EXPORT_SYMBOL(scst_tape_generic_parse);
2370
2371 static int scst_null_parse(struct scst_cmd *cmd)
2372 {
2373         int res = 0;
2374
2375         TRACE_ENTRY();
2376
2377         /*
2378          * SCST sets good defaults for cmd->data_direction and cmd->bufflen,
2379          * therefore change them only if necessary
2380          */
2381
2382         TRACE_DBG("op_name <%s> direct %d flags %d transfer_len %d",
2383               cmd->op_name, cmd->data_direction, cmd->op_flags, cmd->bufflen);
2384 #if 0
2385         switch (cmd->cdb[0]) {
2386         default:
2387                 /* It's all good */
2388                 break;
2389         }
2390 #endif
2391         TRACE_DBG("res %d bufflen %d direct %d",
2392               res, cmd->bufflen, cmd->data_direction);
2393
2394         TRACE_EXIT();
2395         return res;
2396 }
2397
2398 int scst_changer_generic_parse(struct scst_cmd *cmd,
2399         int (*nothing)(struct scst_cmd *cmd))
2400 {
2401         int res = scst_null_parse(cmd);
2402
2403         if (cmd->op_flags & SCST_LONG_TIMEOUT)
2404                 cmd->timeout = SCST_GENERIC_CHANGER_LONG_TIMEOUT;
2405         else
2406                 cmd->timeout = SCST_GENERIC_CHANGER_TIMEOUT;
2407
2408         return res;
2409 }
2410 EXPORT_SYMBOL(scst_changer_generic_parse);
2411
2412 int scst_processor_generic_parse(struct scst_cmd *cmd,
2413         int (*nothing)(struct scst_cmd *cmd))
2414 {
2415         int res = scst_null_parse(cmd);
2416
2417         if (cmd->op_flags & SCST_LONG_TIMEOUT)
2418                 cmd->timeout = SCST_GENERIC_PROCESSOR_LONG_TIMEOUT;
2419         else
2420                 cmd->timeout = SCST_GENERIC_PROCESSOR_TIMEOUT;
2421
2422         return res;
2423 }
2424 EXPORT_SYMBOL(scst_processor_generic_parse);
2425
2426 int scst_raid_generic_parse(struct scst_cmd *cmd,
2427         int (*nothing)(struct scst_cmd *cmd))
2428 {
2429         int res = scst_null_parse(cmd);
2430
2431         if (cmd->op_flags & SCST_LONG_TIMEOUT)
2432                 cmd->timeout = SCST_GENERIC_RAID_LONG_TIMEOUT;
2433         else
2434                 cmd->timeout = SCST_GENERIC_RAID_TIMEOUT;
2435
2436         return res;
2437 }
2438 EXPORT_SYMBOL(scst_raid_generic_parse);
2439
2440 int scst_block_generic_dev_done(struct scst_cmd *cmd,
2441         void (*set_block_shift)(struct scst_cmd *cmd, int block_shift))
2442 {
2443         int opcode = cmd->cdb[0];
2444         int status = cmd->status;
2445         int res = SCST_CMD_STATE_DEFAULT;
2446
2447         TRACE_ENTRY();
2448
2449         /*
2450          * SCST sets good defaults for cmd->is_send_status and
2451          * cmd->resp_data_len based on cmd->status and cmd->data_direction,
2452          * therefore change them only if necessary
2453          */
2454
2455         if ((status == SAM_STAT_GOOD) || (status == SAM_STAT_CONDITION_MET)) {
2456                 switch (opcode) {
2457                 case READ_CAPACITY:
2458                 {
2459                         /* Always keep track of disk capacity */
2460                         int buffer_size, sector_size, sh;
2461                         uint8_t *buffer;
2462
2463                         buffer_size = scst_get_buf_first(cmd, &buffer);
2464                         if (unlikely(buffer_size <= 0)) {
2465                                 if (buffer_size < 0) {
2466                                         PRINT_ERROR("%s: Unable to get the"
2467                                         " buffer (%d)", __func__, buffer_size);
2468                                 }
2469                                 goto out;
2470                         }
2471
2472                         sector_size =
2473                             ((buffer[4] << 24) | (buffer[5] << 16) |
2474                              (buffer[6] << 8) | (buffer[7] << 0));
2475                         scst_put_buf(cmd, buffer);
2476                         if (sector_size != 0)
2477                                 sh = scst_calc_block_shift(sector_size);
2478                         else
2479                                 sh = 0;
2480                         set_block_shift(cmd, sh);
2481                         TRACE_DBG("block_shift %d", sh);
2482                         break;
2483                 }
2484                 default:
2485                         /* It's all good */
2486                         break;
2487                 }
2488         }
2489
2490         TRACE_DBG("cmd->is_send_status=%x, cmd->resp_data_len=%d, "
2491               "res=%d", cmd->is_send_status, cmd->resp_data_len, res);
2492
2493 out:
2494         TRACE_EXIT_RES(res);
2495         return res;
2496 }
2497 EXPORT_SYMBOL(scst_block_generic_dev_done);
2498
2499 int scst_tape_generic_dev_done(struct scst_cmd *cmd,
2500         void (*set_block_size)(struct scst_cmd *cmd, int block_shift))
2501 {
2502         int opcode = cmd->cdb[0];
2503         int res = SCST_CMD_STATE_DEFAULT;
2504         int buffer_size, bs;
2505         uint8_t *buffer = NULL;
2506
2507         TRACE_ENTRY();
2508
2509         /*
2510          * SCST sets good defaults for cmd->is_send_status and
2511          * cmd->resp_data_len based on cmd->status and cmd->data_direction,
2512          * therefore change them only if necessary
2513          */
2514
2515         switch (opcode) {
2516         case MODE_SENSE:
2517         case MODE_SELECT:
2518                 buffer_size = scst_get_buf_first(cmd, &buffer);
2519                 if (unlikely(buffer_size <= 0)) {
2520                         if (buffer_size < 0) {
2521                                 PRINT_ERROR("%s: Unable to get the buffer (%d)",
2522                                         __func__, buffer_size);
2523                         }
2524                         goto out;
2525                 }
2526                 break;
2527         }
2528
2529         switch (opcode) {
2530         case MODE_SENSE:
2531                 TRACE_DBG("%s", "MODE_SENSE");
2532                 if ((cmd->cdb[2] & 0xC0) == 0) {
2533                         if (buffer[3] == 8) {
2534                                 bs = (buffer[9] << 16) |
2535                                     (buffer[10] << 8) | buffer[11];
2536                                 set_block_size(cmd, bs);
2537                         }
2538                 }
2539                 break;
2540         case MODE_SELECT:
2541                 TRACE_DBG("%s", "MODE_SELECT");
2542                 if (buffer[3] == 8) {
2543                         bs = (buffer[9] << 16) | (buffer[10] << 8) |
2544                             (buffer[11]);
2545                         set_block_size(cmd, bs);
2546                 }
2547                 break;
2548         default:
2549                 /* It's all good */
2550                 break;
2551         }
2552
2553         switch (opcode) {
2554         case MODE_SENSE:
2555         case MODE_SELECT:
2556                 scst_put_buf(cmd, buffer);
2557                 break;
2558         }
2559
2560 out:
2561         TRACE_EXIT_RES(res);
2562         return res;
2563 }
2564 EXPORT_SYMBOL(scst_tape_generic_dev_done);
2565
2566 static void scst_check_internal_sense(struct scst_device *dev, int result,
2567         uint8_t *sense, int sense_len)
2568 {
2569         TRACE_ENTRY();
2570
2571         if (host_byte(result) == DID_RESET) {
2572                 TRACE(TRACE_MGMT_MINOR, "%s", "DID_RESET received, triggering "
2573                         "reset UA");
2574                 scst_set_sense(sense, sense_len,
2575                         SCST_LOAD_SENSE(scst_sense_reset_UA));
2576                 scst_dev_check_set_UA(dev, NULL, sense, sense_len);
2577         } else if ((status_byte(result) == CHECK_CONDITION) &&
2578                    SCST_SENSE_VALID(sense) && scst_is_ua_sense(sense))
2579                 scst_dev_check_set_UA(dev, NULL, sense, sense_len);
2580
2581         TRACE_EXIT();
2582         return;
2583 }
2584
2585 int scst_obtain_device_parameters(struct scst_device *dev)
2586 {
2587         int res = 0, i;
2588         uint8_t cmd[16];
2589         uint8_t buffer[4+0x0A];
2590         uint8_t sense_buffer[SCST_SENSE_BUFFERSIZE];
2591
2592         TRACE_ENTRY();
2593
2594         EXTRACHECKS_BUG_ON(dev->scsi_dev == NULL);
2595
2596         for (i = 0; i < 5; i++) {
2597                 /* Get control mode page */
2598                 memset(cmd, 0, sizeof(cmd));
2599                 cmd[0] = MODE_SENSE;
2600                 cmd[1] = 8; /* DBD */
2601                 cmd[2] = 0x0A;
2602                 cmd[4] = sizeof(buffer);
2603
2604                 memset(buffer, 0, sizeof(buffer));
2605                 memset(sense_buffer, 0, sizeof(sense_buffer));
2606
2607                 TRACE(TRACE_SCSI, "%s", "Doing internal MODE_SENSE");
2608                 res = scsi_execute(dev->scsi_dev, cmd, SCST_DATA_READ, buffer,
2609                                 sizeof(buffer), sense_buffer, 15, 0, 0);
2610
2611                 TRACE_DBG("MODE_SENSE done: %x", res);
2612
2613                 if (scsi_status_is_good(res)) {
2614                         int q;
2615
2616                         PRINT_BUFF_FLAG(TRACE_SCSI,
2617                                 "Returned control mode page data",
2618                                 buffer, sizeof(buffer));
2619
2620                         dev->tst = buffer[4+2] >> 5;
2621                         q = buffer[4+3] >> 4;
2622                         if (q > SCST_CONTR_MODE_QUEUE_ALG_UNRESTRICTED_REORDER) {
2623                                 PRINT_ERROR("Too big QUEUE ALG %x, dev "
2624                                         "%d:%d:%d:%d", dev->queue_alg,
2625                                         dev->scsi_dev->host->host_no,
2626                                         dev->scsi_dev->channel,
2627                                         dev->scsi_dev->id, dev->scsi_dev->lun);
2628                         }
2629                         dev->queue_alg = q;
2630                         dev->swp = (buffer[4+4] & 0x8) >> 3;
2631                         dev->tas = (buffer[4+5] & 0x40) >> 6;
2632
2633                         /*
2634                          * Unfortunately, SCSI ML doesn't provide a way to
2635                          * specify commands task attribute, so we can rely on
2636                          * device's restricted reordering only.
2637                          */
2638                         dev->has_own_order_mgmt = !dev->queue_alg;
2639
2640                         TRACE(TRACE_SCSI|TRACE_MGMT_MINOR,
2641                                 "Device %d:%d:%d:%d: TST %x, "
2642                                 "QUEUE ALG %x, SWP %x, TAS %x, "
2643                                 "has_own_order_mgmt %d",
2644                                 dev->scsi_dev->host->host_no,
2645                                 dev->scsi_dev->channel, dev->scsi_dev->id,
2646                                 dev->scsi_dev->lun, dev->tst, dev->queue_alg,
2647                                 dev->swp, dev->tas, dev->has_own_order_mgmt);
2648
2649                         goto out;
2650                 } else {
2651 #if 0
2652                         if ((status_byte(res) == CHECK_CONDITION) &&
2653 #else
2654                         /*
2655                          * 3ware controller is buggy and returns CONDITION_GOOD
2656                          * instead of CHECK_CONDITION
2657                          */
2658                         if (
2659 #endif
2660                             SCST_SENSE_VALID(sense_buffer)) {
2661                                 if (sense_buffer[2] == ILLEGAL_REQUEST) {
2662                                         TRACE(TRACE_SCSI|TRACE_MGMT_MINOR,
2663                                                 "Device %d:%d:%d:%d doesn't"
2664                                                 " support control mode page,"
2665                                                 " using defaults: TST %x,"
2666                                                 " QUEUE ALG %x, SWP %x, TAS %x,"
2667                                                 " has_own_order_mgmt %d",
2668                                                 dev->scsi_dev->host->host_no,
2669                                                 dev->scsi_dev->channel,
2670                                                 dev->scsi_dev->id,
2671                                                 dev->scsi_dev->lun,
2672                                                 dev->tst,
2673                                                 dev->queue_alg,
2674                                                 dev->swp,
2675                                                 dev->tas,
2676                                                 dev->has_own_order_mgmt);
2677                                         res = 0;
2678                                         goto out;
2679                                 } else if (sense_buffer[2] == NOT_READY) {
2680                                         TRACE(TRACE_SCSI,
2681                                                 "Device %d:%d:%d:%d not ready",
2682                                                 dev->scsi_dev->host->host_no,
2683                                                 dev->scsi_dev->channel,
2684                                                 dev->scsi_dev->id,
2685                                                 dev->scsi_dev->lun);
2686                                         res = 0;
2687                                         goto out;
2688                                 }
2689                         } else {
2690                                 TRACE(TRACE_SCSI|TRACE_MGMT_MINOR,
2691                                         "Internal MODE SENSE to "
2692                                         "device %d:%d:%d:%d failed: %x",
2693                                         dev->scsi_dev->host->host_no,
2694                                         dev->scsi_dev->channel,
2695                                         dev->scsi_dev->id,
2696                                         dev->scsi_dev->lun, res);
2697                                 PRINT_BUFF_FLAG(TRACE_SCSI|TRACE_MGMT_MINOR,
2698                                         "MODE SENSE sense",
2699                                         sense_buffer, sizeof(sense_buffer));
2700                         }
2701                         scst_check_internal_sense(dev, res, sense_buffer,
2702                                         sizeof(sense_buffer));
2703                 }
2704         }
2705         res = -ENODEV;
2706
2707 out:
2708         TRACE_EXIT_RES(res);
2709         return res;
2710 }
2711 EXPORT_SYMBOL(scst_obtain_device_parameters);
2712
2713 /* Called under dev_lock and BH off */
2714 void scst_process_reset(struct scst_device *dev,
2715         struct scst_session *originator, struct scst_cmd *exclude_cmd,
2716         struct scst_mgmt_cmd *mcmd, bool setUA)
2717 {
2718         struct scst_tgt_dev *tgt_dev;
2719         struct scst_cmd *cmd, *tcmd;
2720
2721         TRACE_ENTRY();
2722
2723         /* Clear RESERVE'ation, if necessary */
2724         if (dev->dev_reserved) {
2725                 list_for_each_entry(tgt_dev, &dev->dev_tgt_dev_list,
2726                                     dev_tgt_dev_list_entry) {
2727                         TRACE(TRACE_MGMT_MINOR, "Clearing RESERVE'ation for "
2728                                 "tgt_dev lun %lld",
2729                                 (long long unsigned int)tgt_dev->lun);
2730                         clear_bit(SCST_TGT_DEV_RESERVED,
2731                                   &tgt_dev->tgt_dev_flags);
2732                 }
2733                 dev->dev_reserved = 0;
2734                 /*
2735                  * There is no need to send RELEASE, since the device is going
2736                  * to be resetted. Actually, since we can be in RESET TM
2737                  * function, it might be dangerous.
2738                  */
2739         }
2740
2741         dev->dev_double_ua_possible = 1;
2742
2743         list_for_each_entry(tgt_dev, &dev->dev_tgt_dev_list,
2744                 dev_tgt_dev_list_entry) {
2745                 struct scst_session *sess = tgt_dev->sess;
2746
2747                 spin_lock_bh(&tgt_dev->tgt_dev_lock);
2748                 scst_free_all_UA(tgt_dev);
2749                 spin_unlock_bh(&tgt_dev->tgt_dev_lock);
2750
2751                 spin_lock_irq(&sess->sess_list_lock);
2752
2753                 TRACE_DBG("Searching in search cmd list (sess=%p)", sess);
2754                 list_for_each_entry(cmd, &sess->search_cmd_list,
2755                                 search_cmd_list_entry) {
2756                         if (cmd == exclude_cmd)
2757                                 continue;
2758                         if ((cmd->tgt_dev == tgt_dev) ||
2759                             ((cmd->tgt_dev == NULL) &&
2760                              (cmd->lun == tgt_dev->lun))) {
2761                                 scst_abort_cmd(cmd, mcmd,
2762                                         (tgt_dev->sess != originator), 0);
2763                         }
2764                 }
2765                 spin_unlock_irq(&sess->sess_list_lock);
2766         }
2767
2768         list_for_each_entry_safe(cmd, tcmd, &dev->blocked_cmd_list,
2769                                 blocked_cmd_list_entry) {
2770                 if (test_bit(SCST_CMD_ABORTED, &cmd->cmd_flags)) {
2771                         list_del(&cmd->blocked_cmd_list_entry);
2772                         TRACE_MGMT_DBG("Adding aborted blocked cmd %p "
2773                                 "to active cmd list", cmd);
2774                         spin_lock_irq(&cmd->cmd_lists->cmd_list_lock);
2775                         list_add_tail(&cmd->cmd_list_entry,
2776                                 &cmd->cmd_lists->active_cmd_list);
2777                         wake_up(&cmd->cmd_lists->cmd_list_waitQ);
2778                         spin_unlock_irq(&cmd->cmd_lists->cmd_list_lock);
2779                 }
2780         }
2781
2782         if (setUA) {
2783                 /* BH already off */
2784                 spin_lock(&scst_temp_UA_lock);
2785                 scst_set_sense(scst_temp_UA, sizeof(scst_temp_UA),
2786                         SCST_LOAD_SENSE(scst_sense_reset_UA));
2787                 scst_dev_check_set_local_UA(dev, exclude_cmd, scst_temp_UA,
2788                         sizeof(scst_temp_UA));
2789                 spin_unlock(&scst_temp_UA_lock);
2790         }
2791
2792         TRACE_EXIT();
2793         return;
2794 }
2795
2796 int scst_set_pending_UA(struct scst_cmd *cmd)
2797 {
2798         int res = 0;
2799         struct scst_tgt_dev_UA *UA_entry;
2800
2801         TRACE_ENTRY();
2802
2803         TRACE(TRACE_MGMT_MINOR, "Setting pending UA cmd %p", cmd);
2804
2805         spin_lock_bh(&cmd->tgt_dev->tgt_dev_lock);
2806
2807         /* UA list could be cleared behind us, so retest */
2808         if (list_empty(&cmd->tgt_dev->UA_list)) {
2809                 TRACE_DBG("%s",
2810                       "SCST_TGT_DEV_UA_PENDING set, but UA_list empty");
2811                 res = -1;
2812                 goto out_unlock;
2813         }
2814
2815         UA_entry = list_entry(cmd->tgt_dev->UA_list.next, typeof(*UA_entry),
2816                               UA_list_entry);
2817
2818         TRACE_DBG("next %p UA_entry %p",
2819               cmd->tgt_dev->UA_list.next, UA_entry);
2820
2821         scst_set_cmd_error_sense(cmd, UA_entry->UA_sense_buffer,
2822                 sizeof(UA_entry->UA_sense_buffer));
2823
2824         cmd->ua_ignore = 1;
2825
2826         list_del(&UA_entry->UA_list_entry);
2827
2828         mempool_free(UA_entry, scst_ua_mempool);
2829
2830         if (list_empty(&cmd->tgt_dev->UA_list)) {
2831                 clear_bit(SCST_TGT_DEV_UA_PENDING,
2832                           &cmd->tgt_dev->tgt_dev_flags);
2833         }
2834
2835         spin_unlock_bh(&cmd->tgt_dev->tgt_dev_lock);
2836
2837 out:
2838         TRACE_EXIT_RES(res);
2839         return res;
2840
2841 out_unlock:
2842         spin_unlock_bh(&cmd->tgt_dev->tgt_dev_lock);
2843         goto out;
2844 }
2845
2846 /* Called under tgt_dev_lock and BH off */
2847 static void scst_alloc_set_UA(struct scst_tgt_dev *tgt_dev,
2848         const uint8_t *sense, int sense_len, int head)
2849 {
2850         struct scst_tgt_dev_UA *UA_entry = NULL;
2851
2852         TRACE_ENTRY();
2853
2854         UA_entry = mempool_alloc(scst_ua_mempool, GFP_ATOMIC);
2855         if (UA_entry == NULL) {
2856                 PRINT_CRIT_ERROR("%s", "UNIT ATTENTION memory "
2857                      "allocation failed. The UNIT ATTENTION "
2858                      "on some sessions will be missed");
2859                 PRINT_BUFFER("Lost UA", sense, sense_len);
2860                 goto out;
2861         }
2862         memset(UA_entry, 0, sizeof(*UA_entry));
2863
2864         if (sense_len > (int)sizeof(UA_entry->UA_sense_buffer))
2865                 sense_len = sizeof(UA_entry->UA_sense_buffer);
2866         memcpy(UA_entry->UA_sense_buffer, sense, sense_len);
2867
2868         set_bit(SCST_TGT_DEV_UA_PENDING, &tgt_dev->tgt_dev_flags);
2869
2870         TRACE_MGMT_DBG("Adding new UA to tgt_dev %p", tgt_dev);
2871
2872         if (head)
2873                 list_add(&UA_entry->UA_list_entry, &tgt_dev->UA_list);
2874         else
2875                 list_add_tail(&UA_entry->UA_list_entry, &tgt_dev->UA_list);
2876
2877 out:
2878         TRACE_EXIT();
2879         return;
2880 }
2881
2882 void scst_check_set_UA(struct scst_tgt_dev *tgt_dev,
2883         const uint8_t *sense, int sense_len, int head)
2884 {
2885         int skip_UA = 0;
2886         struct scst_tgt_dev_UA *UA_entry_tmp;
2887
2888         TRACE_ENTRY();
2889
2890         spin_lock_bh(&tgt_dev->tgt_dev_lock);
2891
2892         list_for_each_entry(UA_entry_tmp, &tgt_dev->UA_list,
2893                             UA_list_entry) {
2894                 if (memcmp(sense, UA_entry_tmp->UA_sense_buffer,
2895                            sense_len) == 0) {
2896                         TRACE_MGMT_DBG("%s", "UA already exists");
2897                         skip_UA = 1;
2898                         break;
2899                 }
2900         }
2901
2902         if (skip_UA == 0)
2903                 scst_alloc_set_UA(tgt_dev, sense, sense_len, head);
2904
2905         spin_unlock_bh(&tgt_dev->tgt_dev_lock);
2906
2907         TRACE_EXIT();
2908         return;
2909 }
2910
2911 /* Called under dev_lock and BH off */
2912 void scst_dev_check_set_local_UA(struct scst_device *dev,
2913         struct scst_cmd *exclude, const uint8_t *sense, int sense_len)
2914 {
2915         struct scst_tgt_dev *tgt_dev, *exclude_tgt_dev = NULL;
2916
2917         TRACE_ENTRY();
2918
2919         if (exclude != NULL)
2920                 exclude_tgt_dev = exclude->tgt_dev;
2921
2922         list_for_each_entry(tgt_dev, &dev->dev_tgt_dev_list,
2923                         dev_tgt_dev_list_entry) {
2924                 if (tgt_dev != exclude_tgt_dev)
2925                         scst_check_set_UA(tgt_dev, sense, sense_len, 0);
2926         }
2927
2928         TRACE_EXIT();
2929         return;
2930 }
2931
2932 /* Called under dev_lock and BH off */
2933 void __scst_dev_check_set_UA(struct scst_device *dev,
2934         struct scst_cmd *exclude, const uint8_t *sense, int sense_len)
2935 {
2936         TRACE_ENTRY();
2937
2938         TRACE(TRACE_MGMT_MINOR, "Processing UA dev %p", dev);
2939
2940         /* Check for reset UA */
2941         if (sense[12] == SCST_SENSE_ASC_UA_RESET)
2942                 scst_process_reset(dev,
2943                                    (exclude != NULL) ? exclude->sess : NULL,
2944                                    exclude, NULL, false);
2945
2946         scst_dev_check_set_local_UA(dev, exclude, sense, sense_len);
2947
2948         TRACE_EXIT();
2949         return;
2950 }
2951
2952 /* Called under tgt_dev_lock or when tgt_dev is unused */
2953 static void scst_free_all_UA(struct scst_tgt_dev *tgt_dev)
2954 {
2955         struct scst_tgt_dev_UA *UA_entry, *t;
2956
2957         TRACE_ENTRY();
2958
2959         list_for_each_entry_safe(UA_entry, t,
2960                                  &tgt_dev->UA_list, UA_list_entry) {
2961                 TRACE_MGMT_DBG("Clearing UA for tgt_dev lun %lld",
2962                                (long long unsigned int)tgt_dev->lun);
2963                 list_del(&UA_entry->UA_list_entry);
2964                 kfree(UA_entry);
2965         }
2966         INIT_LIST_HEAD(&tgt_dev->UA_list);
2967         clear_bit(SCST_TGT_DEV_UA_PENDING, &tgt_dev->tgt_dev_flags);
2968
2969         TRACE_EXIT();
2970         return;
2971 }
2972
2973 /* No locks */
2974 struct scst_cmd *__scst_check_deferred_commands(struct scst_tgt_dev *tgt_dev)
2975 {
2976         struct scst_cmd *res = NULL, *cmd, *t;
2977         typeof(tgt_dev->expected_sn) expected_sn = tgt_dev->expected_sn;
2978
2979         spin_lock_irq(&tgt_dev->sn_lock);
2980
2981         if (unlikely(tgt_dev->hq_cmd_count != 0))
2982                 goto out_unlock;
2983
2984 restart:
2985         list_for_each_entry_safe(cmd, t, &tgt_dev->deferred_cmd_list,
2986                                 sn_cmd_list_entry) {
2987                 EXTRACHECKS_BUG_ON(cmd->queue_type ==
2988                         SCST_CMD_QUEUE_HEAD_OF_QUEUE);
2989                 if (cmd->sn == expected_sn) {
2990                         TRACE_SN("Deferred command %p (sn %ld, set %d) found",
2991                                 cmd, cmd->sn, cmd->sn_set);
2992                         tgt_dev->def_cmd_count--;
2993                         list_del(&cmd->sn_cmd_list_entry);
2994                         if (res == NULL)
2995                                 res = cmd;
2996                         else {
2997                                 spin_lock(&cmd->cmd_lists->cmd_list_lock);
2998                                 TRACE_SN("Adding cmd %p to active cmd list",
2999                                         cmd);
3000                                 list_add_tail(&cmd->cmd_list_entry,
3001                                         &cmd->cmd_lists->active_cmd_list);
3002                                 wake_up(&cmd->cmd_lists->cmd_list_waitQ);
3003                                 spin_unlock(&cmd->cmd_lists->cmd_list_lock);
3004                         }
3005                 }
3006         }
3007         if (res != NULL)
3008                 goto out_unlock;
3009
3010         list_for_each_entry(cmd, &tgt_dev->skipped_sn_list,
3011                                 sn_cmd_list_entry) {
3012                 EXTRACHECKS_BUG_ON(cmd->queue_type ==
3013                         SCST_CMD_QUEUE_HEAD_OF_QUEUE);
3014                 if (cmd->sn == expected_sn) {
3015                         atomic_t *slot = cmd->sn_slot;
3016                         /*
3017                          * !! At this point any pointer in cmd, except !!
3018                          * !! sn_slot and sn_cmd_list_entry, could be   !!
3019                          * !! already destroyed                         !!
3020                          */
3021                         TRACE_SN("cmd %p (tag %llu) with skipped sn %ld found",
3022                                  cmd,
3023                                  (long long unsigned int)cmd->tag,
3024                                  cmd->sn);
3025                         tgt_dev->def_cmd_count--;
3026                         list_del(&cmd->sn_cmd_list_entry);
3027                         spin_unlock_irq(&tgt_dev->sn_lock);
3028                         if (test_and_set_bit(SCST_CMD_CAN_BE_DESTROYED,
3029                                              &cmd->cmd_flags))
3030                                 scst_destroy_put_cmd(cmd);
3031                         scst_inc_expected_sn(tgt_dev, slot);
3032                         expected_sn = tgt_dev->expected_sn;
3033                         spin_lock_irq(&tgt_dev->sn_lock);
3034                         goto restart;
3035                 }
3036         }
3037
3038 out_unlock:
3039         spin_unlock_irq(&tgt_dev->sn_lock);
3040         return res;
3041 }
3042
3043 void scst_add_thr_data(struct scst_tgt_dev *tgt_dev,
3044         struct scst_thr_data_hdr *data,
3045         void (*free_fn) (struct scst_thr_data_hdr *data))
3046 {
3047         data->owner_thr = current;
3048         atomic_set(&data->ref, 1);
3049         EXTRACHECKS_BUG_ON(free_fn == NULL);
3050         data->free_fn = free_fn;
3051         spin_lock(&tgt_dev->thr_data_lock);
3052         list_add_tail(&data->thr_data_list_entry, &tgt_dev->thr_data_list);
3053         spin_unlock(&tgt_dev->thr_data_lock);
3054 }
3055 EXPORT_SYMBOL(scst_add_thr_data);
3056
3057 void scst_del_all_thr_data(struct scst_tgt_dev *tgt_dev)
3058 {
3059         spin_lock(&tgt_dev->thr_data_lock);
3060         while (!list_empty(&tgt_dev->thr_data_list)) {
3061                 struct scst_thr_data_hdr *d = list_entry(
3062                                 tgt_dev->thr_data_list.next, typeof(*d),
3063                                 thr_data_list_entry);
3064                 list_del(&d->thr_data_list_entry);
3065                 spin_unlock(&tgt_dev->thr_data_lock);
3066                 scst_thr_data_put(d);
3067                 spin_lock(&tgt_dev->thr_data_lock);
3068         }
3069         spin_unlock(&tgt_dev->thr_data_lock);
3070         return;
3071 }
3072 EXPORT_SYMBOL(scst_del_all_thr_data);
3073
3074 void scst_dev_del_all_thr_data(struct scst_device *dev)
3075 {
3076         struct scst_tgt_dev *tgt_dev;
3077
3078         TRACE_ENTRY();
3079
3080         mutex_lock(&scst_mutex);
3081
3082         list_for_each_entry(tgt_dev, &dev->dev_tgt_dev_list,
3083                                 dev_tgt_dev_list_entry) {
3084                 scst_del_all_thr_data(tgt_dev);
3085         }
3086
3087         mutex_unlock(&scst_mutex);
3088
3089         TRACE_EXIT();
3090         return;
3091 }
3092 EXPORT_SYMBOL(scst_dev_del_all_thr_data);
3093
3094 struct scst_thr_data_hdr *__scst_find_thr_data(struct scst_tgt_dev *tgt_dev,
3095         struct task_struct *tsk)
3096 {
3097         struct scst_thr_data_hdr *res = NULL, *d;
3098
3099         spin_lock(&tgt_dev->thr_data_lock);
3100         list_for_each_entry(d, &tgt_dev->thr_data_list, thr_data_list_entry) {
3101                 if (d->owner_thr == tsk) {
3102                         res = d;
3103                         scst_thr_data_get(res);
3104                         break;
3105                 }
3106         }
3107         spin_unlock(&tgt_dev->thr_data_lock);
3108         return res;
3109 }
3110 EXPORT_SYMBOL(__scst_find_thr_data);
3111
3112 /* dev_lock supposed to be held and BH disabled */
3113 void __scst_block_dev(struct scst_device *dev)
3114 {
3115         dev->block_count++;
3116         TRACE_MGMT_DBG("Device BLOCK(new %d), dev %p", dev->block_count, dev);
3117 }
3118
3119 /* No locks */
3120 static void scst_block_dev(struct scst_device *dev, int outstanding)
3121 {
3122         spin_lock_bh(&dev->dev_lock);
3123         __scst_block_dev(dev);
3124         spin_unlock_bh(&dev->dev_lock);
3125
3126         /*
3127          * Memory barrier is necessary here, because we need to read
3128          * on_dev_count in wait_event() below after we increased block_count.
3129          * Otherwise, we can miss wake up in scst_dec_on_dev_cmd().
3130          * We use the explicit barrier, because spin_unlock_bh() doesn't
3131          * provide the necessary memory barrier functionality.
3132          */
3133         smp_mb();
3134
3135         TRACE_MGMT_DBG("Waiting during blocking outstanding %d (on_dev_count "
3136                 "%d)", outstanding, atomic_read(&dev->on_dev_count));
3137         wait_event(dev->on_dev_waitQ,
3138                 atomic_read(&dev->on_dev_count) <= outstanding);
3139         TRACE_MGMT_DBG("%s", "wait_event() returned");
3140 }
3141
3142 /* No locks */
3143 void scst_block_dev_cmd(struct scst_cmd *cmd, int outstanding)
3144 {
3145         sBUG_ON(cmd->needs_unblocking);
3146
3147         cmd->needs_unblocking = 1;
3148         TRACE_MGMT_DBG("Needs unblocking cmd %p (tag %llu)",
3149                        cmd, (long long unsigned int)cmd->tag);
3150
3151         scst_block_dev(cmd->dev, outstanding);
3152 }
3153
3154 /* No locks */
3155 void scst_unblock_dev(struct scst_device *dev)
3156 {
3157         spin_lock_bh(&dev->dev_lock);
3158         TRACE_MGMT_DBG("Device UNBLOCK(new %d), dev %p",
3159                 dev->block_count-1, dev);
3160         if (--dev->block_count == 0)
3161                 scst_unblock_cmds(dev);
3162         spin_unlock_bh(&dev->dev_lock);
3163         sBUG_ON(dev->block_count < 0);
3164 }
3165
3166 /* No locks */
3167 void scst_unblock_dev_cmd(struct scst_cmd *cmd)
3168 {
3169         scst_unblock_dev(cmd->dev);
3170         cmd->needs_unblocking = 0;
3171 }
3172
3173 /* No locks */
3174 int scst_inc_on_dev_cmd(struct scst_cmd *cmd)
3175 {
3176         int res = 0;
3177         struct scst_device *dev = cmd->dev;
3178
3179         TRACE_ENTRY();
3180
3181         sBUG_ON(cmd->inc_blocking || cmd->dec_on_dev_needed);
3182
3183         atomic_inc(&dev->on_dev_count);
3184         cmd->dec_on_dev_needed = 1;
3185         TRACE_DBG("New on_dev_count %d", atomic_read(&dev->on_dev_count));
3186
3187         if (unlikely(cmd->internal) && (cmd->cdb[0] == REQUEST_SENSE)) {
3188                 /*
3189                  * The original command can already block the device, so
3190                  * REQUEST SENSE command should always pass.
3191                  */
3192                 goto out;
3193         }
3194
3195 #ifdef CONFIG_SCST_STRICT_SERIALIZING
3196         spin_lock_bh(&dev->dev_lock);
3197         if (unlikely(test_bit(SCST_CMD_ABORTED, &cmd->cmd_flags)))
3198                 goto out_unlock;
3199         if (dev->block_count > 0) {
3200                 scst_dec_on_dev_cmd(cmd);
3201                 TRACE_MGMT_DBG("Delaying cmd %p due to blocking or strict "
3202                         "serializing (tag %llu, dev %p)", cmd, cmd->tag, dev);
3203                 list_add_tail(&cmd->blocked_cmd_list_entry,
3204                               &dev->blocked_cmd_list);
3205                 res = 1;
3206         } else {
3207                 __scst_block_dev(dev);
3208                 cmd->inc_blocking = 1;
3209         }
3210         spin_unlock_bh(&dev->dev_lock);
3211         goto out;
3212 #else
3213 repeat:
3214         if (unlikely(dev->block_count > 0)) {
3215                 spin_lock_bh(&dev->dev_lock);
3216                 if (unlikely(test_bit(SCST_CMD_ABORTED, &cmd->cmd_flags)))
3217                         goto out_unlock;
3218                 if (dev->block_count > 0) {
3219                         scst_dec_on_dev_cmd(cmd);
3220                         TRACE_MGMT_DBG("Delaying cmd %p due to blocking "
3221                                 "(tag %llu, dev %p)", cmd,
3222                                 (long long unsigned int)cmd->tag, dev);
3223                         list_add_tail(&cmd->blocked_cmd_list_entry,
3224                                       &dev->blocked_cmd_list);
3225                         res = 1;
3226                         spin_unlock_bh(&dev->dev_lock);
3227                         goto out;
3228                 } else {
3229                         TRACE_MGMT_DBG("%s", "Somebody unblocked the device, "
3230                                 "continuing");
3231                 }
3232                 spin_unlock_bh(&dev->dev_lock);
3233         }
3234         if (unlikely(dev->dev_double_ua_possible)) {
3235                 spin_lock_bh(&dev->dev_lock);
3236                 if (dev->block_count == 0) {
3237                         TRACE_MGMT_DBG("cmd %p (tag %llu), blocking further "
3238                                 "cmds due to possible double reset UA (dev %p)",
3239                                 cmd, (long long unsigned int)cmd->tag, dev);
3240                         __scst_block_dev(dev);
3241                         cmd->inc_blocking = 1;
3242                 } else {
3243                         spin_unlock_bh(&dev->dev_lock);
3244                         TRACE_MGMT_DBG("Somebody blocked the device, "
3245                                 "repeating (count %d)", dev->block_count);
3246                         goto repeat;
3247                 }
3248                 spin_unlock_bh(&dev->dev_lock);
3249         }
3250 #endif
3251
3252 out:
3253         TRACE_EXIT_RES(res);
3254         return res;
3255
3256 out_unlock:
3257         spin_unlock_bh(&dev->dev_lock);
3258         goto out;
3259 }
3260
3261 /* Called under dev_lock */
3262 static void scst_unblock_cmds(struct scst_device *dev)
3263 {
3264 #ifdef CONFIG_SCST_STRICT_SERIALIZING
3265         struct scst_cmd *cmd, *t;
3266         unsigned long flags;
3267
3268         TRACE_ENTRY();
3269
3270         local_irq_save(flags);
3271         list_for_each_entry_safe(cmd, t, &dev->blocked_cmd_list,
3272                                  blocked_cmd_list_entry) {
3273                 int brk = 0;
3274                 /*
3275                  * Since only one cmd per time is being executed, expected_sn
3276                  * can't change behind us, if the corresponding cmd is in
3277                  * blocked_cmd_list, but we could be called before
3278                  * scst_inc_expected_sn().
3279                  *
3280                  * For HQ commands SN is not set.
3281                  */
3282                 if (likely(!cmd->internal && cmd->sn_set)) {
3283                         typeof(cmd->tgt_dev->expected_sn) expected_sn;
3284                         if (cmd->tgt_dev == NULL)
3285                                 sBUG();
3286                         expected_sn = cmd->tgt_dev->expected_sn;
3287                         if (cmd->sn == expected_sn)
3288                                 brk = 1;
3289                         else if (cmd->sn != (expected_sn+1))
3290                                 continue;
3291                 }
3292
3293                 list_del(&cmd->blocked_cmd_list_entry);
3294                 TRACE_MGMT_DBG("Adding cmd %p to head of active cmd list", cmd);
3295                 spin_lock(&cmd->cmd_lists->cmd_list_lock);
3296                 list_add(&cmd->cmd_list_entry,
3297                          &cmd->cmd_lists->active_cmd_list);
3298                 wake_up(&cmd->cmd_lists->cmd_list_waitQ);
3299                 spin_unlock(&cmd->cmd_lists->cmd_list_lock);
3300                 if (brk)
3301                         break;
3302         }
3303         local_irq_restore(flags);
3304 #else /* CONFIG_SCST_STRICT_SERIALIZING */
3305         struct scst_cmd *cmd, *tcmd;
3306         unsigned long flags;
3307
3308         TRACE_ENTRY();
3309
3310         local_irq_save(flags);
3311         list_for_each_entry_safe(cmd, tcmd, &dev->blocked_cmd_list,
3312                                  blocked_cmd_list_entry) {
3313                 list_del(&cmd->blocked_cmd_list_entry);
3314                 TRACE_MGMT_DBG("Adding blocked cmd %p to active cmd list", cmd);
3315                 spin_lock(&cmd->cmd_lists->cmd_list_lock);
3316                 if (unlikely(cmd->queue_type == SCST_CMD_QUEUE_HEAD_OF_QUEUE))
3317                         list_add(&cmd->cmd_list_entry,
3318                                 &cmd->cmd_lists->active_cmd_list);
3319                 else
3320                         list_add_tail(&cmd->cmd_list_entry,
3321                                 &cmd->cmd_lists->active_cmd_list);
3322                 wake_up(&cmd->cmd_lists->cmd_list_waitQ);
3323                 spin_unlock(&cmd->cmd_lists->cmd_list_lock);
3324         }
3325         local_irq_restore(flags);
3326 #endif /* CONFIG_SCST_STRICT_SERIALIZING */
3327
3328         TRACE_EXIT();
3329         return;
3330 }
3331
3332 static void __scst_unblock_deferred(struct scst_tgt_dev *tgt_dev,
3333         struct scst_cmd *out_of_sn_cmd)
3334 {
3335         EXTRACHECKS_BUG_ON(!out_of_sn_cmd->sn_set);
3336
3337         if (out_of_sn_cmd->sn == tgt_dev->expected_sn) {
3338                 scst_inc_expected_sn(tgt_dev, out_of_sn_cmd->sn_slot);
3339                 scst_make_deferred_commands_active(tgt_dev);
3340         } else {
3341                 out_of_sn_cmd->out_of_sn = 1;
3342                 spin_lock_irq(&tgt_dev->sn_lock);
3343                 tgt_dev->def_cmd_count++;
3344                 list_add_tail(&out_of_sn_cmd->sn_cmd_list_entry,
3345                               &tgt_dev->skipped_sn_list);
3346                 TRACE_SN("out_of_sn_cmd %p with sn %ld added to skipped_sn_list"
3347                         " (expected_sn %ld)", out_of_sn_cmd, out_of_sn_cmd->sn,
3348                         tgt_dev->expected_sn);
3349                 spin_unlock_irq(&tgt_dev->sn_lock);
3350         }
3351
3352         return;
3353 }
3354
3355 void scst_unblock_deferred(struct scst_tgt_dev *tgt_dev,
3356         struct scst_cmd *out_of_sn_cmd)
3357 {
3358         TRACE_ENTRY();
3359
3360         if (!out_of_sn_cmd->sn_set) {
3361                 TRACE_SN("cmd %p without sn", out_of_sn_cmd);
3362                 goto out;
3363         }
3364
3365         __scst_unblock_deferred(tgt_dev, out_of_sn_cmd);
3366
3367 out:
3368         TRACE_EXIT();
3369         return;
3370 }
3371
3372 void scst_on_hq_cmd_response(struct scst_cmd *cmd)
3373 {
3374         struct scst_tgt_dev *tgt_dev = cmd->tgt_dev;
3375
3376         TRACE_ENTRY();
3377
3378         if (!cmd->hq_cmd_inced)
3379                 goto out;
3380
3381         spin_lock_irq(&tgt_dev->sn_lock);
3382         tgt_dev->hq_cmd_count--;
3383         spin_unlock_irq(&tgt_dev->sn_lock);
3384
3385         EXTRACHECKS_BUG_ON(tgt_dev->hq_cmd_count < 0);
3386
3387         /*
3388          * There is no problem in checking hq_cmd_count in the
3389          * non-locked state. In the worst case we will only have
3390          * unneeded run of the deferred commands.
3391          */
3392         if (tgt_dev->hq_cmd_count == 0)
3393                 scst_make_deferred_commands_active(tgt_dev);
3394
3395 out:
3396         TRACE_EXIT();
3397         return;
3398 }
3399
3400 void scst_xmit_process_aborted_cmd(struct scst_cmd *cmd)
3401 {
3402         TRACE_ENTRY();
3403
3404         TRACE_MGMT_DBG("Aborted cmd %p done (cmd_ref %d, "
3405                 "scst_cmd_count %d)", cmd, atomic_read(&cmd->cmd_ref),
3406                 atomic_read(&scst_cmd_count));
3407
3408         scst_done_cmd_mgmt(cmd);
3409
3410         if (test_bit(SCST_CMD_ABORTED_OTHER, &cmd->cmd_flags)) {
3411                 if (cmd->completed) {
3412                         /* It's completed and it's OK to return its result */
3413                         goto out;
3414                 }
3415
3416                 if (cmd->dev->tas) {
3417                         TRACE_MGMT_DBG("Flag ABORTED OTHER set for cmd %p "
3418                                 "(tag %llu), returning TASK ABORTED ", cmd,
3419                                 (long long unsigned int)cmd->tag);
3420                         scst_set_cmd_error_status(cmd, SAM_STAT_TASK_ABORTED);
3421                 } else {
3422                         TRACE_MGMT_DBG("Flag ABORTED OTHER set for cmd %p "
3423                                 "(tag %llu), aborting without delivery or "
3424                                 "notification",
3425                                 cmd, (long long unsigned int)cmd->tag);
3426                         /*
3427                          * There is no need to check/requeue possible UA,
3428                          * because, if it exists, it will be delivered
3429                          * by the "completed" branch above.
3430                          */
3431                         clear_bit(SCST_CMD_ABORTED_OTHER, &cmd->cmd_flags);
3432                 }
3433         }
3434
3435 out:
3436         TRACE_EXIT();
3437         return;
3438 }
3439
3440 void __init scst_scsi_op_list_init(void)
3441 {
3442         int i;
3443         uint8_t op = 0xff;
3444
3445         TRACE_ENTRY();
3446
3447         for (i = 0; i < 256; i++)
3448                 scst_scsi_op_list[i] = SCST_CDB_TBL_SIZE;
3449
3450         for (i = 0; i < SCST_CDB_TBL_SIZE; i++) {
3451                 if (scst_scsi_op_table[i].ops != op) {
3452                         op = scst_scsi_op_table[i].ops;
3453                         scst_scsi_op_list[op] = i;
3454                 }
3455         }
3456
3457         TRACE_EXIT();
3458         return;
3459 }
3460
3461 #ifdef CONFIG_SCST_DEBUG
3462 /* Original taken from the XFS code */
3463 unsigned long scst_random(void)
3464 {
3465         static int Inited;
3466         static unsigned long RandomValue;
3467         static DEFINE_SPINLOCK(lock);
3468         /* cycles pseudo-randomly through all values between 1 and 2^31 - 2 */
3469         register long rv;
3470         register long lo;
3471         register long hi;
3472         unsigned long flags;
3473
3474         spin_lock_irqsave(&lock, flags);
3475         if (!Inited) {
3476                 RandomValue = jiffies;
3477                 Inited = 1;
3478         }
3479         rv = RandomValue;
3480         hi = rv / 127773;
3481         lo = rv % 127773;
3482         rv = 16807 * lo - 2836 * hi;
3483         if (rv <= 0)
3484                 rv += 2147483647;
3485         RandomValue = rv;
3486         spin_unlock_irqrestore(&lock, flags);
3487         return rv;
3488 }
3489 EXPORT_SYMBOL(scst_random);
3490 #endif
3491
3492 #ifdef CONFIG_SCST_DEBUG_TM
3493
3494 #define TM_DBG_STATE_ABORT              0
3495 #define TM_DBG_STATE_RESET              1
3496 #define TM_DBG_STATE_OFFLINE            2
3497
3498 #define INIT_TM_DBG_STATE               TM_DBG_STATE_ABORT
3499
3500 static void tm_dbg_timer_fn(unsigned long arg);
3501
3502 static DEFINE_SPINLOCK(scst_tm_dbg_lock);
3503 /* All serialized by scst_tm_dbg_lock */
3504 static struct {
3505         unsigned int tm_dbg_release:1;
3506         unsigned int tm_dbg_blocked:1;
3507 } tm_dbg_flags;
3508 static LIST_HEAD(tm_dbg_delayed_cmd_list);
3509 static int tm_dbg_delayed_cmds_count;
3510 static int tm_dbg_passed_cmds_count;
3511 static int tm_dbg_state;
3512 static int tm_dbg_on_state_passes;
3513 static DEFINE_TIMER(tm_dbg_timer, tm_dbg_timer_fn, 0, 0);
3514 static wait_queue_head_t *tm_dbg_p_cmd_list_waitQ;
3515
3516 static const int tm_dbg_on_state_num_passes[] = { 5, 1, 0x7ffffff };
3517
3518 static void tm_dbg_init_tgt_dev(struct scst_tgt_dev *tgt_dev,
3519         struct scst_acg_dev *acg_dev)
3520 {
3521         if ((acg_dev->acg == scst_default_acg) && (acg_dev->lun == 0)) {
3522                 unsigned long flags;
3523                 /* Do TM debugging only for LUN 0 */
3524                 spin_lock_irqsave(&scst_tm_dbg_lock, flags);
3525                 tm_dbg_p_cmd_list_waitQ =
3526                         &tgt_dev->dev->p_cmd_lists->cmd_list_waitQ;
3527                 tm_dbg_state = INIT_TM_DBG_STATE;
3528                 tm_dbg_on_state_passes =
3529                         tm_dbg_on_state_num_passes[tm_dbg_state];
3530                 __set_bit(SCST_TGT_DEV_UNDER_TM_DBG, &tgt_dev->tgt_dev_flags);
3531                 PRINT_INFO("LUN 0 connected from initiator %s is under "
3532                         "TM debugging", tgt_dev->sess->tgt->tgtt->name);
3533                 spin_unlock_irqrestore(&scst_tm_dbg_lock, flags);
3534         }
3535 }
3536
3537 static void tm_dbg_deinit_tgt_dev(struct scst_tgt_dev *tgt_dev)
3538 {
3539         if (test_bit(SCST_TGT_DEV_UNDER_TM_DBG, &tgt_dev->tgt_dev_flags)) {
3540                 unsigned long flags;
3541                 del_timer_sync(&tm_dbg_timer);
3542                 spin_lock_irqsave(&scst_tm_dbg_lock, flags);
3543                 tm_dbg_p_cmd_list_waitQ = NULL;
3544                 spin_unlock_irqrestore(&scst_tm_dbg_lock, flags);
3545         }
3546 }
3547
3548 static void tm_dbg_timer_fn(unsigned long arg)
3549 {
3550         TRACE_MGMT_DBG("%s", "delayed cmd timer expired");
3551         tm_dbg_flags.tm_dbg_release = 1;
3552         /* Used to make sure that all woken up threads see the new value */
3553         smp_wmb();
3554         wake_up_all(tm_dbg_p_cmd_list_waitQ);
3555 }
3556
3557 /* Called under scst_tm_dbg_lock and IRQs off */
3558 static void tm_dbg_delay_cmd(struct scst_cmd *cmd)
3559 {
3560         switch (tm_dbg_state) {
3561         case TM_DBG_STATE_ABORT:
3562                 if (tm_dbg_delayed_cmds_count == 0) {
3563                         unsigned long d = 58*HZ + (scst_random() % (4*HZ));
3564                         TRACE_MGMT_DBG("STATE ABORT: delaying cmd %p (tag %llu)"
3565                                 " for %ld.%ld seconds (%ld HZ), "
3566                                 "tm_dbg_on_state_passes=%d", cmd, cmd->tag,
3567                                 d/HZ, (d%HZ)*100/HZ, d, tm_dbg_on_state_passes);
3568                         mod_timer(&tm_dbg_timer, jiffies + d);
3569 #if 0
3570                         tm_dbg_flags.tm_dbg_blocked = 1;
3571 #endif
3572                 } else {
3573                         TRACE_MGMT_DBG("Delaying another timed cmd %p "
3574                                 "(tag %llu), delayed_cmds_count=%d, "
3575                                 "tm_dbg_on_state_passes=%d", cmd, cmd->tag,
3576                                 tm_dbg_delayed_cmds_count,
3577                                 tm_dbg_on_state_passes);
3578                         if (tm_dbg_delayed_cmds_count == 2)
3579                                 tm_dbg_flags.tm_dbg_blocked = 0;
3580                 }
3581                 break;
3582
3583         case TM_DBG_STATE_RESET:
3584         case TM_DBG_STATE_OFFLINE:
3585                 TRACE_MGMT_DBG("STATE RESET/OFFLINE: delaying cmd %p "
3586                         "(tag %llu), delayed_cmds_count=%d, "
3587                         "tm_dbg_on_state_passes=%d", cmd, cmd->tag,
3588                         tm_dbg_delayed_cmds_count, tm_dbg_on_state_passes);
3589                 tm_dbg_flags.tm_dbg_blocked = 1;
3590                 break;
3591
3592         default:
3593                 sBUG();
3594         }
3595         /* IRQs already off */
3596         spin_lock(&cmd->cmd_lists->cmd_list_lock);
3597         list_add_tail(&cmd->cmd_list_entry, &tm_dbg_delayed_cmd_list);
3598         spin_unlock(&cmd->cmd_lists->cmd_list_lock);
3599         cmd->tm_dbg_delayed = 1;
3600         tm_dbg_delayed_cmds_count++;
3601         return;
3602 }
3603
3604 /* No locks */
3605 void tm_dbg_check_released_cmds(void)
3606 {
3607         if (tm_dbg_flags.tm_dbg_release) {
3608                 struct scst_cmd *cmd, *tc;
3609                 spin_lock_irq(&scst_tm_dbg_lock);
3610                 list_for_each_entry_safe_reverse(cmd, tc,
3611                                 &tm_dbg_delayed_cmd_list, cmd_list_entry) {
3612                         TRACE_MGMT_DBG("Releasing timed cmd %p (tag %llu), "
3613                                 "delayed_cmds_count=%d", cmd, cmd->tag,
3614                                 tm_dbg_delayed_cmds_count);
3615                         spin_lock(&cmd->cmd_lists->cmd_list_lock);
3616                         list_move(&cmd->cmd_list_entry,
3617                                 &cmd->cmd_lists->active_cmd_list);
3618                         spin_unlock(&cmd->cmd_lists->cmd_list_lock);
3619                 }
3620                 tm_dbg_flags.tm_dbg_release = 0;
3621                 spin_unlock_irq(&scst_tm_dbg_lock);
3622         }
3623 }
3624
3625 /* Called under scst_tm_dbg_lock */
3626 static void tm_dbg_change_state(void)
3627 {
3628         tm_dbg_flags.tm_dbg_blocked = 0;
3629         if (--tm_dbg_on_state_passes == 0) {
3630                 switch (tm_dbg_state) {
3631                 case TM_DBG_STATE_ABORT:
3632                         TRACE_MGMT_DBG("%s", "Changing "
3633                             "tm_dbg_state to RESET");
3634                         tm_dbg_state =
3635                                 TM_DBG_STATE_RESET;
3636                         tm_dbg_flags.tm_dbg_blocked = 0;
3637                         break;
3638                 case TM_DBG_STATE_RESET:
3639                 case TM_DBG_STATE_OFFLINE:
3640 #ifdef CONFIG_SCST_TM_DBG_GO_OFFLINE
3641                             TRACE_MGMT_DBG("%s", "Changing "
3642                                     "tm_dbg_state to OFFLINE");
3643                             tm_dbg_state =
3644                                 TM_DBG_STATE_OFFLINE;
3645 #else
3646                             TRACE_MGMT_DBG("%s", "Changing "
3647                                     "tm_dbg_state to ABORT");
3648                             tm_dbg_state =
3649                                 TM_DBG_STATE_ABORT;
3650 #endif
3651                         break;
3652                 default:
3653                         sBUG();
3654                 }
3655                 tm_dbg_on_state_passes =
3656                     tm_dbg_on_state_num_passes[tm_dbg_state];
3657         }
3658
3659         TRACE_MGMT_DBG("%s", "Deleting timer");
3660         del_timer(&tm_dbg_timer);
3661 }
3662
3663 /* No locks */
3664 int tm_dbg_check_cmd(struct scst_cmd *cmd)
3665 {
3666         int res = 0;
3667         unsigned long flags;
3668
3669         if (cmd->tm_dbg_immut)
3670                 goto out;
3671
3672         if (cmd->tm_dbg_delayed) {
3673                 spin_lock_irqsave(&scst_tm_dbg_lock, flags);
3674                 TRACE_MGMT_DBG("Processing delayed cmd %p (tag %llu), "
3675                         "delayed_cmds_count=%d", cmd, cmd->tag,
3676                         tm_dbg_delayed_cmds_count);
3677
3678                 cmd->tm_dbg_immut = 1;
3679                 tm_dbg_delayed_cmds_count--;
3680                 if ((tm_dbg_delayed_cmds_count == 0) &&
3681                     (tm_dbg_state == TM_DBG_STATE_ABORT))
3682                         tm_dbg_change_state();
3683                 spin_unlock_irqrestore(&scst_tm_dbg_lock, flags);
3684         } else if (cmd->tgt_dev && test_bit(SCST_TGT_DEV_UNDER_TM_DBG,
3685                                         &cmd->tgt_dev->tgt_dev_flags)) {
3686                 /* Delay 50th command */
3687                 spin_lock_irqsave(&scst_tm_dbg_lock, flags);
3688                 if (tm_dbg_flags.tm_dbg_blocked ||
3689                     (++tm_dbg_passed_cmds_count % 50) == 0) {
3690                         tm_dbg_delay_cmd(cmd);
3691                         res = 1;
3692                 } else
3693                         cmd->tm_dbg_immut = 1;
3694                 spin_unlock_irqrestore(&scst_tm_dbg_lock, flags);
3695         }
3696
3697 out:
3698         return res;
3699 }
3700
3701 /* No locks */
3702 void tm_dbg_release_cmd(struct scst_cmd *cmd)
3703 {
3704         struct scst_cmd *c;
3705         unsigned long flags;
3706
3707         spin_lock_irqsave(&scst_tm_dbg_lock, flags);
3708         list_for_each_entry(c, &tm_dbg_delayed_cmd_list,
3709                                 cmd_list_entry) {
3710                 if (c == cmd) {
3711                         TRACE_MGMT_DBG("Abort request for "
3712                                 "delayed cmd %p (tag=%llu), moving it to "
3713                                 "active cmd list (delayed_cmds_count=%d)",
3714                                 c, c->tag, tm_dbg_delayed_cmds_count);
3715
3716                         if (!test_bit(SCST_CMD_ABORTED_OTHER,
3717                                             &cmd->cmd_flags)) {
3718                                 /* Test how completed commands handled */
3719                                 if (((scst_random() % 10) == 5)) {
3720                                         scst_set_cmd_error(cmd,
3721                                                 SCST_LOAD_SENSE(
3722                                                 scst_sense_hardw_error));
3723                                         /* It's completed now */
3724                                 }
3725                         }
3726
3727                         spin_lock(&cmd->cmd_lists->cmd_list_lock);
3728                         list_move(&c->cmd_list_entry,
3729                                 &c->cmd_lists->active_cmd_list);
3730                         wake_up(&c->cmd_lists->cmd_list_waitQ);
3731                         spin_unlock(&cmd->cmd_lists->cmd_list_lock);
3732                         break;
3733                 }
3734         }
3735         spin_unlock_irqrestore(&scst_tm_dbg_lock, flags);
3736 }
3737
3738 /* Might be called under scst_mutex */
3739 void tm_dbg_task_mgmt(struct scst_device *dev, const char *fn, int force)
3740 {
3741         unsigned long flags;
3742
3743         if (dev != NULL) {
3744                 struct scst_tgt_dev *tgt_dev;
3745                 bool found = 0;
3746
3747                 spin_lock_bh(&dev->dev_lock);
3748                 list_for_each_entry(tgt_dev, &dev->dev_tgt_dev_list,
3749                                             dev_tgt_dev_list_entry) {
3750                         if (test_bit(SCST_TGT_DEV_UNDER_TM_DBG,
3751                                         &tgt_dev->tgt_dev_flags)) {
3752                                 found = 1;
3753                                 break;
3754                         }
3755                 }
3756                 spin_unlock_bh(&dev->dev_lock);
3757
3758                 if (!found)
3759                         goto out;
3760         }
3761
3762         spin_lock_irqsave(&scst_tm_dbg_lock, flags);
3763         if ((tm_dbg_state !=