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