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