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