target: transport_subsystem_check_init cleanups
[linux-2.6.git] / drivers / target / target_core_transport.c
1 /*******************************************************************************
2  * Filename:  target_core_transport.c
3  *
4  * This file contains the Generic Target Engine Core.
5  *
6  * Copyright (c) 2002, 2003, 2004, 2005 PyX Technologies, Inc.
7  * Copyright (c) 2005, 2006, 2007 SBE, Inc.
8  * Copyright (c) 2007-2010 Rising Tide Systems
9  * Copyright (c) 2008-2010 Linux-iSCSI.org
10  *
11  * Nicholas A. Bellinger <nab@kernel.org>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26  *
27  ******************************************************************************/
28
29 #include <linux/net.h>
30 #include <linux/delay.h>
31 #include <linux/string.h>
32 #include <linux/timer.h>
33 #include <linux/slab.h>
34 #include <linux/blkdev.h>
35 #include <linux/spinlock.h>
36 #include <linux/kthread.h>
37 #include <linux/in.h>
38 #include <linux/cdrom.h>
39 #include <asm/unaligned.h>
40 #include <net/sock.h>
41 #include <net/tcp.h>
42 #include <scsi/scsi.h>
43 #include <scsi/scsi_cmnd.h>
44 #include <scsi/scsi_tcq.h>
45
46 #include <target/target_core_base.h>
47 #include <target/target_core_device.h>
48 #include <target/target_core_tmr.h>
49 #include <target/target_core_tpg.h>
50 #include <target/target_core_transport.h>
51 #include <target/target_core_fabric_ops.h>
52 #include <target/target_core_configfs.h>
53
54 #include "target_core_alua.h"
55 #include "target_core_hba.h"
56 #include "target_core_pr.h"
57 #include "target_core_ua.h"
58
59 static int sub_api_initialized;
60
61 static struct workqueue_struct *target_completion_wq;
62 static struct kmem_cache *se_cmd_cache;
63 static struct kmem_cache *se_sess_cache;
64 struct kmem_cache *se_tmr_req_cache;
65 struct kmem_cache *se_ua_cache;
66 struct kmem_cache *t10_pr_reg_cache;
67 struct kmem_cache *t10_alua_lu_gp_cache;
68 struct kmem_cache *t10_alua_lu_gp_mem_cache;
69 struct kmem_cache *t10_alua_tg_pt_gp_cache;
70 struct kmem_cache *t10_alua_tg_pt_gp_mem_cache;
71
72 static int transport_generic_write_pending(struct se_cmd *);
73 static int transport_processing_thread(void *param);
74 static int __transport_execute_tasks(struct se_device *dev);
75 static void transport_complete_task_attr(struct se_cmd *cmd);
76 static void transport_handle_queue_full(struct se_cmd *cmd,
77                 struct se_device *dev);
78 static void transport_direct_request_timeout(struct se_cmd *cmd);
79 static void transport_free_dev_tasks(struct se_cmd *cmd);
80 static u32 transport_allocate_tasks(struct se_cmd *cmd,
81                 unsigned long long starting_lba,
82                 enum dma_data_direction data_direction,
83                 struct scatterlist *sgl, unsigned int nents);
84 static int transport_generic_get_mem(struct se_cmd *cmd);
85 static void transport_put_cmd(struct se_cmd *cmd);
86 static void transport_remove_cmd_from_queue(struct se_cmd *cmd);
87 static int transport_set_sense_codes(struct se_cmd *cmd, u8 asc, u8 ascq);
88 static void transport_generic_request_failure(struct se_cmd *, int, int);
89 static void target_complete_ok_work(struct work_struct *work);
90
91 int init_se_kmem_caches(void)
92 {
93         se_cmd_cache = kmem_cache_create("se_cmd_cache",
94                         sizeof(struct se_cmd), __alignof__(struct se_cmd), 0, NULL);
95         if (!se_cmd_cache) {
96                 pr_err("kmem_cache_create for struct se_cmd failed\n");
97                 goto out;
98         }
99         se_tmr_req_cache = kmem_cache_create("se_tmr_cache",
100                         sizeof(struct se_tmr_req), __alignof__(struct se_tmr_req),
101                         0, NULL);
102         if (!se_tmr_req_cache) {
103                 pr_err("kmem_cache_create() for struct se_tmr_req"
104                                 " failed\n");
105                 goto out_free_cmd_cache;
106         }
107         se_sess_cache = kmem_cache_create("se_sess_cache",
108                         sizeof(struct se_session), __alignof__(struct se_session),
109                         0, NULL);
110         if (!se_sess_cache) {
111                 pr_err("kmem_cache_create() for struct se_session"
112                                 " failed\n");
113                 goto out_free_tmr_req_cache;
114         }
115         se_ua_cache = kmem_cache_create("se_ua_cache",
116                         sizeof(struct se_ua), __alignof__(struct se_ua),
117                         0, NULL);
118         if (!se_ua_cache) {
119                 pr_err("kmem_cache_create() for struct se_ua failed\n");
120                 goto out_free_sess_cache;
121         }
122         t10_pr_reg_cache = kmem_cache_create("t10_pr_reg_cache",
123                         sizeof(struct t10_pr_registration),
124                         __alignof__(struct t10_pr_registration), 0, NULL);
125         if (!t10_pr_reg_cache) {
126                 pr_err("kmem_cache_create() for struct t10_pr_registration"
127                                 " failed\n");
128                 goto out_free_ua_cache;
129         }
130         t10_alua_lu_gp_cache = kmem_cache_create("t10_alua_lu_gp_cache",
131                         sizeof(struct t10_alua_lu_gp), __alignof__(struct t10_alua_lu_gp),
132                         0, NULL);
133         if (!t10_alua_lu_gp_cache) {
134                 pr_err("kmem_cache_create() for t10_alua_lu_gp_cache"
135                                 " failed\n");
136                 goto out_free_pr_reg_cache;
137         }
138         t10_alua_lu_gp_mem_cache = kmem_cache_create("t10_alua_lu_gp_mem_cache",
139                         sizeof(struct t10_alua_lu_gp_member),
140                         __alignof__(struct t10_alua_lu_gp_member), 0, NULL);
141         if (!t10_alua_lu_gp_mem_cache) {
142                 pr_err("kmem_cache_create() for t10_alua_lu_gp_mem_"
143                                 "cache failed\n");
144                 goto out_free_lu_gp_cache;
145         }
146         t10_alua_tg_pt_gp_cache = kmem_cache_create("t10_alua_tg_pt_gp_cache",
147                         sizeof(struct t10_alua_tg_pt_gp),
148                         __alignof__(struct t10_alua_tg_pt_gp), 0, NULL);
149         if (!t10_alua_tg_pt_gp_cache) {
150                 pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
151                                 "cache failed\n");
152                 goto out_free_lu_gp_mem_cache;
153         }
154         t10_alua_tg_pt_gp_mem_cache = kmem_cache_create(
155                         "t10_alua_tg_pt_gp_mem_cache",
156                         sizeof(struct t10_alua_tg_pt_gp_member),
157                         __alignof__(struct t10_alua_tg_pt_gp_member),
158                         0, NULL);
159         if (!t10_alua_tg_pt_gp_mem_cache) {
160                 pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
161                                 "mem_t failed\n");
162                 goto out_free_tg_pt_gp_cache;
163         }
164
165         target_completion_wq = alloc_workqueue("target_completion",
166                                                WQ_MEM_RECLAIM, 0);
167         if (!target_completion_wq)
168                 goto out_free_tg_pt_gp_mem_cache;
169
170         return 0;
171
172 out_free_tg_pt_gp_mem_cache:
173         kmem_cache_destroy(t10_alua_tg_pt_gp_mem_cache);
174 out_free_tg_pt_gp_cache:
175         kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
176 out_free_lu_gp_mem_cache:
177         kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
178 out_free_lu_gp_cache:
179         kmem_cache_destroy(t10_alua_lu_gp_cache);
180 out_free_pr_reg_cache:
181         kmem_cache_destroy(t10_pr_reg_cache);
182 out_free_ua_cache:
183         kmem_cache_destroy(se_ua_cache);
184 out_free_sess_cache:
185         kmem_cache_destroy(se_sess_cache);
186 out_free_tmr_req_cache:
187         kmem_cache_destroy(se_tmr_req_cache);
188 out_free_cmd_cache:
189         kmem_cache_destroy(se_cmd_cache);
190 out:
191         return -ENOMEM;
192 }
193
194 void release_se_kmem_caches(void)
195 {
196         destroy_workqueue(target_completion_wq);
197         kmem_cache_destroy(se_cmd_cache);
198         kmem_cache_destroy(se_tmr_req_cache);
199         kmem_cache_destroy(se_sess_cache);
200         kmem_cache_destroy(se_ua_cache);
201         kmem_cache_destroy(t10_pr_reg_cache);
202         kmem_cache_destroy(t10_alua_lu_gp_cache);
203         kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
204         kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
205         kmem_cache_destroy(t10_alua_tg_pt_gp_mem_cache);
206 }
207
208 /* This code ensures unique mib indexes are handed out. */
209 static DEFINE_SPINLOCK(scsi_mib_index_lock);
210 static u32 scsi_mib_index[SCSI_INDEX_TYPE_MAX];
211
212 /*
213  * Allocate a new row index for the entry type specified
214  */
215 u32 scsi_get_new_index(scsi_index_t type)
216 {
217         u32 new_index;
218
219         BUG_ON((type < 0) || (type >= SCSI_INDEX_TYPE_MAX));
220
221         spin_lock(&scsi_mib_index_lock);
222         new_index = ++scsi_mib_index[type];
223         spin_unlock(&scsi_mib_index_lock);
224
225         return new_index;
226 }
227
228 void transport_init_queue_obj(struct se_queue_obj *qobj)
229 {
230         atomic_set(&qobj->queue_cnt, 0);
231         INIT_LIST_HEAD(&qobj->qobj_list);
232         init_waitqueue_head(&qobj->thread_wq);
233         spin_lock_init(&qobj->cmd_queue_lock);
234 }
235 EXPORT_SYMBOL(transport_init_queue_obj);
236
237 void transport_subsystem_check_init(void)
238 {
239         int ret;
240
241         if (sub_api_initialized)
242                 return;
243
244         ret = request_module("target_core_iblock");
245         if (ret != 0)
246                 pr_err("Unable to load target_core_iblock\n");
247
248         ret = request_module("target_core_file");
249         if (ret != 0)
250                 pr_err("Unable to load target_core_file\n");
251
252         ret = request_module("target_core_pscsi");
253         if (ret != 0)
254                 pr_err("Unable to load target_core_pscsi\n");
255
256         ret = request_module("target_core_stgt");
257         if (ret != 0)
258                 pr_err("Unable to load target_core_stgt\n");
259
260         sub_api_initialized = 1;
261         return;
262 }
263
264 struct se_session *transport_init_session(void)
265 {
266         struct se_session *se_sess;
267
268         se_sess = kmem_cache_zalloc(se_sess_cache, GFP_KERNEL);
269         if (!se_sess) {
270                 pr_err("Unable to allocate struct se_session from"
271                                 " se_sess_cache\n");
272                 return ERR_PTR(-ENOMEM);
273         }
274         INIT_LIST_HEAD(&se_sess->sess_list);
275         INIT_LIST_HEAD(&se_sess->sess_acl_list);
276
277         return se_sess;
278 }
279 EXPORT_SYMBOL(transport_init_session);
280
281 /*
282  * Called with spin_lock_bh(&struct se_portal_group->session_lock called.
283  */
284 void __transport_register_session(
285         struct se_portal_group *se_tpg,
286         struct se_node_acl *se_nacl,
287         struct se_session *se_sess,
288         void *fabric_sess_ptr)
289 {
290         unsigned char buf[PR_REG_ISID_LEN];
291
292         se_sess->se_tpg = se_tpg;
293         se_sess->fabric_sess_ptr = fabric_sess_ptr;
294         /*
295          * Used by struct se_node_acl's under ConfigFS to locate active se_session-t
296          *
297          * Only set for struct se_session's that will actually be moving I/O.
298          * eg: *NOT* discovery sessions.
299          */
300         if (se_nacl) {
301                 /*
302                  * If the fabric module supports an ISID based TransportID,
303                  * save this value in binary from the fabric I_T Nexus now.
304                  */
305                 if (se_tpg->se_tpg_tfo->sess_get_initiator_sid != NULL) {
306                         memset(&buf[0], 0, PR_REG_ISID_LEN);
307                         se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess,
308                                         &buf[0], PR_REG_ISID_LEN);
309                         se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]);
310                 }
311                 spin_lock_irq(&se_nacl->nacl_sess_lock);
312                 /*
313                  * The se_nacl->nacl_sess pointer will be set to the
314                  * last active I_T Nexus for each struct se_node_acl.
315                  */
316                 se_nacl->nacl_sess = se_sess;
317
318                 list_add_tail(&se_sess->sess_acl_list,
319                               &se_nacl->acl_sess_list);
320                 spin_unlock_irq(&se_nacl->nacl_sess_lock);
321         }
322         list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
323
324         pr_debug("TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
325                 se_tpg->se_tpg_tfo->get_fabric_name(), se_sess->fabric_sess_ptr);
326 }
327 EXPORT_SYMBOL(__transport_register_session);
328
329 void transport_register_session(
330         struct se_portal_group *se_tpg,
331         struct se_node_acl *se_nacl,
332         struct se_session *se_sess,
333         void *fabric_sess_ptr)
334 {
335         spin_lock_bh(&se_tpg->session_lock);
336         __transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
337         spin_unlock_bh(&se_tpg->session_lock);
338 }
339 EXPORT_SYMBOL(transport_register_session);
340
341 void transport_deregister_session_configfs(struct se_session *se_sess)
342 {
343         struct se_node_acl *se_nacl;
344         unsigned long flags;
345         /*
346          * Used by struct se_node_acl's under ConfigFS to locate active struct se_session
347          */
348         se_nacl = se_sess->se_node_acl;
349         if (se_nacl) {
350                 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
351                 list_del(&se_sess->sess_acl_list);
352                 /*
353                  * If the session list is empty, then clear the pointer.
354                  * Otherwise, set the struct se_session pointer from the tail
355                  * element of the per struct se_node_acl active session list.
356                  */
357                 if (list_empty(&se_nacl->acl_sess_list))
358                         se_nacl->nacl_sess = NULL;
359                 else {
360                         se_nacl->nacl_sess = container_of(
361                                         se_nacl->acl_sess_list.prev,
362                                         struct se_session, sess_acl_list);
363                 }
364                 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
365         }
366 }
367 EXPORT_SYMBOL(transport_deregister_session_configfs);
368
369 void transport_free_session(struct se_session *se_sess)
370 {
371         kmem_cache_free(se_sess_cache, se_sess);
372 }
373 EXPORT_SYMBOL(transport_free_session);
374
375 void transport_deregister_session(struct se_session *se_sess)
376 {
377         struct se_portal_group *se_tpg = se_sess->se_tpg;
378         struct se_node_acl *se_nacl;
379         unsigned long flags;
380
381         if (!se_tpg) {
382                 transport_free_session(se_sess);
383                 return;
384         }
385
386         spin_lock_irqsave(&se_tpg->session_lock, flags);
387         list_del(&se_sess->sess_list);
388         se_sess->se_tpg = NULL;
389         se_sess->fabric_sess_ptr = NULL;
390         spin_unlock_irqrestore(&se_tpg->session_lock, flags);
391
392         /*
393          * Determine if we need to do extra work for this initiator node's
394          * struct se_node_acl if it had been previously dynamically generated.
395          */
396         se_nacl = se_sess->se_node_acl;
397         if (se_nacl) {
398                 spin_lock_irqsave(&se_tpg->acl_node_lock, flags);
399                 if (se_nacl->dynamic_node_acl) {
400                         if (!se_tpg->se_tpg_tfo->tpg_check_demo_mode_cache(
401                                         se_tpg)) {
402                                 list_del(&se_nacl->acl_list);
403                                 se_tpg->num_node_acls--;
404                                 spin_unlock_irqrestore(&se_tpg->acl_node_lock, flags);
405
406                                 core_tpg_wait_for_nacl_pr_ref(se_nacl);
407                                 core_free_device_list_for_node(se_nacl, se_tpg);
408                                 se_tpg->se_tpg_tfo->tpg_release_fabric_acl(se_tpg,
409                                                 se_nacl);
410                                 spin_lock_irqsave(&se_tpg->acl_node_lock, flags);
411                         }
412                 }
413                 spin_unlock_irqrestore(&se_tpg->acl_node_lock, flags);
414         }
415
416         transport_free_session(se_sess);
417
418         pr_debug("TARGET_CORE[%s]: Deregistered fabric_sess\n",
419                 se_tpg->se_tpg_tfo->get_fabric_name());
420 }
421 EXPORT_SYMBOL(transport_deregister_session);
422
423 /*
424  * Called with cmd->t_state_lock held.
425  */
426 static void transport_all_task_dev_remove_state(struct se_cmd *cmd)
427 {
428         struct se_device *dev = cmd->se_dev;
429         struct se_task *task;
430         unsigned long flags;
431
432         if (!dev)
433                 return;
434
435         list_for_each_entry(task, &cmd->t_task_list, t_list) {
436                 if (task->task_flags & TF_ACTIVE)
437                         continue;
438
439                 if (!atomic_read(&task->task_state_active))
440                         continue;
441
442                 spin_lock_irqsave(&dev->execute_task_lock, flags);
443                 list_del(&task->t_state_list);
444                 pr_debug("Removed ITT: 0x%08x dev: %p task[%p]\n",
445                         cmd->se_tfo->get_task_tag(cmd), dev, task);
446                 spin_unlock_irqrestore(&dev->execute_task_lock, flags);
447
448                 atomic_set(&task->task_state_active, 0);
449                 atomic_dec(&cmd->t_task_cdbs_ex_left);
450         }
451 }
452
453 /*      transport_cmd_check_stop():
454  *
455  *      'transport_off = 1' determines if t_transport_active should be cleared.
456  *      'transport_off = 2' determines if task_dev_state should be removed.
457  *
458  *      A non-zero u8 t_state sets cmd->t_state.
459  *      Returns 1 when command is stopped, else 0.
460  */
461 static int transport_cmd_check_stop(
462         struct se_cmd *cmd,
463         int transport_off,
464         u8 t_state)
465 {
466         unsigned long flags;
467
468         spin_lock_irqsave(&cmd->t_state_lock, flags);
469         /*
470          * Determine if IOCTL context caller in requesting the stopping of this
471          * command for LUN shutdown purposes.
472          */
473         if (atomic_read(&cmd->transport_lun_stop)) {
474                 pr_debug("%s:%d atomic_read(&cmd->transport_lun_stop)"
475                         " == TRUE for ITT: 0x%08x\n", __func__, __LINE__,
476                         cmd->se_tfo->get_task_tag(cmd));
477
478                 atomic_set(&cmd->t_transport_active, 0);
479                 if (transport_off == 2)
480                         transport_all_task_dev_remove_state(cmd);
481                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
482
483                 complete(&cmd->transport_lun_stop_comp);
484                 return 1;
485         }
486         /*
487          * Determine if frontend context caller is requesting the stopping of
488          * this command for frontend exceptions.
489          */
490         if (atomic_read(&cmd->t_transport_stop)) {
491                 pr_debug("%s:%d atomic_read(&cmd->t_transport_stop) =="
492                         " TRUE for ITT: 0x%08x\n", __func__, __LINE__,
493                         cmd->se_tfo->get_task_tag(cmd));
494
495                 if (transport_off == 2)
496                         transport_all_task_dev_remove_state(cmd);
497
498                 /*
499                  * Clear struct se_cmd->se_lun before the transport_off == 2 handoff
500                  * to FE.
501                  */
502                 if (transport_off == 2)
503                         cmd->se_lun = NULL;
504                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
505
506                 complete(&cmd->t_transport_stop_comp);
507                 return 1;
508         }
509         if (transport_off) {
510                 atomic_set(&cmd->t_transport_active, 0);
511                 if (transport_off == 2) {
512                         transport_all_task_dev_remove_state(cmd);
513                         /*
514                          * Clear struct se_cmd->se_lun before the transport_off == 2
515                          * handoff to fabric module.
516                          */
517                         cmd->se_lun = NULL;
518                         /*
519                          * Some fabric modules like tcm_loop can release
520                          * their internally allocated I/O reference now and
521                          * struct se_cmd now.
522                          */
523                         if (cmd->se_tfo->check_stop_free != NULL) {
524                                 spin_unlock_irqrestore(
525                                         &cmd->t_state_lock, flags);
526
527                                 cmd->se_tfo->check_stop_free(cmd);
528                                 return 1;
529                         }
530                 }
531                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
532
533                 return 0;
534         } else if (t_state)
535                 cmd->t_state = t_state;
536         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
537
538         return 0;
539 }
540
541 static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
542 {
543         return transport_cmd_check_stop(cmd, 2, 0);
544 }
545
546 static void transport_lun_remove_cmd(struct se_cmd *cmd)
547 {
548         struct se_lun *lun = cmd->se_lun;
549         unsigned long flags;
550
551         if (!lun)
552                 return;
553
554         spin_lock_irqsave(&cmd->t_state_lock, flags);
555         if (!atomic_read(&cmd->transport_dev_active)) {
556                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
557                 goto check_lun;
558         }
559         atomic_set(&cmd->transport_dev_active, 0);
560         transport_all_task_dev_remove_state(cmd);
561         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
562
563
564 check_lun:
565         spin_lock_irqsave(&lun->lun_cmd_lock, flags);
566         if (atomic_read(&cmd->transport_lun_active)) {
567                 list_del(&cmd->se_lun_node);
568                 atomic_set(&cmd->transport_lun_active, 0);
569 #if 0
570                 pr_debug("Removed ITT: 0x%08x from LUN LIST[%d]\n"
571                         cmd->se_tfo->get_task_tag(cmd), lun->unpacked_lun);
572 #endif
573         }
574         spin_unlock_irqrestore(&lun->lun_cmd_lock, flags);
575 }
576
577 void transport_cmd_finish_abort(struct se_cmd *cmd, int remove)
578 {
579         if (!cmd->se_tmr_req)
580                 transport_lun_remove_cmd(cmd);
581
582         if (transport_cmd_check_stop_to_fabric(cmd))
583                 return;
584         if (remove) {
585                 transport_remove_cmd_from_queue(cmd);
586                 transport_put_cmd(cmd);
587         }
588 }
589
590 static void transport_add_cmd_to_queue(struct se_cmd *cmd, int t_state,
591                 bool at_head)
592 {
593         struct se_device *dev = cmd->se_dev;
594         struct se_queue_obj *qobj = &dev->dev_queue_obj;
595         unsigned long flags;
596
597         if (t_state) {
598                 spin_lock_irqsave(&cmd->t_state_lock, flags);
599                 cmd->t_state = t_state;
600                 atomic_set(&cmd->t_transport_active, 1);
601                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
602         }
603
604         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
605
606         /* If the cmd is already on the list, remove it before we add it */
607         if (!list_empty(&cmd->se_queue_node))
608                 list_del(&cmd->se_queue_node);
609         else
610                 atomic_inc(&qobj->queue_cnt);
611
612         if (at_head)
613                 list_add(&cmd->se_queue_node, &qobj->qobj_list);
614         else
615                 list_add_tail(&cmd->se_queue_node, &qobj->qobj_list);
616         atomic_set(&cmd->t_transport_queue_active, 1);
617         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
618
619         wake_up_interruptible(&qobj->thread_wq);
620 }
621
622 static struct se_cmd *
623 transport_get_cmd_from_queue(struct se_queue_obj *qobj)
624 {
625         struct se_cmd *cmd;
626         unsigned long flags;
627
628         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
629         if (list_empty(&qobj->qobj_list)) {
630                 spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
631                 return NULL;
632         }
633         cmd = list_first_entry(&qobj->qobj_list, struct se_cmd, se_queue_node);
634
635         atomic_set(&cmd->t_transport_queue_active, 0);
636
637         list_del_init(&cmd->se_queue_node);
638         atomic_dec(&qobj->queue_cnt);
639         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
640
641         return cmd;
642 }
643
644 static void transport_remove_cmd_from_queue(struct se_cmd *cmd)
645 {
646         struct se_queue_obj *qobj = &cmd->se_dev->dev_queue_obj;
647         unsigned long flags;
648
649         spin_lock_irqsave(&qobj->cmd_queue_lock, flags);
650         if (!atomic_read(&cmd->t_transport_queue_active)) {
651                 spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
652                 return;
653         }
654         atomic_set(&cmd->t_transport_queue_active, 0);
655         atomic_dec(&qobj->queue_cnt);
656         list_del_init(&cmd->se_queue_node);
657         spin_unlock_irqrestore(&qobj->cmd_queue_lock, flags);
658
659         if (atomic_read(&cmd->t_transport_queue_active)) {
660                 pr_err("ITT: 0x%08x t_transport_queue_active: %d\n",
661                         cmd->se_tfo->get_task_tag(cmd),
662                         atomic_read(&cmd->t_transport_queue_active));
663         }
664 }
665
666 /*
667  * Completion function used by TCM subsystem plugins (such as FILEIO)
668  * for queueing up response from struct se_subsystem_api->do_task()
669  */
670 void transport_complete_sync_cache(struct se_cmd *cmd, int good)
671 {
672         struct se_task *task = list_entry(cmd->t_task_list.next,
673                                 struct se_task, t_list);
674
675         if (good) {
676                 cmd->scsi_status = SAM_STAT_GOOD;
677                 task->task_scsi_status = GOOD;
678         } else {
679                 task->task_scsi_status = SAM_STAT_CHECK_CONDITION;
680                 task->task_error_status = PYX_TRANSPORT_ILLEGAL_REQUEST;
681                 task->task_se_cmd->transport_error_status =
682                                         PYX_TRANSPORT_ILLEGAL_REQUEST;
683         }
684
685         transport_complete_task(task, good);
686 }
687 EXPORT_SYMBOL(transport_complete_sync_cache);
688
689 static void target_complete_timeout_work(struct work_struct *work)
690 {
691         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
692         unsigned long flags;
693
694         /*
695          * Reset cmd->t_se_count to allow transport_put_cmd()
696          * to allow last call to free memory resources.
697          */
698         spin_lock_irqsave(&cmd->t_state_lock, flags);
699         if (atomic_read(&cmd->t_transport_timeout) > 1) {
700                 int tmp = (atomic_read(&cmd->t_transport_timeout) - 1);
701
702                 atomic_sub(tmp, &cmd->t_se_count);
703         }
704         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
705
706         transport_put_cmd(cmd);
707 }
708
709 static void target_complete_failure_work(struct work_struct *work)
710 {
711         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
712
713         transport_generic_request_failure(cmd, 1, 1);
714 }
715
716 /*      transport_complete_task():
717  *
718  *      Called from interrupt and non interrupt context depending
719  *      on the transport plugin.
720  */
721 void transport_complete_task(struct se_task *task, int success)
722 {
723         struct se_cmd *cmd = task->task_se_cmd;
724         struct se_device *dev = cmd->se_dev;
725         unsigned long flags;
726 #if 0
727         pr_debug("task: %p CDB: 0x%02x obj_ptr: %p\n", task,
728                         cmd->t_task_cdb[0], dev);
729 #endif
730         if (dev)
731                 atomic_inc(&dev->depth_left);
732
733         del_timer(&task->task_timer);
734
735         spin_lock_irqsave(&cmd->t_state_lock, flags);
736         task->task_flags &= ~TF_ACTIVE;
737
738         /*
739          * See if any sense data exists, if so set the TASK_SENSE flag.
740          * Also check for any other post completion work that needs to be
741          * done by the plugins.
742          */
743         if (dev && dev->transport->transport_complete) {
744                 if (dev->transport->transport_complete(task) != 0) {
745                         cmd->se_cmd_flags |= SCF_TRANSPORT_TASK_SENSE;
746                         task->task_sense = 1;
747                         success = 1;
748                 }
749         }
750
751         /*
752          * See if we are waiting for outstanding struct se_task
753          * to complete for an exception condition
754          */
755         if (task->task_flags & TF_REQUEST_STOP) {
756                 /*
757                  * Decrement cmd->t_se_count if this task had
758                  * previously thrown its timeout exception handler.
759                  */
760                 if (task->task_flags & TF_TIMEOUT) {
761                         atomic_dec(&cmd->t_se_count);
762                         task->task_flags &= ~TF_TIMEOUT;
763                 }
764                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
765
766                 complete(&task->task_stop_comp);
767                 return;
768         }
769         /*
770          * If the task's timeout handler has fired, use the t_task_cdbs_timeout
771          * left counter to determine when the struct se_cmd is ready to be queued to
772          * the processing thread.
773          */
774         if (task->task_flags & TF_TIMEOUT) {
775                 if (!atomic_dec_and_test(&cmd->t_task_cdbs_timeout_left)) {
776                         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
777                         return;
778                 }
779                 INIT_WORK(&cmd->work, target_complete_timeout_work);
780                 goto out_queue;
781         }
782         atomic_dec(&cmd->t_task_cdbs_timeout_left);
783
784         /*
785          * Decrement the outstanding t_task_cdbs_left count.  The last
786          * struct se_task from struct se_cmd will complete itself into the
787          * device queue depending upon int success.
788          */
789         if (!atomic_dec_and_test(&cmd->t_task_cdbs_left)) {
790                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
791                 return;
792         }
793
794         if (!success || cmd->t_tasks_failed) {
795                 if (!task->task_error_status) {
796                         task->task_error_status =
797                                 PYX_TRANSPORT_UNKNOWN_SAM_OPCODE;
798                         cmd->transport_error_status =
799                                 PYX_TRANSPORT_UNKNOWN_SAM_OPCODE;
800                 }
801                 INIT_WORK(&cmd->work, target_complete_failure_work);
802         } else {
803                 atomic_set(&cmd->t_transport_complete, 1);
804                 INIT_WORK(&cmd->work, target_complete_ok_work);
805         }
806
807 out_queue:
808         cmd->t_state = TRANSPORT_COMPLETE;
809         atomic_set(&cmd->t_transport_active, 1);
810         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
811
812         queue_work(target_completion_wq, &cmd->work);
813 }
814 EXPORT_SYMBOL(transport_complete_task);
815
816 /*
817  * Called by transport_add_tasks_from_cmd() once a struct se_cmd's
818  * struct se_task list are ready to be added to the active execution list
819  * struct se_device
820
821  * Called with se_dev_t->execute_task_lock called.
822  */
823 static inline int transport_add_task_check_sam_attr(
824         struct se_task *task,
825         struct se_task *task_prev,
826         struct se_device *dev)
827 {
828         /*
829          * No SAM Task attribute emulation enabled, add to tail of
830          * execution queue
831          */
832         if (dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED) {
833                 list_add_tail(&task->t_execute_list, &dev->execute_task_list);
834                 return 0;
835         }
836         /*
837          * HEAD_OF_QUEUE attribute for received CDB, which means
838          * the first task that is associated with a struct se_cmd goes to
839          * head of the struct se_device->execute_task_list, and task_prev
840          * after that for each subsequent task
841          */
842         if (task->task_se_cmd->sam_task_attr == MSG_HEAD_TAG) {
843                 list_add(&task->t_execute_list,
844                                 (task_prev != NULL) ?
845                                 &task_prev->t_execute_list :
846                                 &dev->execute_task_list);
847
848                 pr_debug("Set HEAD_OF_QUEUE for task CDB: 0x%02x"
849                                 " in execution queue\n",
850                                 task->task_se_cmd->t_task_cdb[0]);
851                 return 1;
852         }
853         /*
854          * For ORDERED, SIMPLE or UNTAGGED attribute tasks once they have been
855          * transitioned from Dermant -> Active state, and are added to the end
856          * of the struct se_device->execute_task_list
857          */
858         list_add_tail(&task->t_execute_list, &dev->execute_task_list);
859         return 0;
860 }
861
862 /*      __transport_add_task_to_execute_queue():
863  *
864  *      Called with se_dev_t->execute_task_lock called.
865  */
866 static void __transport_add_task_to_execute_queue(
867         struct se_task *task,
868         struct se_task *task_prev,
869         struct se_device *dev)
870 {
871         int head_of_queue;
872
873         head_of_queue = transport_add_task_check_sam_attr(task, task_prev, dev);
874         atomic_inc(&dev->execute_tasks);
875
876         if (atomic_read(&task->task_state_active))
877                 return;
878         /*
879          * Determine if this task needs to go to HEAD_OF_QUEUE for the
880          * state list as well.  Running with SAM Task Attribute emulation
881          * will always return head_of_queue == 0 here
882          */
883         if (head_of_queue)
884                 list_add(&task->t_state_list, (task_prev) ?
885                                 &task_prev->t_state_list :
886                                 &dev->state_task_list);
887         else
888                 list_add_tail(&task->t_state_list, &dev->state_task_list);
889
890         atomic_set(&task->task_state_active, 1);
891
892         pr_debug("Added ITT: 0x%08x task[%p] to dev: %p\n",
893                 task->task_se_cmd->se_tfo->get_task_tag(task->task_se_cmd),
894                 task, dev);
895 }
896
897 static void transport_add_tasks_to_state_queue(struct se_cmd *cmd)
898 {
899         struct se_device *dev = cmd->se_dev;
900         struct se_task *task;
901         unsigned long flags;
902
903         spin_lock_irqsave(&cmd->t_state_lock, flags);
904         list_for_each_entry(task, &cmd->t_task_list, t_list) {
905                 if (atomic_read(&task->task_state_active))
906                         continue;
907
908                 spin_lock(&dev->execute_task_lock);
909                 list_add_tail(&task->t_state_list, &dev->state_task_list);
910                 atomic_set(&task->task_state_active, 1);
911
912                 pr_debug("Added ITT: 0x%08x task[%p] to dev: %p\n",
913                         task->task_se_cmd->se_tfo->get_task_tag(
914                         task->task_se_cmd), task, dev);
915
916                 spin_unlock(&dev->execute_task_lock);
917         }
918         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
919 }
920
921 static void transport_add_tasks_from_cmd(struct se_cmd *cmd)
922 {
923         struct se_device *dev = cmd->se_dev;
924         struct se_task *task, *task_prev = NULL;
925         unsigned long flags;
926
927         spin_lock_irqsave(&dev->execute_task_lock, flags);
928         list_for_each_entry(task, &cmd->t_task_list, t_list) {
929                 if (!list_empty(&task->t_execute_list))
930                         continue;
931                 /*
932                  * __transport_add_task_to_execute_queue() handles the
933                  * SAM Task Attribute emulation if enabled
934                  */
935                 __transport_add_task_to_execute_queue(task, task_prev, dev);
936                 task_prev = task;
937         }
938         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
939 }
940
941 void __transport_remove_task_from_execute_queue(struct se_task *task,
942                 struct se_device *dev)
943 {
944         list_del_init(&task->t_execute_list);
945         atomic_dec(&dev->execute_tasks);
946 }
947
948 void transport_remove_task_from_execute_queue(
949         struct se_task *task,
950         struct se_device *dev)
951 {
952         unsigned long flags;
953
954         if (WARN_ON(list_empty(&task->t_execute_list)))
955                 return;
956
957         spin_lock_irqsave(&dev->execute_task_lock, flags);
958         __transport_remove_task_from_execute_queue(task, dev);
959         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
960 }
961
962 /*
963  * Handle QUEUE_FULL / -EAGAIN status
964  */
965
966 static void target_qf_do_work(struct work_struct *work)
967 {
968         struct se_device *dev = container_of(work, struct se_device,
969                                         qf_work_queue);
970         LIST_HEAD(qf_cmd_list);
971         struct se_cmd *cmd, *cmd_tmp;
972
973         spin_lock_irq(&dev->qf_cmd_lock);
974         list_splice_init(&dev->qf_cmd_list, &qf_cmd_list);
975         spin_unlock_irq(&dev->qf_cmd_lock);
976
977         list_for_each_entry_safe(cmd, cmd_tmp, &qf_cmd_list, se_qf_node) {
978                 list_del(&cmd->se_qf_node);
979                 atomic_dec(&dev->dev_qf_count);
980                 smp_mb__after_atomic_dec();
981
982                 pr_debug("Processing %s cmd: %p QUEUE_FULL in work queue"
983                         " context: %s\n", cmd->se_tfo->get_fabric_name(), cmd,
984                         (cmd->t_state == TRANSPORT_COMPLETE_QF_OK) ? "COMPLETE_OK" :
985                         (cmd->t_state == TRANSPORT_COMPLETE_QF_WP) ? "WRITE_PENDING"
986                         : "UNKNOWN");
987
988                 transport_add_cmd_to_queue(cmd, cmd->t_state, true);
989         }
990 }
991
992 unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
993 {
994         switch (cmd->data_direction) {
995         case DMA_NONE:
996                 return "NONE";
997         case DMA_FROM_DEVICE:
998                 return "READ";
999         case DMA_TO_DEVICE:
1000                 return "WRITE";
1001         case DMA_BIDIRECTIONAL:
1002                 return "BIDI";
1003         default:
1004                 break;
1005         }
1006
1007         return "UNKNOWN";
1008 }
1009
1010 void transport_dump_dev_state(
1011         struct se_device *dev,
1012         char *b,
1013         int *bl)
1014 {
1015         *bl += sprintf(b + *bl, "Status: ");
1016         switch (dev->dev_status) {
1017         case TRANSPORT_DEVICE_ACTIVATED:
1018                 *bl += sprintf(b + *bl, "ACTIVATED");
1019                 break;
1020         case TRANSPORT_DEVICE_DEACTIVATED:
1021                 *bl += sprintf(b + *bl, "DEACTIVATED");
1022                 break;
1023         case TRANSPORT_DEVICE_SHUTDOWN:
1024                 *bl += sprintf(b + *bl, "SHUTDOWN");
1025                 break;
1026         case TRANSPORT_DEVICE_OFFLINE_ACTIVATED:
1027         case TRANSPORT_DEVICE_OFFLINE_DEACTIVATED:
1028                 *bl += sprintf(b + *bl, "OFFLINE");
1029                 break;
1030         default:
1031                 *bl += sprintf(b + *bl, "UNKNOWN=%d", dev->dev_status);
1032                 break;
1033         }
1034
1035         *bl += sprintf(b + *bl, "  Execute/Left/Max Queue Depth: %d/%d/%d",
1036                 atomic_read(&dev->execute_tasks), atomic_read(&dev->depth_left),
1037                 dev->queue_depth);
1038         *bl += sprintf(b + *bl, "  SectorSize: %u  MaxSectors: %u\n",
1039                 dev->se_sub_dev->se_dev_attrib.block_size, dev->se_sub_dev->se_dev_attrib.max_sectors);
1040         *bl += sprintf(b + *bl, "        ");
1041 }
1042
1043 void transport_dump_vpd_proto_id(
1044         struct t10_vpd *vpd,
1045         unsigned char *p_buf,
1046         int p_buf_len)
1047 {
1048         unsigned char buf[VPD_TMP_BUF_SIZE];
1049         int len;
1050
1051         memset(buf, 0, VPD_TMP_BUF_SIZE);
1052         len = sprintf(buf, "T10 VPD Protocol Identifier: ");
1053
1054         switch (vpd->protocol_identifier) {
1055         case 0x00:
1056                 sprintf(buf+len, "Fibre Channel\n");
1057                 break;
1058         case 0x10:
1059                 sprintf(buf+len, "Parallel SCSI\n");
1060                 break;
1061         case 0x20:
1062                 sprintf(buf+len, "SSA\n");
1063                 break;
1064         case 0x30:
1065                 sprintf(buf+len, "IEEE 1394\n");
1066                 break;
1067         case 0x40:
1068                 sprintf(buf+len, "SCSI Remote Direct Memory Access"
1069                                 " Protocol\n");
1070                 break;
1071         case 0x50:
1072                 sprintf(buf+len, "Internet SCSI (iSCSI)\n");
1073                 break;
1074         case 0x60:
1075                 sprintf(buf+len, "SAS Serial SCSI Protocol\n");
1076                 break;
1077         case 0x70:
1078                 sprintf(buf+len, "Automation/Drive Interface Transport"
1079                                 " Protocol\n");
1080                 break;
1081         case 0x80:
1082                 sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
1083                 break;
1084         default:
1085                 sprintf(buf+len, "Unknown 0x%02x\n",
1086                                 vpd->protocol_identifier);
1087                 break;
1088         }
1089
1090         if (p_buf)
1091                 strncpy(p_buf, buf, p_buf_len);
1092         else
1093                 pr_debug("%s", buf);
1094 }
1095
1096 void
1097 transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
1098 {
1099         /*
1100          * Check if the Protocol Identifier Valid (PIV) bit is set..
1101          *
1102          * from spc3r23.pdf section 7.5.1
1103          */
1104          if (page_83[1] & 0x80) {
1105                 vpd->protocol_identifier = (page_83[0] & 0xf0);
1106                 vpd->protocol_identifier_set = 1;
1107                 transport_dump_vpd_proto_id(vpd, NULL, 0);
1108         }
1109 }
1110 EXPORT_SYMBOL(transport_set_vpd_proto_id);
1111
1112 int transport_dump_vpd_assoc(
1113         struct t10_vpd *vpd,
1114         unsigned char *p_buf,
1115         int p_buf_len)
1116 {
1117         unsigned char buf[VPD_TMP_BUF_SIZE];
1118         int ret = 0;
1119         int len;
1120
1121         memset(buf, 0, VPD_TMP_BUF_SIZE);
1122         len = sprintf(buf, "T10 VPD Identifier Association: ");
1123
1124         switch (vpd->association) {
1125         case 0x00:
1126                 sprintf(buf+len, "addressed logical unit\n");
1127                 break;
1128         case 0x10:
1129                 sprintf(buf+len, "target port\n");
1130                 break;
1131         case 0x20:
1132                 sprintf(buf+len, "SCSI target device\n");
1133                 break;
1134         default:
1135                 sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
1136                 ret = -EINVAL;
1137                 break;
1138         }
1139
1140         if (p_buf)
1141                 strncpy(p_buf, buf, p_buf_len);
1142         else
1143                 pr_debug("%s", buf);
1144
1145         return ret;
1146 }
1147
1148 int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
1149 {
1150         /*
1151          * The VPD identification association..
1152          *
1153          * from spc3r23.pdf Section 7.6.3.1 Table 297
1154          */
1155         vpd->association = (page_83[1] & 0x30);
1156         return transport_dump_vpd_assoc(vpd, NULL, 0);
1157 }
1158 EXPORT_SYMBOL(transport_set_vpd_assoc);
1159
1160 int transport_dump_vpd_ident_type(
1161         struct t10_vpd *vpd,
1162         unsigned char *p_buf,
1163         int p_buf_len)
1164 {
1165         unsigned char buf[VPD_TMP_BUF_SIZE];
1166         int ret = 0;
1167         int len;
1168
1169         memset(buf, 0, VPD_TMP_BUF_SIZE);
1170         len = sprintf(buf, "T10 VPD Identifier Type: ");
1171
1172         switch (vpd->device_identifier_type) {
1173         case 0x00:
1174                 sprintf(buf+len, "Vendor specific\n");
1175                 break;
1176         case 0x01:
1177                 sprintf(buf+len, "T10 Vendor ID based\n");
1178                 break;
1179         case 0x02:
1180                 sprintf(buf+len, "EUI-64 based\n");
1181                 break;
1182         case 0x03:
1183                 sprintf(buf+len, "NAA\n");
1184                 break;
1185         case 0x04:
1186                 sprintf(buf+len, "Relative target port identifier\n");
1187                 break;
1188         case 0x08:
1189                 sprintf(buf+len, "SCSI name string\n");
1190                 break;
1191         default:
1192                 sprintf(buf+len, "Unsupported: 0x%02x\n",
1193                                 vpd->device_identifier_type);
1194                 ret = -EINVAL;
1195                 break;
1196         }
1197
1198         if (p_buf) {
1199                 if (p_buf_len < strlen(buf)+1)
1200                         return -EINVAL;
1201                 strncpy(p_buf, buf, p_buf_len);
1202         } else {
1203                 pr_debug("%s", buf);
1204         }
1205
1206         return ret;
1207 }
1208
1209 int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
1210 {
1211         /*
1212          * The VPD identifier type..
1213          *
1214          * from spc3r23.pdf Section 7.6.3.1 Table 298
1215          */
1216         vpd->device_identifier_type = (page_83[1] & 0x0f);
1217         return transport_dump_vpd_ident_type(vpd, NULL, 0);
1218 }
1219 EXPORT_SYMBOL(transport_set_vpd_ident_type);
1220
1221 int transport_dump_vpd_ident(
1222         struct t10_vpd *vpd,
1223         unsigned char *p_buf,
1224         int p_buf_len)
1225 {
1226         unsigned char buf[VPD_TMP_BUF_SIZE];
1227         int ret = 0;
1228
1229         memset(buf, 0, VPD_TMP_BUF_SIZE);
1230
1231         switch (vpd->device_identifier_code_set) {
1232         case 0x01: /* Binary */
1233                 sprintf(buf, "T10 VPD Binary Device Identifier: %s\n",
1234                         &vpd->device_identifier[0]);
1235                 break;
1236         case 0x02: /* ASCII */
1237                 sprintf(buf, "T10 VPD ASCII Device Identifier: %s\n",
1238                         &vpd->device_identifier[0]);
1239                 break;
1240         case 0x03: /* UTF-8 */
1241                 sprintf(buf, "T10 VPD UTF-8 Device Identifier: %s\n",
1242                         &vpd->device_identifier[0]);
1243                 break;
1244         default:
1245                 sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
1246                         " 0x%02x", vpd->device_identifier_code_set);
1247                 ret = -EINVAL;
1248                 break;
1249         }
1250
1251         if (p_buf)
1252                 strncpy(p_buf, buf, p_buf_len);
1253         else
1254                 pr_debug("%s", buf);
1255
1256         return ret;
1257 }
1258
1259 int
1260 transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
1261 {
1262         static const char hex_str[] = "0123456789abcdef";
1263         int j = 0, i = 4; /* offset to start of the identifer */
1264
1265         /*
1266          * The VPD Code Set (encoding)
1267          *
1268          * from spc3r23.pdf Section 7.6.3.1 Table 296
1269          */
1270         vpd->device_identifier_code_set = (page_83[0] & 0x0f);
1271         switch (vpd->device_identifier_code_set) {
1272         case 0x01: /* Binary */
1273                 vpd->device_identifier[j++] =
1274                                 hex_str[vpd->device_identifier_type];
1275                 while (i < (4 + page_83[3])) {
1276                         vpd->device_identifier[j++] =
1277                                 hex_str[(page_83[i] & 0xf0) >> 4];
1278                         vpd->device_identifier[j++] =
1279                                 hex_str[page_83[i] & 0x0f];
1280                         i++;
1281                 }
1282                 break;
1283         case 0x02: /* ASCII */
1284         case 0x03: /* UTF-8 */
1285                 while (i < (4 + page_83[3]))
1286                         vpd->device_identifier[j++] = page_83[i++];
1287                 break;
1288         default:
1289                 break;
1290         }
1291
1292         return transport_dump_vpd_ident(vpd, NULL, 0);
1293 }
1294 EXPORT_SYMBOL(transport_set_vpd_ident);
1295
1296 static void core_setup_task_attr_emulation(struct se_device *dev)
1297 {
1298         /*
1299          * If this device is from Target_Core_Mod/pSCSI, disable the
1300          * SAM Task Attribute emulation.
1301          *
1302          * This is currently not available in upsream Linux/SCSI Target
1303          * mode code, and is assumed to be disabled while using TCM/pSCSI.
1304          */
1305         if (dev->transport->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV) {
1306                 dev->dev_task_attr_type = SAM_TASK_ATTR_PASSTHROUGH;
1307                 return;
1308         }
1309
1310         dev->dev_task_attr_type = SAM_TASK_ATTR_EMULATED;
1311         pr_debug("%s: Using SAM_TASK_ATTR_EMULATED for SPC: 0x%02x"
1312                 " device\n", dev->transport->name,
1313                 dev->transport->get_device_rev(dev));
1314 }
1315
1316 static void scsi_dump_inquiry(struct se_device *dev)
1317 {
1318         struct t10_wwn *wwn = &dev->se_sub_dev->t10_wwn;
1319         int i, device_type;
1320         /*
1321          * Print Linux/SCSI style INQUIRY formatting to the kernel ring buffer
1322          */
1323         pr_debug("  Vendor: ");
1324         for (i = 0; i < 8; i++)
1325                 if (wwn->vendor[i] >= 0x20)
1326                         pr_debug("%c", wwn->vendor[i]);
1327                 else
1328                         pr_debug(" ");
1329
1330         pr_debug("  Model: ");
1331         for (i = 0; i < 16; i++)
1332                 if (wwn->model[i] >= 0x20)
1333                         pr_debug("%c", wwn->model[i]);
1334                 else
1335                         pr_debug(" ");
1336
1337         pr_debug("  Revision: ");
1338         for (i = 0; i < 4; i++)
1339                 if (wwn->revision[i] >= 0x20)
1340                         pr_debug("%c", wwn->revision[i]);
1341                 else
1342                         pr_debug(" ");
1343
1344         pr_debug("\n");
1345
1346         device_type = dev->transport->get_device_type(dev);
1347         pr_debug("  Type:   %s ", scsi_device_type(device_type));
1348         pr_debug("                 ANSI SCSI revision: %02x\n",
1349                                 dev->transport->get_device_rev(dev));
1350 }
1351
1352 struct se_device *transport_add_device_to_core_hba(
1353         struct se_hba *hba,
1354         struct se_subsystem_api *transport,
1355         struct se_subsystem_dev *se_dev,
1356         u32 device_flags,
1357         void *transport_dev,
1358         struct se_dev_limits *dev_limits,
1359         const char *inquiry_prod,
1360         const char *inquiry_rev)
1361 {
1362         int force_pt;
1363         struct se_device  *dev;
1364
1365         dev = kzalloc(sizeof(struct se_device), GFP_KERNEL);
1366         if (!dev) {
1367                 pr_err("Unable to allocate memory for se_dev_t\n");
1368                 return NULL;
1369         }
1370
1371         transport_init_queue_obj(&dev->dev_queue_obj);
1372         dev->dev_flags          = device_flags;
1373         dev->dev_status         |= TRANSPORT_DEVICE_DEACTIVATED;
1374         dev->dev_ptr            = transport_dev;
1375         dev->se_hba             = hba;
1376         dev->se_sub_dev         = se_dev;
1377         dev->transport          = transport;
1378         atomic_set(&dev->active_cmds, 0);
1379         INIT_LIST_HEAD(&dev->dev_list);
1380         INIT_LIST_HEAD(&dev->dev_sep_list);
1381         INIT_LIST_HEAD(&dev->dev_tmr_list);
1382         INIT_LIST_HEAD(&dev->execute_task_list);
1383         INIT_LIST_HEAD(&dev->delayed_cmd_list);
1384         INIT_LIST_HEAD(&dev->ordered_cmd_list);
1385         INIT_LIST_HEAD(&dev->state_task_list);
1386         INIT_LIST_HEAD(&dev->qf_cmd_list);
1387         spin_lock_init(&dev->execute_task_lock);
1388         spin_lock_init(&dev->delayed_cmd_lock);
1389         spin_lock_init(&dev->ordered_cmd_lock);
1390         spin_lock_init(&dev->state_task_lock);
1391         spin_lock_init(&dev->dev_alua_lock);
1392         spin_lock_init(&dev->dev_reservation_lock);
1393         spin_lock_init(&dev->dev_status_lock);
1394         spin_lock_init(&dev->dev_status_thr_lock);
1395         spin_lock_init(&dev->se_port_lock);
1396         spin_lock_init(&dev->se_tmr_lock);
1397         spin_lock_init(&dev->qf_cmd_lock);
1398
1399         dev->queue_depth        = dev_limits->queue_depth;
1400         atomic_set(&dev->depth_left, dev->queue_depth);
1401         atomic_set(&dev->dev_ordered_id, 0);
1402
1403         se_dev_set_default_attribs(dev, dev_limits);
1404
1405         dev->dev_index = scsi_get_new_index(SCSI_DEVICE_INDEX);
1406         dev->creation_time = get_jiffies_64();
1407         spin_lock_init(&dev->stats_lock);
1408
1409         spin_lock(&hba->device_lock);
1410         list_add_tail(&dev->dev_list, &hba->hba_dev_list);
1411         hba->dev_count++;
1412         spin_unlock(&hba->device_lock);
1413         /*
1414          * Setup the SAM Task Attribute emulation for struct se_device
1415          */
1416         core_setup_task_attr_emulation(dev);
1417         /*
1418          * Force PR and ALUA passthrough emulation with internal object use.
1419          */
1420         force_pt = (hba->hba_flags & HBA_FLAGS_INTERNAL_USE);
1421         /*
1422          * Setup the Reservations infrastructure for struct se_device
1423          */
1424         core_setup_reservations(dev, force_pt);
1425         /*
1426          * Setup the Asymmetric Logical Unit Assignment for struct se_device
1427          */
1428         if (core_setup_alua(dev, force_pt) < 0)
1429                 goto out;
1430
1431         /*
1432          * Startup the struct se_device processing thread
1433          */
1434         dev->process_thread = kthread_run(transport_processing_thread, dev,
1435                                           "LIO_%s", dev->transport->name);
1436         if (IS_ERR(dev->process_thread)) {
1437                 pr_err("Unable to create kthread: LIO_%s\n",
1438                         dev->transport->name);
1439                 goto out;
1440         }
1441         /*
1442          * Setup work_queue for QUEUE_FULL
1443          */
1444         INIT_WORK(&dev->qf_work_queue, target_qf_do_work);
1445         /*
1446          * Preload the initial INQUIRY const values if we are doing
1447          * anything virtual (IBLOCK, FILEIO, RAMDISK), but not for TCM/pSCSI
1448          * passthrough because this is being provided by the backend LLD.
1449          * This is required so that transport_get_inquiry() copies these
1450          * originals once back into DEV_T10_WWN(dev) for the virtual device
1451          * setup.
1452          */
1453         if (dev->transport->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV) {
1454                 if (!inquiry_prod || !inquiry_rev) {
1455                         pr_err("All non TCM/pSCSI plugins require"
1456                                 " INQUIRY consts\n");
1457                         goto out;
1458                 }
1459
1460                 strncpy(&dev->se_sub_dev->t10_wwn.vendor[0], "LIO-ORG", 8);
1461                 strncpy(&dev->se_sub_dev->t10_wwn.model[0], inquiry_prod, 16);
1462                 strncpy(&dev->se_sub_dev->t10_wwn.revision[0], inquiry_rev, 4);
1463         }
1464         scsi_dump_inquiry(dev);
1465
1466         return dev;
1467 out:
1468         kthread_stop(dev->process_thread);
1469
1470         spin_lock(&hba->device_lock);
1471         list_del(&dev->dev_list);
1472         hba->dev_count--;
1473         spin_unlock(&hba->device_lock);
1474
1475         se_release_vpd_for_dev(dev);
1476
1477         kfree(dev);
1478
1479         return NULL;
1480 }
1481 EXPORT_SYMBOL(transport_add_device_to_core_hba);
1482
1483 /*      transport_generic_prepare_cdb():
1484  *
1485  *      Since the Initiator sees iSCSI devices as LUNs,  the SCSI CDB will
1486  *      contain the iSCSI LUN in bits 7-5 of byte 1 as per SAM-2.
1487  *      The point of this is since we are mapping iSCSI LUNs to
1488  *      SCSI Target IDs having a non-zero LUN in the CDB will throw the
1489  *      devices and HBAs for a loop.
1490  */
1491 static inline void transport_generic_prepare_cdb(
1492         unsigned char *cdb)
1493 {
1494         switch (cdb[0]) {
1495         case READ_10: /* SBC - RDProtect */
1496         case READ_12: /* SBC - RDProtect */
1497         case READ_16: /* SBC - RDProtect */
1498         case SEND_DIAGNOSTIC: /* SPC - SELF-TEST Code */
1499         case VERIFY: /* SBC - VRProtect */
1500         case VERIFY_16: /* SBC - VRProtect */
1501         case WRITE_VERIFY: /* SBC - VRProtect */
1502         case WRITE_VERIFY_12: /* SBC - VRProtect */
1503                 break;
1504         default:
1505                 cdb[1] &= 0x1f; /* clear logical unit number */
1506                 break;
1507         }
1508 }
1509
1510 static struct se_task *
1511 transport_generic_get_task(struct se_cmd *cmd,
1512                 enum dma_data_direction data_direction)
1513 {
1514         struct se_task *task;
1515         struct se_device *dev = cmd->se_dev;
1516
1517         task = dev->transport->alloc_task(cmd->t_task_cdb);
1518         if (!task) {
1519                 pr_err("Unable to allocate struct se_task\n");
1520                 return NULL;
1521         }
1522
1523         INIT_LIST_HEAD(&task->t_list);
1524         INIT_LIST_HEAD(&task->t_execute_list);
1525         INIT_LIST_HEAD(&task->t_state_list);
1526         init_timer(&task->task_timer);
1527         init_completion(&task->task_stop_comp);
1528         task->task_se_cmd = cmd;
1529         task->task_data_direction = data_direction;
1530
1531         return task;
1532 }
1533
1534 static int transport_generic_cmd_sequencer(struct se_cmd *, unsigned char *);
1535
1536 /*
1537  * Used by fabric modules containing a local struct se_cmd within their
1538  * fabric dependent per I/O descriptor.
1539  */
1540 void transport_init_se_cmd(
1541         struct se_cmd *cmd,
1542         struct target_core_fabric_ops *tfo,
1543         struct se_session *se_sess,
1544         u32 data_length,
1545         int data_direction,
1546         int task_attr,
1547         unsigned char *sense_buffer)
1548 {
1549         INIT_LIST_HEAD(&cmd->se_lun_node);
1550         INIT_LIST_HEAD(&cmd->se_delayed_node);
1551         INIT_LIST_HEAD(&cmd->se_ordered_node);
1552         INIT_LIST_HEAD(&cmd->se_qf_node);
1553         INIT_LIST_HEAD(&cmd->se_queue_node);
1554
1555         INIT_LIST_HEAD(&cmd->t_task_list);
1556         init_completion(&cmd->transport_lun_fe_stop_comp);
1557         init_completion(&cmd->transport_lun_stop_comp);
1558         init_completion(&cmd->t_transport_stop_comp);
1559         spin_lock_init(&cmd->t_state_lock);
1560         atomic_set(&cmd->transport_dev_active, 1);
1561
1562         cmd->se_tfo = tfo;
1563         cmd->se_sess = se_sess;
1564         cmd->data_length = data_length;
1565         cmd->data_direction = data_direction;
1566         cmd->sam_task_attr = task_attr;
1567         cmd->sense_buffer = sense_buffer;
1568 }
1569 EXPORT_SYMBOL(transport_init_se_cmd);
1570
1571 static int transport_check_alloc_task_attr(struct se_cmd *cmd)
1572 {
1573         /*
1574          * Check if SAM Task Attribute emulation is enabled for this
1575          * struct se_device storage object
1576          */
1577         if (cmd->se_dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
1578                 return 0;
1579
1580         if (cmd->sam_task_attr == MSG_ACA_TAG) {
1581                 pr_debug("SAM Task Attribute ACA"
1582                         " emulation is not supported\n");
1583                 return -EINVAL;
1584         }
1585         /*
1586          * Used to determine when ORDERED commands should go from
1587          * Dormant to Active status.
1588          */
1589         cmd->se_ordered_id = atomic_inc_return(&cmd->se_dev->dev_ordered_id);
1590         smp_mb__after_atomic_inc();
1591         pr_debug("Allocated se_ordered_id: %u for Task Attr: 0x%02x on %s\n",
1592                         cmd->se_ordered_id, cmd->sam_task_attr,
1593                         cmd->se_dev->transport->name);
1594         return 0;
1595 }
1596
1597 /*      transport_generic_allocate_tasks():
1598  *
1599  *      Called from fabric RX Thread.
1600  */
1601 int transport_generic_allocate_tasks(
1602         struct se_cmd *cmd,
1603         unsigned char *cdb)
1604 {
1605         int ret;
1606
1607         transport_generic_prepare_cdb(cdb);
1608         /*
1609          * Ensure that the received CDB is less than the max (252 + 8) bytes
1610          * for VARIABLE_LENGTH_CMD
1611          */
1612         if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
1613                 pr_err("Received SCSI CDB with command_size: %d that"
1614                         " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1615                         scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
1616                 return -EINVAL;
1617         }
1618         /*
1619          * If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
1620          * allocate the additional extended CDB buffer now..  Otherwise
1621          * setup the pointer from __t_task_cdb to t_task_cdb.
1622          */
1623         if (scsi_command_size(cdb) > sizeof(cmd->__t_task_cdb)) {
1624                 cmd->t_task_cdb = kzalloc(scsi_command_size(cdb),
1625                                                 GFP_KERNEL);
1626                 if (!cmd->t_task_cdb) {
1627                         pr_err("Unable to allocate cmd->t_task_cdb"
1628                                 " %u > sizeof(cmd->__t_task_cdb): %lu ops\n",
1629                                 scsi_command_size(cdb),
1630                                 (unsigned long)sizeof(cmd->__t_task_cdb));
1631                         return -ENOMEM;
1632                 }
1633         } else
1634                 cmd->t_task_cdb = &cmd->__t_task_cdb[0];
1635         /*
1636          * Copy the original CDB into cmd->
1637          */
1638         memcpy(cmd->t_task_cdb, cdb, scsi_command_size(cdb));
1639         /*
1640          * Setup the received CDB based on SCSI defined opcodes and
1641          * perform unit attention, persistent reservations and ALUA
1642          * checks for virtual device backends.  The cmd->t_task_cdb
1643          * pointer is expected to be setup before we reach this point.
1644          */
1645         ret = transport_generic_cmd_sequencer(cmd, cdb);
1646         if (ret < 0)
1647                 return ret;
1648         /*
1649          * Check for SAM Task Attribute Emulation
1650          */
1651         if (transport_check_alloc_task_attr(cmd) < 0) {
1652                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1653                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1654                 return -EINVAL;
1655         }
1656         spin_lock(&cmd->se_lun->lun_sep_lock);
1657         if (cmd->se_lun->lun_sep)
1658                 cmd->se_lun->lun_sep->sep_stats.cmd_pdus++;
1659         spin_unlock(&cmd->se_lun->lun_sep_lock);
1660         return 0;
1661 }
1662 EXPORT_SYMBOL(transport_generic_allocate_tasks);
1663
1664 /*
1665  * Used by fabric module frontends to queue tasks directly.
1666  * Many only be used from process context only
1667  */
1668 int transport_handle_cdb_direct(
1669         struct se_cmd *cmd)
1670 {
1671         int ret;
1672
1673         if (!cmd->se_lun) {
1674                 dump_stack();
1675                 pr_err("cmd->se_lun is NULL\n");
1676                 return -EINVAL;
1677         }
1678         if (in_interrupt()) {
1679                 dump_stack();
1680                 pr_err("transport_generic_handle_cdb cannot be called"
1681                                 " from interrupt context\n");
1682                 return -EINVAL;
1683         }
1684         /*
1685          * Set TRANSPORT_NEW_CMD state and cmd->t_transport_active=1 following
1686          * transport_generic_handle_cdb*() -> transport_add_cmd_to_queue()
1687          * in existing usage to ensure that outstanding descriptors are handled
1688          * correctly during shutdown via transport_wait_for_tasks()
1689          *
1690          * Also, we don't take cmd->t_state_lock here as we only expect
1691          * this to be called for initial descriptor submission.
1692          */
1693         cmd->t_state = TRANSPORT_NEW_CMD;
1694         atomic_set(&cmd->t_transport_active, 1);
1695         /*
1696          * transport_generic_new_cmd() is already handling QUEUE_FULL,
1697          * so follow TRANSPORT_NEW_CMD processing thread context usage
1698          * and call transport_generic_request_failure() if necessary..
1699          */
1700         ret = transport_generic_new_cmd(cmd);
1701         if (ret == -EAGAIN)
1702                 return 0;
1703         else if (ret < 0) {
1704                 cmd->transport_error_status = ret;
1705                 transport_generic_request_failure(cmd, 0,
1706                                 (cmd->data_direction != DMA_TO_DEVICE));
1707         }
1708         return 0;
1709 }
1710 EXPORT_SYMBOL(transport_handle_cdb_direct);
1711
1712 /*
1713  * Used by fabric module frontends defining a TFO->new_cmd_map() caller
1714  * to  queue up a newly setup se_cmd w/ TRANSPORT_NEW_CMD_MAP in order to
1715  * complete setup in TCM process context w/ TFO->new_cmd_map().
1716  */
1717 int transport_generic_handle_cdb_map(
1718         struct se_cmd *cmd)
1719 {
1720         if (!cmd->se_lun) {
1721                 dump_stack();
1722                 pr_err("cmd->se_lun is NULL\n");
1723                 return -EINVAL;
1724         }
1725
1726         transport_add_cmd_to_queue(cmd, TRANSPORT_NEW_CMD_MAP, false);
1727         return 0;
1728 }
1729 EXPORT_SYMBOL(transport_generic_handle_cdb_map);
1730
1731 /*      transport_generic_handle_data():
1732  *
1733  *
1734  */
1735 int transport_generic_handle_data(
1736         struct se_cmd *cmd)
1737 {
1738         /*
1739          * For the software fabric case, then we assume the nexus is being
1740          * failed/shutdown when signals are pending from the kthread context
1741          * caller, so we return a failure.  For the HW target mode case running
1742          * in interrupt code, the signal_pending() check is skipped.
1743          */
1744         if (!in_interrupt() && signal_pending(current))
1745                 return -EPERM;
1746         /*
1747          * If the received CDB has aleady been ABORTED by the generic
1748          * target engine, we now call transport_check_aborted_status()
1749          * to queue any delated TASK_ABORTED status for the received CDB to the
1750          * fabric module as we are expecting no further incoming DATA OUT
1751          * sequences at this point.
1752          */
1753         if (transport_check_aborted_status(cmd, 1) != 0)
1754                 return 0;
1755
1756         transport_add_cmd_to_queue(cmd, TRANSPORT_PROCESS_WRITE, false);
1757         return 0;
1758 }
1759 EXPORT_SYMBOL(transport_generic_handle_data);
1760
1761 /*      transport_generic_handle_tmr():
1762  *
1763  *
1764  */
1765 int transport_generic_handle_tmr(
1766         struct se_cmd *cmd)
1767 {
1768         transport_add_cmd_to_queue(cmd, TRANSPORT_PROCESS_TMR, false);
1769         return 0;
1770 }
1771 EXPORT_SYMBOL(transport_generic_handle_tmr);
1772
1773 void transport_generic_free_cmd_intr(
1774         struct se_cmd *cmd)
1775 {
1776         transport_add_cmd_to_queue(cmd, TRANSPORT_FREE_CMD_INTR, false);
1777 }
1778 EXPORT_SYMBOL(transport_generic_free_cmd_intr);
1779
1780 /*
1781  * If the task is active, request it to be stopped and sleep until it
1782  * has completed.
1783  */
1784 bool target_stop_task(struct se_task *task, unsigned long *flags)
1785 {
1786         struct se_cmd *cmd = task->task_se_cmd;
1787         bool was_active = false;
1788
1789         if (task->task_flags & TF_ACTIVE) {
1790                 task->task_flags |= TF_REQUEST_STOP;
1791                 spin_unlock_irqrestore(&cmd->t_state_lock, *flags);
1792
1793                 pr_debug("Task %p waiting to complete\n", task);
1794                 del_timer_sync(&task->task_timer);
1795                 wait_for_completion(&task->task_stop_comp);
1796                 pr_debug("Task %p stopped successfully\n", task);
1797
1798                 spin_lock_irqsave(&cmd->t_state_lock, *flags);
1799                 atomic_dec(&cmd->t_task_cdbs_left);
1800                 task->task_flags &= ~(TF_ACTIVE | TF_REQUEST_STOP);
1801                 was_active = true;
1802         }
1803
1804         return was_active;
1805 }
1806
1807 static int transport_stop_tasks_for_cmd(struct se_cmd *cmd)
1808 {
1809         struct se_task *task, *task_tmp;
1810         unsigned long flags;
1811         int ret = 0;
1812
1813         pr_debug("ITT[0x%08x] - Stopping tasks\n",
1814                 cmd->se_tfo->get_task_tag(cmd));
1815
1816         /*
1817          * No tasks remain in the execution queue
1818          */
1819         spin_lock_irqsave(&cmd->t_state_lock, flags);
1820         list_for_each_entry_safe(task, task_tmp,
1821                                 &cmd->t_task_list, t_list) {
1822                 pr_debug("Processing task %p\n", task);
1823                 /*
1824                  * If the struct se_task has not been sent and is not active,
1825                  * remove the struct se_task from the execution queue.
1826                  */
1827                 if (!(task->task_flags & (TF_ACTIVE | TF_SENT))) {
1828                         spin_unlock_irqrestore(&cmd->t_state_lock,
1829                                         flags);
1830                         transport_remove_task_from_execute_queue(task,
1831                                         cmd->se_dev);
1832
1833                         pr_debug("Task %p removed from execute queue\n", task);
1834                         spin_lock_irqsave(&cmd->t_state_lock, flags);
1835                         continue;
1836                 }
1837
1838                 if (!target_stop_task(task, &flags)) {
1839                         pr_debug("Task %p - did nothing\n", task);
1840                         ret++;
1841                 }
1842         }
1843         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
1844
1845         return ret;
1846 }
1847
1848 /*
1849  * Handle SAM-esque emulation for generic transport request failures.
1850  */
1851 static void transport_generic_request_failure(
1852         struct se_cmd *cmd,
1853         int complete,
1854         int sc)
1855 {
1856         int ret = 0;
1857
1858         pr_debug("-----[ Storage Engine Exception for cmd: %p ITT: 0x%08x"
1859                 " CDB: 0x%02x\n", cmd, cmd->se_tfo->get_task_tag(cmd),
1860                 cmd->t_task_cdb[0]);
1861         pr_debug("-----[ i_state: %d t_state: %d transport_error_status: %d\n",
1862                 cmd->se_tfo->get_cmd_state(cmd),
1863                 cmd->t_state,
1864                 cmd->transport_error_status);
1865         pr_debug("-----[ t_tasks: %d t_task_cdbs_left: %d"
1866                 " t_task_cdbs_sent: %d t_task_cdbs_ex_left: %d --"
1867                 " t_transport_active: %d t_transport_stop: %d"
1868                 " t_transport_sent: %d\n", cmd->t_task_list_num,
1869                 atomic_read(&cmd->t_task_cdbs_left),
1870                 atomic_read(&cmd->t_task_cdbs_sent),
1871                 atomic_read(&cmd->t_task_cdbs_ex_left),
1872                 atomic_read(&cmd->t_transport_active),
1873                 atomic_read(&cmd->t_transport_stop),
1874                 atomic_read(&cmd->t_transport_sent));
1875
1876         /*
1877          * For SAM Task Attribute emulation for failed struct se_cmd
1878          */
1879         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
1880                 transport_complete_task_attr(cmd);
1881
1882         if (complete) {
1883                 transport_direct_request_timeout(cmd);
1884                 cmd->transport_error_status = PYX_TRANSPORT_LU_COMM_FAILURE;
1885         }
1886
1887         switch (cmd->transport_error_status) {
1888         case PYX_TRANSPORT_UNKNOWN_SAM_OPCODE:
1889                 cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
1890                 break;
1891         case PYX_TRANSPORT_REQ_TOO_MANY_SECTORS:
1892                 cmd->scsi_sense_reason = TCM_SECTOR_COUNT_TOO_MANY;
1893                 break;
1894         case PYX_TRANSPORT_INVALID_CDB_FIELD:
1895                 cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1896                 break;
1897         case PYX_TRANSPORT_INVALID_PARAMETER_LIST:
1898                 cmd->scsi_sense_reason = TCM_INVALID_PARAMETER_LIST;
1899                 break;
1900         case PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES:
1901                 if (!sc)
1902                         transport_new_cmd_failure(cmd);
1903                 /*
1904                  * Currently for PYX_TRANSPORT_OUT_OF_MEMORY_RESOURCES,
1905                  * we force this session to fall back to session
1906                  * recovery.
1907                  */
1908                 cmd->se_tfo->fall_back_to_erl0(cmd->se_sess);
1909                 cmd->se_tfo->stop_session(cmd->se_sess, 0, 0);
1910
1911                 goto check_stop;
1912         case PYX_TRANSPORT_LU_COMM_FAILURE:
1913         case PYX_TRANSPORT_ILLEGAL_REQUEST:
1914                 cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1915                 break;
1916         case PYX_TRANSPORT_UNKNOWN_MODE_PAGE:
1917                 cmd->scsi_sense_reason = TCM_UNKNOWN_MODE_PAGE;
1918                 break;
1919         case PYX_TRANSPORT_WRITE_PROTECTED:
1920                 cmd->scsi_sense_reason = TCM_WRITE_PROTECTED;
1921                 break;
1922         case PYX_TRANSPORT_RESERVATION_CONFLICT:
1923                 /*
1924                  * No SENSE Data payload for this case, set SCSI Status
1925                  * and queue the response to $FABRIC_MOD.
1926                  *
1927                  * Uses linux/include/scsi/scsi.h SAM status codes defs
1928                  */
1929                 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1930                 /*
1931                  * For UA Interlock Code 11b, a RESERVATION CONFLICT will
1932                  * establish a UNIT ATTENTION with PREVIOUS RESERVATION
1933                  * CONFLICT STATUS.
1934                  *
1935                  * See spc4r17, section 7.4.6 Control Mode Page, Table 349
1936                  */
1937                 if (cmd->se_sess &&
1938                     cmd->se_dev->se_sub_dev->se_dev_attrib.emulate_ua_intlck_ctrl == 2)
1939                         core_scsi3_ua_allocate(cmd->se_sess->se_node_acl,
1940                                 cmd->orig_fe_lun, 0x2C,
1941                                 ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
1942
1943                 ret = cmd->se_tfo->queue_status(cmd);
1944                 if (ret == -EAGAIN)
1945                         goto queue_full;
1946                 goto check_stop;
1947         case PYX_TRANSPORT_USE_SENSE_REASON:
1948                 /*
1949                  * struct se_cmd->scsi_sense_reason already set
1950                  */
1951                 break;
1952         default:
1953                 pr_err("Unknown transport error for CDB 0x%02x: %d\n",
1954                         cmd->t_task_cdb[0],
1955                         cmd->transport_error_status);
1956                 cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
1957                 break;
1958         }
1959         /*
1960          * If a fabric does not define a cmd->se_tfo->new_cmd_map caller,
1961          * make the call to transport_send_check_condition_and_sense()
1962          * directly.  Otherwise expect the fabric to make the call to
1963          * transport_send_check_condition_and_sense() after handling
1964          * possible unsoliticied write data payloads.
1965          */
1966         if (!sc && !cmd->se_tfo->new_cmd_map)
1967                 transport_new_cmd_failure(cmd);
1968         else {
1969                 ret = transport_send_check_condition_and_sense(cmd,
1970                                 cmd->scsi_sense_reason, 0);
1971                 if (ret == -EAGAIN)
1972                         goto queue_full;
1973         }
1974
1975 check_stop:
1976         transport_lun_remove_cmd(cmd);
1977         if (!transport_cmd_check_stop_to_fabric(cmd))
1978                 ;
1979         return;
1980
1981 queue_full:
1982         cmd->t_state = TRANSPORT_COMPLETE_QF_OK;
1983         transport_handle_queue_full(cmd, cmd->se_dev);
1984 }
1985
1986 static void transport_direct_request_timeout(struct se_cmd *cmd)
1987 {
1988         unsigned long flags;
1989
1990         spin_lock_irqsave(&cmd->t_state_lock, flags);
1991         if (!atomic_read(&cmd->t_transport_timeout)) {
1992                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
1993                 return;
1994         }
1995         if (atomic_read(&cmd->t_task_cdbs_timeout_left)) {
1996                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
1997                 return;
1998         }
1999
2000         atomic_sub(atomic_read(&cmd->t_transport_timeout),
2001                    &cmd->t_se_count);
2002         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2003 }
2004
2005 static inline u32 transport_lba_21(unsigned char *cdb)
2006 {
2007         return ((cdb[1] & 0x1f) << 16) | (cdb[2] << 8) | cdb[3];
2008 }
2009
2010 static inline u32 transport_lba_32(unsigned char *cdb)
2011 {
2012         return (cdb[2] << 24) | (cdb[3] << 16) | (cdb[4] << 8) | cdb[5];
2013 }
2014
2015 static inline unsigned long long transport_lba_64(unsigned char *cdb)
2016 {
2017         unsigned int __v1, __v2;
2018
2019         __v1 = (cdb[2] << 24) | (cdb[3] << 16) | (cdb[4] << 8) | cdb[5];
2020         __v2 = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
2021
2022         return ((unsigned long long)__v2) | (unsigned long long)__v1 << 32;
2023 }
2024
2025 /*
2026  * For VARIABLE_LENGTH_CDB w/ 32 byte extended CDBs
2027  */
2028 static inline unsigned long long transport_lba_64_ext(unsigned char *cdb)
2029 {
2030         unsigned int __v1, __v2;
2031
2032         __v1 = (cdb[12] << 24) | (cdb[13] << 16) | (cdb[14] << 8) | cdb[15];
2033         __v2 = (cdb[16] << 24) | (cdb[17] << 16) | (cdb[18] << 8) | cdb[19];
2034
2035         return ((unsigned long long)__v2) | (unsigned long long)__v1 << 32;
2036 }
2037
2038 static void transport_set_supported_SAM_opcode(struct se_cmd *se_cmd)
2039 {
2040         unsigned long flags;
2041
2042         spin_lock_irqsave(&se_cmd->t_state_lock, flags);
2043         se_cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
2044         spin_unlock_irqrestore(&se_cmd->t_state_lock, flags);
2045 }
2046
2047 /*
2048  * Called from interrupt context.
2049  */
2050 static void transport_task_timeout_handler(unsigned long data)
2051 {
2052         struct se_task *task = (struct se_task *)data;
2053         struct se_cmd *cmd = task->task_se_cmd;
2054         unsigned long flags;
2055
2056         pr_debug("transport task timeout fired! task: %p cmd: %p\n", task, cmd);
2057
2058         spin_lock_irqsave(&cmd->t_state_lock, flags);
2059
2060         /*
2061          * Determine if transport_complete_task() has already been called.
2062          */
2063         if (!(task->task_flags & TF_ACTIVE)) {
2064                 pr_debug("transport task: %p cmd: %p timeout !TF_ACTIVE\n",
2065                          task, cmd);
2066                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2067                 return;
2068         }
2069
2070         atomic_inc(&cmd->t_se_count);
2071         atomic_inc(&cmd->t_transport_timeout);
2072         cmd->t_tasks_failed = 1;
2073
2074         task->task_flags |= TF_TIMEOUT;
2075         task->task_error_status = PYX_TRANSPORT_TASK_TIMEOUT;
2076         task->task_scsi_status = 1;
2077
2078         if (task->task_flags & TF_REQUEST_STOP) {
2079                 pr_debug("transport task: %p cmd: %p timeout TF_REQUEST_STOP"
2080                                 " == 1\n", task, cmd);
2081                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2082                 complete(&task->task_stop_comp);
2083                 return;
2084         }
2085
2086         if (!atomic_dec_and_test(&cmd->t_task_cdbs_left)) {
2087                 pr_debug("transport task: %p cmd: %p timeout non zero"
2088                                 " t_task_cdbs_left\n", task, cmd);
2089                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2090                 return;
2091         }
2092         pr_debug("transport task: %p cmd: %p timeout ZERO t_task_cdbs_left\n",
2093                         task, cmd);
2094
2095         INIT_WORK(&cmd->work, target_complete_failure_work);
2096         cmd->t_state = TRANSPORT_COMPLETE;
2097         atomic_set(&cmd->t_transport_active, 1);
2098         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2099
2100         queue_work(target_completion_wq, &cmd->work);
2101 }
2102
2103 static void transport_start_task_timer(struct se_task *task)
2104 {
2105         struct se_device *dev = task->task_se_cmd->se_dev;
2106         int timeout;
2107
2108         /*
2109          * If the task_timeout is disabled, exit now.
2110          */
2111         timeout = dev->se_sub_dev->se_dev_attrib.task_timeout;
2112         if (!timeout)
2113                 return;
2114
2115         task->task_timer.expires = (get_jiffies_64() + timeout * HZ);
2116         task->task_timer.data = (unsigned long) task;
2117         task->task_timer.function = transport_task_timeout_handler;
2118         add_timer(&task->task_timer);
2119 }
2120
2121 static inline int transport_tcq_window_closed(struct se_device *dev)
2122 {
2123         if (dev->dev_tcq_window_closed++ <
2124                         PYX_TRANSPORT_WINDOW_CLOSED_THRESHOLD) {
2125                 msleep(PYX_TRANSPORT_WINDOW_CLOSED_WAIT_SHORT);
2126         } else
2127                 msleep(PYX_TRANSPORT_WINDOW_CLOSED_WAIT_LONG);
2128
2129         wake_up_interruptible(&dev->dev_queue_obj.thread_wq);
2130         return 0;
2131 }
2132
2133 /*
2134  * Called from Fabric Module context from transport_execute_tasks()
2135  *
2136  * The return of this function determins if the tasks from struct se_cmd
2137  * get added to the execution queue in transport_execute_tasks(),
2138  * or are added to the delayed or ordered lists here.
2139  */
2140 static inline int transport_execute_task_attr(struct se_cmd *cmd)
2141 {
2142         if (cmd->se_dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
2143                 return 1;
2144         /*
2145          * Check for the existence of HEAD_OF_QUEUE, and if true return 1
2146          * to allow the passed struct se_cmd list of tasks to the front of the list.
2147          */
2148          if (cmd->sam_task_attr == MSG_HEAD_TAG) {
2149                 atomic_inc(&cmd->se_dev->dev_hoq_count);
2150                 smp_mb__after_atomic_inc();
2151                 pr_debug("Added HEAD_OF_QUEUE for CDB:"
2152                         " 0x%02x, se_ordered_id: %u\n",
2153                         cmd->t_task_cdb[0],
2154                         cmd->se_ordered_id);
2155                 return 1;
2156         } else if (cmd->sam_task_attr == MSG_ORDERED_TAG) {
2157                 spin_lock(&cmd->se_dev->ordered_cmd_lock);
2158                 list_add_tail(&cmd->se_ordered_node,
2159                                 &cmd->se_dev->ordered_cmd_list);
2160                 spin_unlock(&cmd->se_dev->ordered_cmd_lock);
2161
2162                 atomic_inc(&cmd->se_dev->dev_ordered_sync);
2163                 smp_mb__after_atomic_inc();
2164
2165                 pr_debug("Added ORDERED for CDB: 0x%02x to ordered"
2166                                 " list, se_ordered_id: %u\n",
2167                                 cmd->t_task_cdb[0],
2168                                 cmd->se_ordered_id);
2169                 /*
2170                  * Add ORDERED command to tail of execution queue if
2171                  * no other older commands exist that need to be
2172                  * completed first.
2173                  */
2174                 if (!atomic_read(&cmd->se_dev->simple_cmds))
2175                         return 1;
2176         } else {
2177                 /*
2178                  * For SIMPLE and UNTAGGED Task Attribute commands
2179                  */
2180                 atomic_inc(&cmd->se_dev->simple_cmds);
2181                 smp_mb__after_atomic_inc();
2182         }
2183         /*
2184          * Otherwise if one or more outstanding ORDERED task attribute exist,
2185          * add the dormant task(s) built for the passed struct se_cmd to the
2186          * execution queue and become in Active state for this struct se_device.
2187          */
2188         if (atomic_read(&cmd->se_dev->dev_ordered_sync) != 0) {
2189                 /*
2190                  * Otherwise, add cmd w/ tasks to delayed cmd queue that
2191                  * will be drained upon completion of HEAD_OF_QUEUE task.
2192                  */
2193                 spin_lock(&cmd->se_dev->delayed_cmd_lock);
2194                 cmd->se_cmd_flags |= SCF_DELAYED_CMD_FROM_SAM_ATTR;
2195                 list_add_tail(&cmd->se_delayed_node,
2196                                 &cmd->se_dev->delayed_cmd_list);
2197                 spin_unlock(&cmd->se_dev->delayed_cmd_lock);
2198
2199                 pr_debug("Added CDB: 0x%02x Task Attr: 0x%02x to"
2200                         " delayed CMD list, se_ordered_id: %u\n",
2201                         cmd->t_task_cdb[0], cmd->sam_task_attr,
2202                         cmd->se_ordered_id);
2203                 /*
2204                  * Return zero to let transport_execute_tasks() know
2205                  * not to add the delayed tasks to the execution list.
2206                  */
2207                 return 0;
2208         }
2209         /*
2210          * Otherwise, no ORDERED task attributes exist..
2211          */
2212         return 1;
2213 }
2214
2215 /*
2216  * Called from fabric module context in transport_generic_new_cmd() and
2217  * transport_generic_process_write()
2218  */
2219 static int transport_execute_tasks(struct se_cmd *cmd)
2220 {
2221         int add_tasks;
2222
2223         if (se_dev_check_online(cmd->se_orig_obj_ptr) != 0) {
2224                 cmd->transport_error_status = PYX_TRANSPORT_LU_COMM_FAILURE;
2225                 transport_generic_request_failure(cmd, 0, 1);
2226                 return 0;
2227         }
2228
2229         /*
2230          * Call transport_cmd_check_stop() to see if a fabric exception
2231          * has occurred that prevents execution.
2232          */
2233         if (!transport_cmd_check_stop(cmd, 0, TRANSPORT_PROCESSING)) {
2234                 /*
2235                  * Check for SAM Task Attribute emulation and HEAD_OF_QUEUE
2236                  * attribute for the tasks of the received struct se_cmd CDB
2237                  */
2238                 add_tasks = transport_execute_task_attr(cmd);
2239                 if (!add_tasks)
2240                         goto execute_tasks;
2241                 /*
2242                  * This calls transport_add_tasks_from_cmd() to handle
2243                  * HEAD_OF_QUEUE ordering for SAM Task Attribute emulation
2244                  * (if enabled) in __transport_add_task_to_execute_queue() and
2245                  * transport_add_task_check_sam_attr().
2246                  */
2247                 transport_add_tasks_from_cmd(cmd);
2248         }
2249         /*
2250          * Kick the execution queue for the cmd associated struct se_device
2251          * storage object.
2252          */
2253 execute_tasks:
2254         __transport_execute_tasks(cmd->se_dev);
2255         return 0;
2256 }
2257
2258 /*
2259  * Called to check struct se_device tcq depth window, and once open pull struct se_task
2260  * from struct se_device->execute_task_list and
2261  *
2262  * Called from transport_processing_thread()
2263  */
2264 static int __transport_execute_tasks(struct se_device *dev)
2265 {
2266         int error;
2267         struct se_cmd *cmd = NULL;
2268         struct se_task *task = NULL;
2269         unsigned long flags;
2270
2271         /*
2272          * Check if there is enough room in the device and HBA queue to send
2273          * struct se_tasks to the selected transport.
2274          */
2275 check_depth:
2276         if (!atomic_read(&dev->depth_left))
2277                 return transport_tcq_window_closed(dev);
2278
2279         dev->dev_tcq_window_closed = 0;
2280
2281         spin_lock_irq(&dev->execute_task_lock);
2282         if (list_empty(&dev->execute_task_list)) {
2283                 spin_unlock_irq(&dev->execute_task_lock);
2284                 return 0;
2285         }
2286         task = list_first_entry(&dev->execute_task_list,
2287                                 struct se_task, t_execute_list);
2288         __transport_remove_task_from_execute_queue(task, dev);
2289         spin_unlock_irq(&dev->execute_task_lock);
2290
2291         atomic_dec(&dev->depth_left);
2292
2293         cmd = task->task_se_cmd;
2294
2295         spin_lock_irqsave(&cmd->t_state_lock, flags);
2296         task->task_flags |= (TF_ACTIVE | TF_SENT);
2297         atomic_inc(&cmd->t_task_cdbs_sent);
2298
2299         if (atomic_read(&cmd->t_task_cdbs_sent) ==
2300             cmd->t_task_list_num)
2301                 atomic_set(&cmd->transport_sent, 1);
2302
2303         transport_start_task_timer(task);
2304         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2305         /*
2306          * The struct se_cmd->transport_emulate_cdb() function pointer is used
2307          * to grab REPORT_LUNS and other CDBs we want to handle before they hit the
2308          * struct se_subsystem_api->do_task() caller below.
2309          */
2310         if (cmd->transport_emulate_cdb) {
2311                 error = cmd->transport_emulate_cdb(cmd);
2312                 if (error != 0) {
2313                         cmd->transport_error_status = error;
2314                         spin_lock_irqsave(&cmd->t_state_lock, flags);
2315                         task->task_flags &= ~TF_ACTIVE;
2316                         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2317                         del_timer_sync(&task->task_timer);
2318                         atomic_set(&cmd->transport_sent, 0);
2319                         transport_stop_tasks_for_cmd(cmd);
2320                         atomic_inc(&dev->depth_left);
2321                         transport_generic_request_failure(cmd, 0, 1);
2322                         goto check_depth;
2323                 }
2324                 /*
2325                  * Handle the successful completion for transport_emulate_cdb()
2326                  * for synchronous operation, following SCF_EMULATE_CDB_ASYNC
2327                  * Otherwise the caller is expected to complete the task with
2328                  * proper status.
2329                  */
2330                 if (!(cmd->se_cmd_flags & SCF_EMULATE_CDB_ASYNC)) {
2331                         cmd->scsi_status = SAM_STAT_GOOD;
2332                         task->task_scsi_status = GOOD;
2333                         transport_complete_task(task, 1);
2334                 }
2335         } else {
2336                 /*
2337                  * Currently for all virtual TCM plugins including IBLOCK, FILEIO and
2338                  * RAMDISK we use the internal transport_emulate_control_cdb() logic
2339                  * with struct se_subsystem_api callers for the primary SPC-3 TYPE_DISK
2340                  * LUN emulation code.
2341                  *
2342                  * For TCM/pSCSI and all other SCF_SCSI_DATA_SG_IO_CDB I/O tasks we
2343                  * call ->do_task() directly and let the underlying TCM subsystem plugin
2344                  * code handle the CDB emulation.
2345                  */
2346                 if ((dev->transport->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV) &&
2347                     (!(task->task_se_cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB)))
2348                         error = transport_emulate_control_cdb(task);
2349                 else
2350                         error = dev->transport->do_task(task);
2351
2352                 if (error != 0) {
2353                         cmd->transport_error_status = error;
2354                         spin_lock_irqsave(&cmd->t_state_lock, flags);
2355                         task->task_flags &= ~TF_ACTIVE;
2356                         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2357                         del_timer_sync(&task->task_timer);
2358                         atomic_set(&cmd->transport_sent, 0);
2359                         transport_stop_tasks_for_cmd(cmd);
2360                         atomic_inc(&dev->depth_left);
2361                         transport_generic_request_failure(cmd, 0, 1);
2362                 }
2363         }
2364
2365         goto check_depth;
2366
2367         return 0;
2368 }
2369
2370 void transport_new_cmd_failure(struct se_cmd *se_cmd)
2371 {
2372         unsigned long flags;
2373         /*
2374          * Any unsolicited data will get dumped for failed command inside of
2375          * the fabric plugin
2376          */
2377         spin_lock_irqsave(&se_cmd->t_state_lock, flags);
2378         se_cmd->se_cmd_flags |= SCF_SE_CMD_FAILED;
2379         se_cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2380         spin_unlock_irqrestore(&se_cmd->t_state_lock, flags);
2381 }
2382
2383 static inline u32 transport_get_sectors_6(
2384         unsigned char *cdb,
2385         struct se_cmd *cmd,
2386         int *ret)
2387 {
2388         struct se_device *dev = cmd->se_dev;
2389
2390         /*
2391          * Assume TYPE_DISK for non struct se_device objects.
2392          * Use 8-bit sector value.
2393          */
2394         if (!dev)
2395                 goto type_disk;
2396
2397         /*
2398          * Use 24-bit allocation length for TYPE_TAPE.
2399          */
2400         if (dev->transport->get_device_type(dev) == TYPE_TAPE)
2401                 return (u32)(cdb[2] << 16) + (cdb[3] << 8) + cdb[4];
2402
2403         /*
2404          * Everything else assume TYPE_DISK Sector CDB location.
2405          * Use 8-bit sector value.
2406          */
2407 type_disk:
2408         return (u32)cdb[4];
2409 }
2410
2411 static inline u32 transport_get_sectors_10(
2412         unsigned char *cdb,
2413         struct se_cmd *cmd,
2414         int *ret)
2415 {
2416         struct se_device *dev = cmd->se_dev;
2417
2418         /*
2419          * Assume TYPE_DISK for non struct se_device objects.
2420          * Use 16-bit sector value.
2421          */
2422         if (!dev)
2423                 goto type_disk;
2424
2425         /*
2426          * XXX_10 is not defined in SSC, throw an exception
2427          */
2428         if (dev->transport->get_device_type(dev) == TYPE_TAPE) {
2429                 *ret = -EINVAL;
2430                 return 0;
2431         }
2432
2433         /*
2434          * Everything else assume TYPE_DISK Sector CDB location.
2435          * Use 16-bit sector value.
2436          */
2437 type_disk:
2438         return (u32)(cdb[7] << 8) + cdb[8];
2439 }
2440
2441 static inline u32 transport_get_sectors_12(
2442         unsigned char *cdb,
2443         struct se_cmd *cmd,
2444         int *ret)
2445 {
2446         struct se_device *dev = cmd->se_dev;
2447
2448         /*
2449          * Assume TYPE_DISK for non struct se_device objects.
2450          * Use 32-bit sector value.
2451          */
2452         if (!dev)
2453                 goto type_disk;
2454
2455         /*
2456          * XXX_12 is not defined in SSC, throw an exception
2457          */
2458         if (dev->transport->get_device_type(dev) == TYPE_TAPE) {
2459                 *ret = -EINVAL;
2460                 return 0;
2461         }
2462
2463         /*
2464          * Everything else assume TYPE_DISK Sector CDB location.
2465          * Use 32-bit sector value.
2466          */
2467 type_disk:
2468         return (u32)(cdb[6] << 24) + (cdb[7] << 16) + (cdb[8] << 8) + cdb[9];
2469 }
2470
2471 static inline u32 transport_get_sectors_16(
2472         unsigned char *cdb,
2473         struct se_cmd *cmd,
2474         int *ret)
2475 {
2476         struct se_device *dev = cmd->se_dev;
2477
2478         /*
2479          * Assume TYPE_DISK for non struct se_device objects.
2480          * Use 32-bit sector value.
2481          */
2482         if (!dev)
2483                 goto type_disk;
2484
2485         /*
2486          * Use 24-bit allocation length for TYPE_TAPE.
2487          */
2488         if (dev->transport->get_device_type(dev) == TYPE_TAPE)
2489                 return (u32)(cdb[12] << 16) + (cdb[13] << 8) + cdb[14];
2490
2491 type_disk:
2492         return (u32)(cdb[10] << 24) + (cdb[11] << 16) +
2493                     (cdb[12] << 8) + cdb[13];
2494 }
2495
2496 /*
2497  * Used for VARIABLE_LENGTH_CDB WRITE_32 and READ_32 variants
2498  */
2499 static inline u32 transport_get_sectors_32(
2500         unsigned char *cdb,
2501         struct se_cmd *cmd,
2502         int *ret)
2503 {
2504         /*
2505          * Assume TYPE_DISK for non struct se_device objects.
2506          * Use 32-bit sector value.
2507          */
2508         return (u32)(cdb[28] << 24) + (cdb[29] << 16) +
2509                     (cdb[30] << 8) + cdb[31];
2510
2511 }
2512
2513 static inline u32 transport_get_size(
2514         u32 sectors,
2515         unsigned char *cdb,
2516         struct se_cmd *cmd)
2517 {
2518         struct se_device *dev = cmd->se_dev;
2519
2520         if (dev->transport->get_device_type(dev) == TYPE_TAPE) {
2521                 if (cdb[1] & 1) { /* sectors */
2522                         return dev->se_sub_dev->se_dev_attrib.block_size * sectors;
2523                 } else /* bytes */
2524                         return sectors;
2525         }
2526 #if 0
2527         pr_debug("Returning block_size: %u, sectors: %u == %u for"
2528                         " %s object\n", dev->se_sub_dev->se_dev_attrib.block_size, sectors,
2529                         dev->se_sub_dev->se_dev_attrib.block_size * sectors,
2530                         dev->transport->name);
2531 #endif
2532         return dev->se_sub_dev->se_dev_attrib.block_size * sectors;
2533 }
2534
2535 static void transport_xor_callback(struct se_cmd *cmd)
2536 {
2537         unsigned char *buf, *addr;
2538         struct scatterlist *sg;
2539         unsigned int offset;
2540         int i;
2541         int count;
2542         /*
2543          * From sbc3r22.pdf section 5.48 XDWRITEREAD (10) command
2544          *
2545          * 1) read the specified logical block(s);
2546          * 2) transfer logical blocks from the data-out buffer;
2547          * 3) XOR the logical blocks transferred from the data-out buffer with
2548          *    the logical blocks read, storing the resulting XOR data in a buffer;
2549          * 4) if the DISABLE WRITE bit is set to zero, then write the logical
2550          *    blocks transferred from the data-out buffer; and
2551          * 5) transfer the resulting XOR data to the data-in buffer.
2552          */
2553         buf = kmalloc(cmd->data_length, GFP_KERNEL);
2554         if (!buf) {
2555                 pr_err("Unable to allocate xor_callback buf\n");
2556                 return;
2557         }
2558         /*
2559          * Copy the scatterlist WRITE buffer located at cmd->t_data_sg
2560          * into the locally allocated *buf
2561          */
2562         sg_copy_to_buffer(cmd->t_data_sg,
2563                           cmd->t_data_nents,
2564                           buf,
2565                           cmd->data_length);
2566
2567         /*
2568          * Now perform the XOR against the BIDI read memory located at
2569          * cmd->t_mem_bidi_list
2570          */
2571
2572         offset = 0;
2573         for_each_sg(cmd->t_bidi_data_sg, sg, cmd->t_bidi_data_nents, count) {
2574                 addr = kmap_atomic(sg_page(sg), KM_USER0);
2575                 if (!addr)
2576                         goto out;
2577
2578                 for (i = 0; i < sg->length; i++)
2579                         *(addr + sg->offset + i) ^= *(buf + offset + i);
2580
2581                 offset += sg->length;
2582                 kunmap_atomic(addr, KM_USER0);
2583         }
2584
2585 out:
2586         kfree(buf);
2587 }
2588
2589 /*
2590  * Used to obtain Sense Data from underlying Linux/SCSI struct scsi_cmnd
2591  */
2592 static int transport_get_sense_data(struct se_cmd *cmd)
2593 {
2594         unsigned char *buffer = cmd->sense_buffer, *sense_buffer = NULL;
2595         struct se_device *dev = cmd->se_dev;
2596         struct se_task *task = NULL, *task_tmp;
2597         unsigned long flags;
2598         u32 offset = 0;
2599
2600         WARN_ON(!cmd->se_lun);
2601
2602         if (!dev)
2603                 return 0;
2604
2605         spin_lock_irqsave(&cmd->t_state_lock, flags);
2606         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
2607                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2608                 return 0;
2609         }
2610
2611         list_for_each_entry_safe(task, task_tmp,
2612                                 &cmd->t_task_list, t_list) {
2613                 if (!task->task_sense)
2614                         continue;
2615
2616                 if (!dev->transport->get_sense_buffer) {
2617                         pr_err("dev->transport->get_sense_buffer"
2618                                         " is NULL\n");
2619                         continue;
2620                 }
2621
2622                 sense_buffer = dev->transport->get_sense_buffer(task);
2623                 if (!sense_buffer) {
2624                         pr_err("ITT[0x%08x]_TASK[%p]: Unable to locate"
2625                                 " sense buffer for task with sense\n",
2626                                 cmd->se_tfo->get_task_tag(cmd), task);
2627                         continue;
2628                 }
2629                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2630
2631                 offset = cmd->se_tfo->set_fabric_sense_len(cmd,
2632                                 TRANSPORT_SENSE_BUFFER);
2633
2634                 memcpy(&buffer[offset], sense_buffer,
2635                                 TRANSPORT_SENSE_BUFFER);
2636                 cmd->scsi_status = task->task_scsi_status;
2637                 /* Automatically padded */
2638                 cmd->scsi_sense_length =
2639                                 (TRANSPORT_SENSE_BUFFER + offset);
2640
2641                 pr_debug("HBA_[%u]_PLUG[%s]: Set SAM STATUS: 0x%02x"
2642                                 " and sense\n",
2643                         dev->se_hba->hba_id, dev->transport->name,
2644                                 cmd->scsi_status);
2645                 return 0;
2646         }
2647         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2648
2649         return -1;
2650 }
2651
2652 static int
2653 transport_handle_reservation_conflict(struct se_cmd *cmd)
2654 {
2655         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2656         cmd->se_cmd_flags |= SCF_SCSI_RESERVATION_CONFLICT;
2657         cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
2658         /*
2659          * For UA Interlock Code 11b, a RESERVATION CONFLICT will
2660          * establish a UNIT ATTENTION with PREVIOUS RESERVATION
2661          * CONFLICT STATUS.
2662          *
2663          * See spc4r17, section 7.4.6 Control Mode Page, Table 349
2664          */
2665         if (cmd->se_sess &&
2666             cmd->se_dev->se_sub_dev->se_dev_attrib.emulate_ua_intlck_ctrl == 2)
2667                 core_scsi3_ua_allocate(cmd->se_sess->se_node_acl,
2668                         cmd->orig_fe_lun, 0x2C,
2669                         ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
2670         return -EINVAL;
2671 }
2672
2673 static inline long long transport_dev_end_lba(struct se_device *dev)
2674 {
2675         return dev->transport->get_blocks(dev) + 1;
2676 }
2677
2678 static int transport_cmd_get_valid_sectors(struct se_cmd *cmd)
2679 {
2680         struct se_device *dev = cmd->se_dev;
2681         u32 sectors;
2682
2683         if (dev->transport->get_device_type(dev) != TYPE_DISK)
2684                 return 0;
2685
2686         sectors = (cmd->data_length / dev->se_sub_dev->se_dev_attrib.block_size);
2687
2688         if ((cmd->t_task_lba + sectors) > transport_dev_end_lba(dev)) {
2689                 pr_err("LBA: %llu Sectors: %u exceeds"
2690                         " transport_dev_end_lba(): %llu\n",
2691                         cmd->t_task_lba, sectors,
2692                         transport_dev_end_lba(dev));
2693                 return -EINVAL;
2694         }
2695
2696         return 0;
2697 }
2698
2699 static int target_check_write_same_discard(unsigned char *flags, struct se_device *dev)
2700 {
2701         /*
2702          * Determine if the received WRITE_SAME is used to for direct
2703          * passthrough into Linux/SCSI with struct request via TCM/pSCSI
2704          * or we are signaling the use of internal WRITE_SAME + UNMAP=1
2705          * emulation for -> Linux/BLOCK disbard with TCM/IBLOCK code.
2706          */
2707         int passthrough = (dev->transport->transport_type ==
2708                                 TRANSPORT_PLUGIN_PHBA_PDEV);
2709
2710         if (!passthrough) {
2711                 if ((flags[0] & 0x04) || (flags[0] & 0x02)) {
2712                         pr_err("WRITE_SAME PBDATA and LBDATA"
2713                                 " bits not supported for Block Discard"
2714                                 " Emulation\n");
2715                         return -ENOSYS;
2716                 }
2717                 /*
2718                  * Currently for the emulated case we only accept
2719                  * tpws with the UNMAP=1 bit set.
2720                  */
2721                 if (!(flags[0] & 0x08)) {
2722                         pr_err("WRITE_SAME w/o UNMAP bit not"
2723                                 " supported for Block Discard Emulation\n");
2724                         return -ENOSYS;
2725                 }
2726         }
2727
2728         return 0;
2729 }
2730
2731 /*      transport_generic_cmd_sequencer():
2732  *
2733  *      Generic Command Sequencer that should work for most DAS transport
2734  *      drivers.
2735  *
2736  *      Called from transport_generic_allocate_tasks() in the $FABRIC_MOD
2737  *      RX Thread.
2738  *
2739  *      FIXME: Need to support other SCSI OPCODES where as well.
2740  */
2741 static int transport_generic_cmd_sequencer(
2742         struct se_cmd *cmd,
2743         unsigned char *cdb)
2744 {
2745         struct se_device *dev = cmd->se_dev;
2746         struct se_subsystem_dev *su_dev = dev->se_sub_dev;
2747         int ret = 0, sector_ret = 0, passthrough;
2748         u32 sectors = 0, size = 0, pr_reg_type = 0;
2749         u16 service_action;
2750         u8 alua_ascq = 0;
2751         /*
2752          * Check for an existing UNIT ATTENTION condition
2753          */
2754         if (core_scsi3_ua_check(cmd, cdb) < 0) {
2755                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2756                 cmd->scsi_sense_reason = TCM_CHECK_CONDITION_UNIT_ATTENTION;
2757                 return -EINVAL;
2758         }
2759         /*
2760          * Check status of Asymmetric Logical Unit Assignment port
2761          */
2762         ret = su_dev->t10_alua.alua_state_check(cmd, cdb, &alua_ascq);
2763         if (ret != 0) {
2764                 /*
2765                  * Set SCSI additional sense code (ASC) to 'LUN Not Accessible';
2766                  * The ALUA additional sense code qualifier (ASCQ) is determined
2767                  * by the ALUA primary or secondary access state..
2768                  */
2769                 if (ret > 0) {
2770 #if 0
2771                         pr_debug("[%s]: ALUA TG Port not available,"
2772                                 " SenseKey: NOT_READY, ASC/ASCQ: 0x04/0x%02x\n",
2773                                 cmd->se_tfo->get_fabric_name(), alua_ascq);
2774 #endif
2775                         transport_set_sense_codes(cmd, 0x04, alua_ascq);
2776                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2777                         cmd->scsi_sense_reason = TCM_CHECK_CONDITION_NOT_READY;
2778                         return -EINVAL;
2779                 }
2780                 goto out_invalid_cdb_field;
2781         }
2782         /*
2783          * Check status for SPC-3 Persistent Reservations
2784          */
2785         if (su_dev->t10_pr.pr_ops.t10_reservation_check(cmd, &pr_reg_type) != 0) {
2786                 if (su_dev->t10_pr.pr_ops.t10_seq_non_holder(
2787                                         cmd, cdb, pr_reg_type) != 0)
2788                         return transport_handle_reservation_conflict(cmd);
2789                 /*
2790                  * This means the CDB is allowed for the SCSI Initiator port
2791                  * when said port is *NOT* holding the legacy SPC-2 or
2792                  * SPC-3 Persistent Reservation.
2793                  */
2794         }
2795
2796         switch (cdb[0]) {
2797         case READ_6:
2798                 sectors = transport_get_sectors_6(cdb, cmd, &sector_ret);
2799                 if (sector_ret)
2800                         goto out_unsupported_cdb;
2801                 size = transport_get_size(sectors, cdb, cmd);
2802                 cmd->t_task_lba = transport_lba_21(cdb);
2803                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2804                 break;
2805         case READ_10:
2806                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
2807                 if (sector_ret)
2808                         goto out_unsupported_cdb;
2809                 size = transport_get_size(sectors, cdb, cmd);
2810                 cmd->t_task_lba = transport_lba_32(cdb);
2811                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2812                 break;
2813         case READ_12:
2814                 sectors = transport_get_sectors_12(cdb, cmd, &sector_ret);
2815                 if (sector_ret)
2816                         goto out_unsupported_cdb;
2817                 size = transport_get_size(sectors, cdb, cmd);
2818                 cmd->t_task_lba = transport_lba_32(cdb);
2819                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2820                 break;
2821         case READ_16:
2822                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
2823                 if (sector_ret)
2824                         goto out_unsupported_cdb;
2825                 size = transport_get_size(sectors, cdb, cmd);
2826                 cmd->t_task_lba = transport_lba_64(cdb);
2827                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2828                 break;
2829         case WRITE_6:
2830                 sectors = transport_get_sectors_6(cdb, cmd, &sector_ret);
2831                 if (sector_ret)
2832                         goto out_unsupported_cdb;
2833                 size = transport_get_size(sectors, cdb, cmd);
2834                 cmd->t_task_lba = transport_lba_21(cdb);
2835                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2836                 break;
2837         case WRITE_10:
2838                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
2839                 if (sector_ret)
2840                         goto out_unsupported_cdb;
2841                 size = transport_get_size(sectors, cdb, cmd);
2842                 cmd->t_task_lba = transport_lba_32(cdb);
2843                 cmd->t_tasks_fua = (cdb[1] & 0x8);
2844                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2845                 break;
2846         case WRITE_12:
2847                 sectors = transport_get_sectors_12(cdb, cmd, &sector_ret);
2848                 if (sector_ret)
2849                         goto out_unsupported_cdb;
2850                 size = transport_get_size(sectors, cdb, cmd);
2851                 cmd->t_task_lba = transport_lba_32(cdb);
2852                 cmd->t_tasks_fua = (cdb[1] & 0x8);
2853                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2854                 break;
2855         case WRITE_16:
2856                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
2857                 if (sector_ret)
2858                         goto out_unsupported_cdb;
2859                 size = transport_get_size(sectors, cdb, cmd);
2860                 cmd->t_task_lba = transport_lba_64(cdb);
2861                 cmd->t_tasks_fua = (cdb[1] & 0x8);
2862                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2863                 break;
2864         case XDWRITEREAD_10:
2865                 if ((cmd->data_direction != DMA_TO_DEVICE) ||
2866                     !(cmd->t_tasks_bidi))
2867                         goto out_invalid_cdb_field;
2868                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
2869                 if (sector_ret)
2870                         goto out_unsupported_cdb;
2871                 size = transport_get_size(sectors, cdb, cmd);
2872                 cmd->t_task_lba = transport_lba_32(cdb);
2873                 cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2874                 passthrough = (dev->transport->transport_type ==
2875                                 TRANSPORT_PLUGIN_PHBA_PDEV);
2876                 /*
2877                  * Skip the remaining assignments for TCM/PSCSI passthrough
2878                  */
2879                 if (passthrough)
2880                         break;
2881                 /*
2882                  * Setup BIDI XOR callback to be run after I/O completion.
2883                  */
2884                 cmd->transport_complete_callback = &transport_xor_callback;
2885                 cmd->t_tasks_fua = (cdb[1] & 0x8);
2886                 break;
2887         case VARIABLE_LENGTH_CMD:
2888                 service_action = get_unaligned_be16(&cdb[8]);
2889                 /*
2890                  * Determine if this is TCM/PSCSI device and we should disable
2891                  * internal emulation for this CDB.
2892                  */
2893                 passthrough = (dev->transport->transport_type ==
2894                                         TRANSPORT_PLUGIN_PHBA_PDEV);
2895
2896                 switch (service_action) {
2897                 case XDWRITEREAD_32:
2898                         sectors = transport_get_sectors_32(cdb, cmd, &sector_ret);
2899                         if (sector_ret)
2900                                 goto out_unsupported_cdb;
2901                         size = transport_get_size(sectors, cdb, cmd);
2902                         /*
2903                          * Use WRITE_32 and READ_32 opcodes for the emulated
2904                          * XDWRITE_READ_32 logic.
2905                          */
2906                         cmd->t_task_lba = transport_lba_64_ext(cdb);
2907                         cmd->se_cmd_flags |= SCF_SCSI_DATA_SG_IO_CDB;
2908
2909                         /*
2910                          * Skip the remaining assignments for TCM/PSCSI passthrough
2911                          */
2912                         if (passthrough)
2913                                 break;
2914
2915                         /*
2916                          * Setup BIDI XOR callback to be run during after I/O
2917                          * completion.
2918                          */
2919                         cmd->transport_complete_callback = &transport_xor_callback;
2920                         cmd->t_tasks_fua = (cdb[10] & 0x8);
2921                         break;
2922                 case WRITE_SAME_32:
2923                         sectors = transport_get_sectors_32(cdb, cmd, &sector_ret);
2924                         if (sector_ret)
2925                                 goto out_unsupported_cdb;
2926
2927                         if (sectors)
2928                                 size = transport_get_size(1, cdb, cmd);
2929                         else {
2930                                 pr_err("WSNZ=1, WRITE_SAME w/sectors=0 not"
2931                                        " supported\n");
2932                                 goto out_invalid_cdb_field;
2933                         }
2934
2935                         cmd->t_task_lba = get_unaligned_be64(&cdb[12]);
2936                         cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2937
2938                         if (target_check_write_same_discard(&cdb[10], dev) < 0)
2939                                 goto out_invalid_cdb_field;
2940
2941                         break;
2942                 default:
2943                         pr_err("VARIABLE_LENGTH_CMD service action"
2944                                 " 0x%04x not supported\n", service_action);
2945                         goto out_unsupported_cdb;
2946                 }
2947                 break;
2948         case MAINTENANCE_IN:
2949                 if (dev->transport->get_device_type(dev) != TYPE_ROM) {
2950                         /* MAINTENANCE_IN from SCC-2 */
2951                         /*
2952                          * Check for emulated MI_REPORT_TARGET_PGS.
2953                          */
2954                         if (cdb[1] == MI_REPORT_TARGET_PGS) {
2955                                 cmd->transport_emulate_cdb =
2956                                 (su_dev->t10_alua.alua_type ==
2957                                  SPC3_ALUA_EMULATED) ?
2958                                 core_emulate_report_target_port_groups :
2959                                 NULL;
2960                         }
2961                         size = (cdb[6] << 24) | (cdb[7] << 16) |
2962                                (cdb[8] << 8) | cdb[9];
2963                 } else {
2964                         /* GPCMD_SEND_KEY from multi media commands */
2965                         size = (cdb[8] << 8) + cdb[9];
2966                 }
2967                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2968                 break;
2969         case MODE_SELECT:
2970                 size = cdb[4];
2971                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2972                 break;
2973         case MODE_SELECT_10:
2974                 size = (cdb[7] << 8) + cdb[8];
2975                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2976                 break;
2977         case MODE_SENSE:
2978                 size = cdb[4];
2979                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2980                 break;
2981         case MODE_SENSE_10:
2982         case GPCMD_READ_BUFFER_CAPACITY:
2983         case GPCMD_SEND_OPC:
2984         case LOG_SELECT:
2985         case LOG_SENSE:
2986                 size = (cdb[7] << 8) + cdb[8];
2987                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2988                 break;
2989         case READ_BLOCK_LIMITS:
2990                 size = READ_BLOCK_LEN;
2991                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2992                 break;
2993         case GPCMD_GET_CONFIGURATION:
2994         case GPCMD_READ_FORMAT_CAPACITIES:
2995         case GPCMD_READ_DISC_INFO:
2996         case GPCMD_READ_TRACK_RZONE_INFO:
2997                 size = (cdb[7] << 8) + cdb[8];
2998                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
2999                 break;
3000         case PERSISTENT_RESERVE_IN:
3001         case PERSISTENT_RESERVE_OUT:
3002                 cmd->transport_emulate_cdb =
3003                         (su_dev->t10_pr.res_type ==
3004                          SPC3_PERSISTENT_RESERVATIONS) ?
3005                         core_scsi3_emulate_pr : NULL;
3006                 size = (cdb[7] << 8) + cdb[8];
3007                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3008                 break;
3009         case GPCMD_MECHANISM_STATUS:
3010         case GPCMD_READ_DVD_STRUCTURE:
3011                 size = (cdb[8] << 8) + cdb[9];
3012                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3013                 break;
3014         case READ_POSITION:
3015                 size = READ_POSITION_LEN;
3016                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3017                 break;
3018         case MAINTENANCE_OUT:
3019                 if (dev->transport->get_device_type(dev) != TYPE_ROM) {
3020                         /* MAINTENANCE_OUT from SCC-2
3021                          *
3022                          * Check for emulated MO_SET_TARGET_PGS.
3023                          */
3024                         if (cdb[1] == MO_SET_TARGET_PGS) {
3025                                 cmd->transport_emulate_cdb =
3026                                 (su_dev->t10_alua.alua_type ==
3027                                         SPC3_ALUA_EMULATED) ?
3028                                 core_emulate_set_target_port_groups :
3029                                 NULL;
3030                         }
3031
3032                         size = (cdb[6] << 24) | (cdb[7] << 16) |
3033                                (cdb[8] << 8) | cdb[9];
3034                 } else  {
3035                         /* GPCMD_REPORT_KEY from multi media commands */
3036                         size = (cdb[8] << 8) + cdb[9];
3037                 }
3038                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3039                 break;
3040         case INQUIRY:
3041                 size = (cdb[3] << 8) + cdb[4];
3042                 /*
3043                  * Do implict HEAD_OF_QUEUE processing for INQUIRY.
3044                  * See spc4r17 section 5.3
3045                  */
3046                 if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
3047                         cmd->sam_task_attr = MSG_HEAD_TAG;
3048                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3049                 break;
3050         case READ_BUFFER:
3051                 size = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
3052                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3053                 break;
3054         case READ_CAPACITY:
3055                 size = READ_CAP_LEN;
3056                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3057                 break;
3058         case READ_MEDIA_SERIAL_NUMBER:
3059         case SECURITY_PROTOCOL_IN:
3060         case SECURITY_PROTOCOL_OUT:
3061                 size = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
3062                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3063                 break;
3064         case SERVICE_ACTION_IN:
3065         case ACCESS_CONTROL_IN:
3066         case ACCESS_CONTROL_OUT:
3067         case EXTENDED_COPY:
3068         case READ_ATTRIBUTE:
3069         case RECEIVE_COPY_RESULTS:
3070         case WRITE_ATTRIBUTE:
3071                 size = (cdb[10] << 24) | (cdb[11] << 16) |
3072                        (cdb[12] << 8) | cdb[13];
3073                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3074                 break;
3075         case RECEIVE_DIAGNOSTIC:
3076         case SEND_DIAGNOSTIC:
3077                 size = (cdb[3] << 8) | cdb[4];
3078                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3079                 break;
3080 /* #warning FIXME: Figure out correct GPCMD_READ_CD blocksize. */
3081 #if 0
3082         case GPCMD_READ_CD:
3083                 sectors = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
3084                 size = (2336 * sectors);
3085                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3086                 break;
3087 #endif
3088         case READ_TOC:
3089                 size = cdb[8];
3090                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3091                 break;
3092         case REQUEST_SENSE:
3093                 size = cdb[4];
3094                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3095                 break;
3096         case READ_ELEMENT_STATUS:
3097                 size = 65536 * cdb[7] + 256 * cdb[8] + cdb[9];
3098                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3099                 break;
3100         case WRITE_BUFFER:
3101                 size = (cdb[6] << 16) + (cdb[7] << 8) + cdb[8];
3102                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3103                 break;
3104         case RESERVE:
3105         case RESERVE_10:
3106                 /*
3107                  * The SPC-2 RESERVE does not contain a size in the SCSI CDB.
3108                  * Assume the passthrough or $FABRIC_MOD will tell us about it.
3109                  */
3110                 if (cdb[0] == RESERVE_10)
3111                         size = (cdb[7] << 8) | cdb[8];
3112                 else
3113                         size = cmd->data_length;
3114
3115                 /*
3116                  * Setup the legacy emulated handler for SPC-2 and
3117                  * >= SPC-3 compatible reservation handling (CRH=1)
3118                  * Otherwise, we assume the underlying SCSI logic is
3119                  * is running in SPC_PASSTHROUGH, and wants reservations
3120                  * emulation disabled.
3121                  */
3122                 cmd->transport_emulate_cdb =
3123                                 (su_dev->t10_pr.res_type !=
3124                                  SPC_PASSTHROUGH) ?
3125                                 core_scsi2_emulate_crh : NULL;
3126                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3127                 break;
3128         case RELEASE:
3129         case RELEASE_10:
3130                 /*
3131                  * The SPC-2 RELEASE does not contain a size in the SCSI CDB.
3132                  * Assume the passthrough or $FABRIC_MOD will tell us about it.
3133                 */
3134                 if (cdb[0] == RELEASE_10)
3135                         size = (cdb[7] << 8) | cdb[8];
3136                 else
3137                         size = cmd->data_length;
3138
3139                 cmd->transport_emulate_cdb =
3140                                 (su_dev->t10_pr.res_type !=
3141                                  SPC_PASSTHROUGH) ?
3142                                 core_scsi2_emulate_crh : NULL;
3143                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3144                 break;
3145         case SYNCHRONIZE_CACHE:
3146         case 0x91: /* SYNCHRONIZE_CACHE_16: */
3147                 /*
3148                  * Extract LBA and range to be flushed for emulated SYNCHRONIZE_CACHE
3149                  */
3150                 if (cdb[0] == SYNCHRONIZE_CACHE) {
3151                         sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
3152                         cmd->t_task_lba = transport_lba_32(cdb);
3153                 } else {
3154                         sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
3155                         cmd->t_task_lba = transport_lba_64(cdb);
3156                 }
3157                 if (sector_ret)
3158                         goto out_unsupported_cdb;
3159
3160                 size = transport_get_size(sectors, cdb, cmd);
3161                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3162
3163                 /*
3164                  * For TCM/pSCSI passthrough, skip cmd->transport_emulate_cdb()
3165                  */
3166                 if (dev->transport->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV)
3167                         break;
3168                 /*
3169                  * Set SCF_EMULATE_CDB_ASYNC to ensure asynchronous operation
3170                  * for SYNCHRONIZE_CACHE* Immed=1 case in __transport_execute_tasks()
3171                  */
3172                 cmd->se_cmd_flags |= SCF_EMULATE_CDB_ASYNC;
3173                 /*
3174                  * Check to ensure that LBA + Range does not exceed past end of
3175                  * device for IBLOCK and FILEIO ->do_sync_cache() backend calls
3176                  */
3177                 if ((cmd->t_task_lba != 0) || (sectors != 0)) {
3178                         if (transport_cmd_get_valid_sectors(cmd) < 0)
3179                                 goto out_invalid_cdb_field;
3180                 }
3181                 break;
3182         case UNMAP:
3183                 size = get_unaligned_be16(&cdb[7]);
3184                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3185                 break;
3186         case WRITE_SAME_16:
3187                 sectors = transport_get_sectors_16(cdb, cmd, &sector_ret);
3188                 if (sector_ret)
3189                         goto out_unsupported_cdb;
3190
3191                 if (sectors)
3192                         size = transport_get_size(1, cdb, cmd);
3193                 else {
3194                         pr_err("WSNZ=1, WRITE_SAME w/sectors=0 not supported\n");
3195                         goto out_invalid_cdb_field;
3196                 }
3197
3198                 cmd->t_task_lba = get_unaligned_be64(&cdb[2]);
3199                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3200
3201                 if (target_check_write_same_discard(&cdb[1], dev) < 0)
3202                         goto out_invalid_cdb_field;
3203                 break;
3204         case WRITE_SAME:
3205                 sectors = transport_get_sectors_10(cdb, cmd, &sector_ret);
3206                 if (sector_ret)
3207                         goto out_unsupported_cdb;
3208
3209                 if (sectors)
3210                         size = transport_get_size(1, cdb, cmd);
3211                 else {
3212                         pr_err("WSNZ=1, WRITE_SAME w/sectors=0 not supported\n");
3213                         goto out_invalid_cdb_field;
3214                 }
3215
3216                 cmd->t_task_lba = get_unaligned_be32(&cdb[2]);
3217                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3218                 /*
3219                  * Follow sbcr26 with WRITE_SAME (10) and check for the existence
3220                  * of byte 1 bit 3 UNMAP instead of original reserved field
3221                  */
3222                 if (target_check_write_same_discard(&cdb[1], dev) < 0)
3223                         goto out_invalid_cdb_field;
3224                 break;
3225         case ALLOW_MEDIUM_REMOVAL:
3226         case GPCMD_CLOSE_TRACK:
3227         case ERASE:
3228         case INITIALIZE_ELEMENT_STATUS:
3229         case GPCMD_LOAD_UNLOAD:
3230         case REZERO_UNIT:
3231         case SEEK_10:
3232         case GPCMD_SET_SPEED:
3233         case SPACE:
3234         case START_STOP:
3235         case TEST_UNIT_READY:
3236         case VERIFY:
3237         case WRITE_FILEMARKS:
3238         case MOVE_MEDIUM:
3239                 cmd->se_cmd_flags |= SCF_SCSI_NON_DATA_CDB;
3240                 break;
3241         case REPORT_LUNS:
3242                 cmd->transport_emulate_cdb =
3243                                 transport_core_report_lun_response;
3244                 size = (cdb[6] << 24) | (cdb[7] << 16) | (cdb[8] << 8) | cdb[9];
3245                 /*
3246                  * Do implict HEAD_OF_QUEUE processing for REPORT_LUNS
3247                  * See spc4r17 section 5.3
3248                  */
3249                 if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
3250                         cmd->sam_task_attr = MSG_HEAD_TAG;
3251                 cmd->se_cmd_flags |= SCF_SCSI_CONTROL_SG_IO_CDB;
3252                 break;
3253         default:
3254                 pr_warn("TARGET_CORE[%s]: Unsupported SCSI Opcode"
3255                         " 0x%02x, sending CHECK_CONDITION.\n",
3256                         cmd->se_tfo->get_fabric_name(), cdb[0]);
3257                 goto out_unsupported_cdb;
3258         }
3259
3260         if (size != cmd->data_length) {
3261                 pr_warn("TARGET_CORE[%s]: Expected Transfer Length:"
3262                         " %u does not match SCSI CDB Length: %u for SAM Opcode:"
3263                         " 0x%02x\n", cmd->se_tfo->get_fabric_name(),
3264                                 cmd->data_length, size, cdb[0]);
3265
3266                 cmd->cmd_spdtl = size;
3267
3268                 if (cmd->data_direction == DMA_TO_DEVICE) {
3269                         pr_err("Rejecting underflow/overflow"
3270                                         " WRITE data\n");
3271                         goto out_invalid_cdb_field;
3272                 }
3273                 /*
3274                  * Reject READ_* or WRITE_* with overflow/underflow for
3275                  * type SCF_SCSI_DATA_SG_IO_CDB.
3276                  */
3277                 if (!ret && (dev->se_sub_dev->se_dev_attrib.block_size != 512))  {
3278                         pr_err("Failing OVERFLOW/UNDERFLOW for LBA op"
3279                                 " CDB on non 512-byte sector setup subsystem"
3280                                 " plugin: %s\n", dev->transport->name);
3281                         /* Returns CHECK_CONDITION + INVALID_CDB_FIELD */
3282                         goto out_invalid_cdb_field;
3283                 }
3284
3285                 if (size > cmd->data_length) {
3286                         cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
3287                         cmd->residual_count = (size - cmd->data_length);
3288                 } else {
3289                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
3290                         cmd->residual_count = (cmd->data_length - size);
3291                 }
3292                 cmd->data_length = size;
3293         }
3294
3295         /* Let's limit control cdbs to a page, for simplicity's sake. */
3296         if ((cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB) &&
3297             size > PAGE_SIZE)
3298                 goto out_invalid_cdb_field;
3299
3300         transport_set_supported_SAM_opcode(cmd);
3301         return ret;
3302
3303 out_unsupported_cdb:
3304         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
3305         cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
3306         return -EINVAL;
3307 out_invalid_cdb_field:
3308         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
3309         cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
3310         return -EINVAL;
3311 }
3312
3313 /*
3314  * Called from I/O completion to determine which dormant/delayed
3315  * and ordered cmds need to have their tasks added to the execution queue.
3316  */
3317 static void transport_complete_task_attr(struct se_cmd *cmd)
3318 {
3319         struct se_device *dev = cmd->se_dev;
3320         struct se_cmd *cmd_p, *cmd_tmp;
3321         int new_active_tasks = 0;
3322
3323         if (cmd->sam_task_attr == MSG_SIMPLE_TAG) {
3324                 atomic_dec(&dev->simple_cmds);
3325                 smp_mb__after_atomic_dec();
3326                 dev->dev_cur_ordered_id++;
3327                 pr_debug("Incremented dev->dev_cur_ordered_id: %u for"
3328                         " SIMPLE: %u\n", dev->dev_cur_ordered_id,
3329                         cmd->se_ordered_id);
3330         } else if (cmd->sam_task_attr == MSG_HEAD_TAG) {
3331                 atomic_dec(&dev->dev_hoq_count);
3332                 smp_mb__after_atomic_dec();
3333                 dev->dev_cur_ordered_id++;
3334                 pr_debug("Incremented dev_cur_ordered_id: %u for"
3335                         " HEAD_OF_QUEUE: %u\n", dev->dev_cur_ordered_id,
3336                         cmd->se_ordered_id);
3337         } else if (cmd->sam_task_attr == MSG_ORDERED_TAG) {
3338                 spin_lock(&dev->ordered_cmd_lock);
3339                 list_del(&cmd->se_ordered_node);
3340                 atomic_dec(&dev->dev_ordered_sync);
3341                 smp_mb__after_atomic_dec();
3342                 spin_unlock(&dev->ordered_cmd_lock);
3343
3344                 dev->dev_cur_ordered_id++;
3345                 pr_debug("Incremented dev_cur_ordered_id: %u for ORDERED:"
3346                         " %u\n", dev->dev_cur_ordered_id, cmd->se_ordered_id);
3347         }
3348         /*
3349          * Process all commands up to the last received
3350          * ORDERED task attribute which requires another blocking
3351          * boundary
3352          */
3353         spin_lock(&dev->delayed_cmd_lock);
3354         list_for_each_entry_safe(cmd_p, cmd_tmp,
3355                         &dev->delayed_cmd_list, se_delayed_node) {
3356
3357                 list_del(&cmd_p->se_delayed_node);
3358                 spin_unlock(&dev->delayed_cmd_lock);
3359
3360                 pr_debug("Calling add_tasks() for"
3361                         " cmd_p: 0x%02x Task Attr: 0x%02x"
3362                         " Dormant -> Active, se_ordered_id: %u\n",
3363                         cmd_p->t_task_cdb[0],
3364                         cmd_p->sam_task_attr, cmd_p->se_ordered_id);
3365
3366                 transport_add_tasks_from_cmd(cmd_p);
3367                 new_active_tasks++;
3368
3369                 spin_lock(&dev->delayed_cmd_lock);
3370                 if (cmd_p->sam_task_attr == MSG_ORDERED_TAG)
3371                         break;
3372         }
3373         spin_unlock(&dev->delayed_cmd_lock);
3374         /*
3375          * If new tasks have become active, wake up the transport thread
3376          * to do the processing of the Active tasks.
3377          */
3378         if (new_active_tasks != 0)
3379                 wake_up_interruptible(&dev->dev_queue_obj.thread_wq);
3380 }
3381
3382 static void transport_complete_qf(struct se_cmd *cmd)
3383 {
3384         int ret = 0;
3385
3386         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
3387                 transport_complete_task_attr(cmd);
3388
3389         if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
3390                 ret = cmd->se_tfo->queue_status(cmd);
3391                 if (ret)
3392                         goto out;
3393         }
3394
3395         switch (cmd->data_direction) {
3396         case DMA_FROM_DEVICE:
3397                 ret = cmd->se_tfo->queue_data_in(cmd);
3398                 break;
3399         case DMA_TO_DEVICE:
3400                 if (cmd->t_bidi_data_sg) {
3401                         ret = cmd->se_tfo->queue_data_in(cmd);
3402                         if (ret < 0)
3403                                 break;
3404                 }
3405                 /* Fall through for DMA_TO_DEVICE */
3406         case DMA_NONE:
3407                 ret = cmd->se_tfo->queue_status(cmd);
3408                 break;
3409         default:
3410                 break;
3411         }
3412
3413 out:
3414         if (ret < 0) {
3415                 transport_handle_queue_full(cmd, cmd->se_dev);
3416                 return;
3417         }
3418         transport_lun_remove_cmd(cmd);
3419         transport_cmd_check_stop_to_fabric(cmd);
3420 }
3421
3422 static void transport_handle_queue_full(
3423         struct se_cmd *cmd,
3424         struct se_device *dev)
3425 {
3426         spin_lock_irq(&dev->qf_cmd_lock);
3427         list_add_tail(&cmd->se_qf_node, &cmd->se_dev->qf_cmd_list);
3428         atomic_inc(&dev->dev_qf_count);
3429         smp_mb__after_atomic_inc();
3430         spin_unlock_irq(&cmd->se_dev->qf_cmd_lock);
3431
3432         schedule_work(&cmd->se_dev->qf_work_queue);
3433 }
3434
3435 static void target_complete_ok_work(struct work_struct *work)
3436 {
3437         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
3438         int reason = 0, ret;
3439
3440         /*
3441          * Check if we need to move delayed/dormant tasks from cmds on the
3442          * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
3443          * Attribute.
3444          */
3445         if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
3446                 transport_complete_task_attr(cmd);
3447         /*
3448          * Check to schedule QUEUE_FULL work, or execute an existing
3449          * cmd->transport_qf_callback()
3450          */
3451         if (atomic_read(&cmd->se_dev->dev_qf_count) != 0)
3452                 schedule_work(&cmd->se_dev->qf_work_queue);
3453
3454         /*
3455          * Check if we need to retrieve a sense buffer from
3456          * the struct se_cmd in question.
3457          */
3458         if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
3459                 if (transport_get_sense_data(cmd) < 0)
3460                         reason = TCM_NON_EXISTENT_LUN;
3461
3462                 /*
3463                  * Only set when an struct se_task->task_scsi_status returned
3464                  * a non GOOD status.
3465                  */
3466                 if (cmd->scsi_status) {
3467                         ret = transport_send_check_condition_and_sense(
3468                                         cmd, reason, 1);
3469                         if (ret == -EAGAIN)
3470                                 goto queue_full;
3471
3472                         transport_lun_remove_cmd(cmd);
3473                         transport_cmd_check_stop_to_fabric(cmd);
3474                         return;
3475                 }
3476         }
3477         /*
3478          * Check for a callback, used by amongst other things
3479          * XDWRITE_READ_10 emulation.
3480          */
3481         if (cmd->transport_complete_callback)
3482                 cmd->transport_complete_callback(cmd);
3483
3484         switch (cmd->data_direction) {
3485         case DMA_FROM_DEVICE:
3486                 spin_lock(&cmd->se_lun->lun_sep_lock);
3487                 if (cmd->se_lun->lun_sep) {
3488                         cmd->se_lun->lun_sep->sep_stats.tx_data_octets +=
3489                                         cmd->data_length;
3490                 }
3491                 spin_unlock(&cmd->se_lun->lun_sep_lock);
3492
3493                 ret = cmd->se_tfo->queue_data_in(cmd);
3494                 if (ret == -EAGAIN)
3495                         goto queue_full;
3496                 break;
3497         case DMA_TO_DEVICE:
3498                 spin_lock(&cmd->se_lun->lun_sep_lock);
3499                 if (cmd->se_lun->lun_sep) {
3500                         cmd->se_lun->lun_sep->sep_stats.rx_data_octets +=
3501                                 cmd->data_length;
3502                 }
3503                 spin_unlock(&cmd->se_lun->lun_sep_lock);
3504                 /*
3505                  * Check if we need to send READ payload for BIDI-COMMAND
3506                  */
3507                 if (cmd->t_bidi_data_sg) {
3508                         spin_lock(&cmd->se_lun->lun_sep_lock);
3509                         if (cmd->se_lun->lun_sep) {
3510                                 cmd->se_lun->lun_sep->sep_stats.tx_data_octets +=
3511                                         cmd->data_length;
3512                         }
3513                         spin_unlock(&cmd->se_lun->lun_sep_lock);
3514                         ret = cmd->se_tfo->queue_data_in(cmd);
3515                         if (ret == -EAGAIN)
3516                                 goto queue_full;
3517                         break;
3518                 }
3519                 /* Fall through for DMA_TO_DEVICE */
3520         case DMA_NONE:
3521                 ret = cmd->se_tfo->queue_status(cmd);
3522                 if (ret == -EAGAIN)
3523                         goto queue_full;
3524                 break;
3525         default:
3526                 break;
3527         }
3528
3529         transport_lun_remove_cmd(cmd);
3530         transport_cmd_check_stop_to_fabric(cmd);
3531         return;
3532
3533 queue_full:
3534         pr_debug("Handling complete_ok QUEUE_FULL: se_cmd: %p,"
3535                 " data_direction: %d\n", cmd, cmd->data_direction);
3536         cmd->t_state = TRANSPORT_COMPLETE_QF_OK;
3537         transport_handle_queue_full(cmd, cmd->se_dev);
3538 }
3539
3540 static void transport_free_dev_tasks(struct se_cmd *cmd)
3541 {
3542         struct se_task *task, *task_tmp;
3543         unsigned long flags;
3544         LIST_HEAD(dispose_list);
3545
3546         spin_lock_irqsave(&cmd->t_state_lock, flags);
3547         list_for_each_entry_safe(task, task_tmp,
3548                                 &cmd->t_task_list, t_list) {
3549                 if (!(task->task_flags & TF_ACTIVE))
3550                         list_move_tail(&task->t_list, &dispose_list);
3551         }
3552         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3553
3554         while (!list_empty(&dispose_list)) {
3555                 task = list_first_entry(&dispose_list, struct se_task, t_list);
3556
3557                 /*
3558                  * We already cancelled all pending timers in
3559                  * transport_complete_task, but that was just a pure del_timer,
3560                  * so do a full del_timer_sync here to make sure any handler
3561                  * that was running at that point has finished execution.
3562                  */
3563                 del_timer_sync(&task->task_timer);
3564
3565                 kfree(task->task_sg_bidi);
3566                 kfree(task->task_sg);
3567
3568                 list_del(&task->t_list);
3569
3570                 cmd->se_dev->transport->free_task(task);
3571         }
3572 }
3573
3574 static inline void transport_free_sgl(struct scatterlist *sgl, int nents)
3575 {
3576         struct scatterlist *sg;
3577         int count;
3578
3579         for_each_sg(sgl, sg, nents, count)
3580                 __free_page(sg_page(sg));
3581
3582         kfree(sgl);
3583 }
3584
3585 static inline void transport_free_pages(struct se_cmd *cmd)
3586 {
3587         if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC)
3588                 return;
3589
3590         transport_free_sgl(cmd->t_data_sg, cmd->t_data_nents);
3591         cmd->t_data_sg = NULL;
3592         cmd->t_data_nents = 0;
3593
3594         transport_free_sgl(cmd->t_bidi_data_sg, cmd->t_bidi_data_nents);
3595         cmd->t_bidi_data_sg = NULL;
3596         cmd->t_bidi_data_nents = 0;
3597 }
3598
3599 /**
3600  * transport_put_cmd - release a reference to a command
3601  * @cmd:       command to release
3602  *
3603  * This routine releases our reference to the command and frees it if possible.
3604  */
3605 static void transport_put_cmd(struct se_cmd *cmd)
3606 {
3607         unsigned long flags;
3608         int free_tasks = 0;
3609
3610         spin_lock_irqsave(&cmd->t_state_lock, flags);
3611         if (atomic_read(&cmd->t_fe_count)) {
3612                 if (!atomic_dec_and_test(&cmd->t_fe_count))
3613                         goto out_busy;
3614         }
3615
3616         if (atomic_read(&cmd->t_se_count)) {
3617                 if (!atomic_dec_and_test(&cmd->t_se_count))
3618                         goto out_busy;
3619         }
3620
3621         if (atomic_read(&cmd->transport_dev_active)) {
3622                 atomic_set(&cmd->transport_dev_active, 0);
3623                 transport_all_task_dev_remove_state(cmd);
3624                 free_tasks = 1;
3625         }
3626         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3627
3628         if (free_tasks != 0)
3629                 transport_free_dev_tasks(cmd);
3630
3631         transport_free_pages(cmd);
3632         transport_release_cmd(cmd);
3633         return;
3634 out_busy:
3635         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3636 }
3637
3638 /*
3639  * transport_generic_map_mem_to_cmd - Use fabric-alloced pages instead of
3640  * allocating in the core.
3641  * @cmd:  Associated se_cmd descriptor
3642  * @mem:  SGL style memory for TCM WRITE / READ
3643  * @sg_mem_num: Number of SGL elements
3644  * @mem_bidi_in: SGL style memory for TCM BIDI READ
3645  * @sg_mem_bidi_num: Number of BIDI READ SGL elements
3646  *
3647  * Return: nonzero return cmd was rejected for -ENOMEM or inproper usage
3648  * of parameters.
3649  */
3650 int transport_generic_map_mem_to_cmd(
3651         struct se_cmd *cmd,
3652         struct scatterlist *sgl,
3653         u32 sgl_count,
3654         struct scatterlist *sgl_bidi,
3655         u32 sgl_bidi_count)
3656 {
3657         if (!sgl || !sgl_count)
3658                 return 0;
3659
3660         if ((cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB) ||
3661             (cmd->se_cmd_flags & SCF_SCSI_CONTROL_SG_IO_CDB)) {
3662
3663                 cmd->t_data_sg = sgl;
3664                 cmd->t_data_nents = sgl_count;
3665
3666                 if (sgl_bidi && sgl_bidi_count) {
3667                         cmd->t_bidi_data_sg = sgl_bidi;
3668                         cmd->t_bidi_data_nents = sgl_bidi_count;
3669                 }
3670                 cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
3671         }
3672
3673         return 0;
3674 }
3675 EXPORT_SYMBOL(transport_generic_map_mem_to_cmd);
3676
3677 static int transport_new_cmd_obj(struct se_cmd *cmd)
3678 {
3679         struct se_device *dev = cmd->se_dev;
3680         int set_counts = 1, rc, task_cdbs;
3681
3682         /*
3683          * Setup any BIDI READ tasks and memory from
3684          * cmd->t_mem_bidi_list so the READ struct se_tasks
3685          * are queued first for the non pSCSI passthrough case.
3686          */
3687         if (cmd->t_bidi_data_sg &&
3688             (dev->transport->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV)) {
3689                 rc = transport_allocate_tasks(cmd,
3690                                               cmd->t_task_lba,
3691                                               DMA_FROM_DEVICE,
3692                                               cmd->t_bidi_data_sg,
3693                                               cmd->t_bidi_data_nents);
3694                 if (rc <= 0) {
3695                         cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
3696                         cmd->scsi_sense_reason =
3697                                 TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
3698                         return -EINVAL;
3699                 }
3700                 atomic_inc(&cmd->t_fe_count);
3701                 atomic_inc(&cmd->t_se_count);
3702                 set_counts = 0;
3703         }
3704         /*
3705          * Setup the tasks and memory from cmd->t_mem_list
3706          * Note for BIDI transfers this will contain the WRITE payload
3707          */
3708         task_cdbs = transport_allocate_tasks(cmd,
3709                                              cmd->t_task_lba,
3710                                              cmd->data_direction,
3711                                              cmd->t_data_sg,
3712                                              cmd->t_data_nents);
3713         if (task_cdbs <= 0) {
3714                 cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
3715                 cmd->scsi_sense_reason =
3716                         TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
3717                 return -EINVAL;
3718         }
3719
3720         if (set_counts) {
3721                 atomic_inc(&cmd->t_fe_count);
3722                 atomic_inc(&cmd->t_se_count);
3723         }
3724
3725         cmd->t_task_list_num = task_cdbs;
3726
3727         atomic_set(&cmd->t_task_cdbs_left, task_cdbs);
3728         atomic_set(&cmd->t_task_cdbs_ex_left, task_cdbs);
3729         atomic_set(&cmd->t_task_cdbs_timeout_left, task_cdbs);
3730         return 0;
3731 }
3732
3733 void *transport_kmap_first_data_page(struct se_cmd *cmd)
3734 {
3735         struct scatterlist *sg = cmd->t_data_sg;
3736
3737         BUG_ON(!sg);
3738         /*
3739          * We need to take into account a possible offset here for fabrics like
3740          * tcm_loop who may be using a contig buffer from the SCSI midlayer for
3741          * control CDBs passed as SGLs via transport_generic_map_mem_to_cmd()
3742          */
3743         return kmap(sg_page(sg)) + sg->offset;
3744 }
3745 EXPORT_SYMBOL(transport_kmap_first_data_page);
3746
3747 void transport_kunmap_first_data_page(struct se_cmd *cmd)
3748 {
3749         kunmap(sg_page(cmd->t_data_sg));
3750 }
3751 EXPORT_SYMBOL(transport_kunmap_first_data_page);
3752
3753 static int
3754 transport_generic_get_mem(struct se_cmd *cmd)
3755 {
3756         u32 length = cmd->data_length;
3757         unsigned int nents;
3758         struct page *page;
3759         int i = 0;
3760
3761         nents = DIV_ROUND_UP(length, PAGE_SIZE);
3762         cmd->t_data_sg = kmalloc(sizeof(struct scatterlist) * nents, GFP_KERNEL);
3763         if (!cmd->t_data_sg)
3764                 return -ENOMEM;
3765
3766         cmd->t_data_nents = nents;
3767         sg_init_table(cmd->t_data_sg, nents);
3768
3769         while (length) {
3770                 u32 page_len = min_t(u32, length, PAGE_SIZE);
3771                 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
3772                 if (!page)
3773                         goto out;
3774
3775                 sg_set_page(&cmd->t_data_sg[i], page, page_len, 0);
3776                 length -= page_len;
3777                 i++;
3778         }
3779         return 0;
3780
3781 out:
3782         while (i >= 0) {
3783                 __free_page(sg_page(&cmd->t_data_sg[i]));
3784                 i--;
3785         }
3786         kfree(cmd->t_data_sg);
3787         cmd->t_data_sg = NULL;
3788         return -ENOMEM;
3789 }
3790
3791 /* Reduce sectors if they are too long for the device */
3792 static inline sector_t transport_limit_task_sectors(
3793         struct se_device *dev,
3794         unsigned long long lba,
3795         sector_t sectors)
3796 {
3797         sectors = min_t(sector_t, sectors, dev->se_sub_dev->se_dev_attrib.max_sectors);
3798
3799         if (dev->transport->get_device_type(dev) == TYPE_DISK)
3800                 if ((lba + sectors) > transport_dev_end_lba(dev))
3801                         sectors = ((transport_dev_end_lba(dev) - lba) + 1);
3802
3803         return sectors;
3804 }
3805
3806
3807 /*
3808  * This function can be used by HW target mode drivers to create a linked
3809  * scatterlist from all contiguously allocated struct se_task->task_sg[].
3810  * This is intended to be called during the completion path by TCM Core
3811  * when struct target_core_fabric_ops->check_task_sg_chaining is enabled.
3812  */
3813 void transport_do_task_sg_chain(struct se_cmd *cmd)
3814 {
3815         struct scatterlist *sg_first = NULL;
3816         struct scatterlist *sg_prev = NULL;
3817         int sg_prev_nents = 0;
3818         struct scatterlist *sg;
3819         struct se_task *task;
3820         u32 chained_nents = 0;
3821         int i;
3822
3823         BUG_ON(!cmd->se_tfo->task_sg_chaining);
3824
3825         /*
3826          * Walk the struct se_task list and setup scatterlist chains
3827          * for each contiguously allocated struct se_task->task_sg[].
3828          */
3829         list_for_each_entry(task, &cmd->t_task_list, t_list) {
3830                 if (!task->task_sg)
3831                         continue;
3832
3833                 if (!sg_first) {
3834                         sg_first = task->task_sg;
3835                         chained_nents = task->task_sg_nents;
3836                 } else {
3837                         sg_chain(sg_prev, sg_prev_nents, task->task_sg);
3838                         chained_nents += task->task_sg_nents;
3839                 }
3840                 /*
3841                  * For the padded tasks, use the extra SGL vector allocated
3842                  * in transport_allocate_data_tasks() for the sg_prev_nents
3843                  * offset into sg_chain() above.
3844                  *
3845                  * We do not need the padding for the last task (or a single
3846                  * task), but in that case we will never use the sg_prev_nents
3847                  * value below which would be incorrect.
3848                  */
3849                 sg_prev_nents = (task->task_sg_nents + 1);
3850                 sg_prev = task->task_sg;
3851         }
3852         /*
3853          * Setup the starting pointer and total t_tasks_sg_linked_no including
3854          * padding SGs for linking and to mark the end.
3855          */
3856         cmd->t_tasks_sg_chained = sg_first;
3857         cmd->t_tasks_sg_chained_no = chained_nents;
3858
3859         pr_debug("Setup cmd: %p cmd->t_tasks_sg_chained: %p and"
3860                 " t_tasks_sg_chained_no: %u\n", cmd, cmd->t_tasks_sg_chained,
3861                 cmd->t_tasks_sg_chained_no);
3862
3863         for_each_sg(cmd->t_tasks_sg_chained, sg,
3864                         cmd->t_tasks_sg_chained_no, i) {
3865
3866                 pr_debug("SG[%d]: %p page: %p length: %d offset: %d\n",
3867                         i, sg, sg_page(sg), sg->length, sg->offset);
3868                 if (sg_is_chain(sg))
3869                         pr_debug("SG: %p sg_is_chain=1\n", sg);
3870                 if (sg_is_last(sg))
3871                         pr_debug("SG: %p sg_is_last=1\n", sg);
3872         }
3873 }
3874 EXPORT_SYMBOL(transport_do_task_sg_chain);
3875
3876 /*
3877  * Break up cmd into chunks transport can handle
3878  */
3879 static int transport_allocate_data_tasks(
3880         struct se_cmd *cmd,
3881         unsigned long long lba,
3882         enum dma_data_direction data_direction,
3883         struct scatterlist *sgl,
3884         unsigned int sgl_nents)
3885 {
3886         struct se_task *task;
3887         struct se_device *dev = cmd->se_dev;
3888         unsigned long flags;
3889         int task_count, i;
3890         sector_t sectors, dev_max_sectors = dev->se_sub_dev->se_dev_attrib.max_sectors;
3891         u32 sector_size = dev->se_sub_dev->se_dev_attrib.block_size;
3892         struct scatterlist *sg;
3893         struct scatterlist *cmd_sg;
3894
3895         WARN_ON(cmd->data_length % sector_size);
3896         sectors = DIV_ROUND_UP(cmd->data_length, sector_size);
3897         task_count = DIV_ROUND_UP_SECTOR_T(sectors, dev_max_sectors);
3898         
3899         cmd_sg = sgl;
3900         for (i = 0; i < task_count; i++) {
3901                 unsigned int task_size, task_sg_nents_padded;
3902                 int count;
3903
3904                 task = transport_generic_get_task(cmd, data_direction);
3905                 if (!task)
3906                         return -ENOMEM;
3907
3908                 task->task_lba = lba;
3909                 task->task_sectors = min(sectors, dev_max_sectors);
3910                 task->task_size = task->task_sectors * sector_size;
3911
3912                 /*
3913                  * This now assumes that passed sg_ents are in PAGE_SIZE chunks
3914                  * in order to calculate the number per task SGL entries
3915                  */
3916                 task->task_sg_nents = DIV_ROUND_UP(task->task_size, PAGE_SIZE);
3917                 /*
3918                  * Check if the fabric module driver is requesting that all
3919                  * struct se_task->task_sg[] be chained together..  If so,
3920                  * then allocate an extra padding SG entry for linking and
3921                  * marking the end of the chained SGL for every task except
3922                  * the last one for (task_count > 1) operation, or skipping
3923                  * the extra padding for the (task_count == 1) case.
3924                  */
3925                 if (cmd->se_tfo->task_sg_chaining && (i < (task_count - 1))) {
3926                         task_sg_nents_padded = (task->task_sg_nents + 1);
3927                 } else
3928                         task_sg_nents_padded = task->task_sg_nents;
3929
3930                 task->task_sg = kmalloc(sizeof(struct scatterlist) *
3931                                         task_sg_nents_padded, GFP_KERNEL);
3932                 if (!task->task_sg) {
3933                         cmd->se_dev->transport->free_task(task);
3934                         return -ENOMEM;
3935                 }
3936
3937                 sg_init_table(task->task_sg, task_sg_nents_padded);
3938
3939                 task_size = task->task_size;
3940
3941                 /* Build new sgl, only up to task_size */
3942                 for_each_sg(task->task_sg, sg, task->task_sg_nents, count) {
3943                         if (cmd_sg->length > task_size)
3944                                 break;
3945
3946                         *sg = *cmd_sg;
3947                         task_size -= cmd_sg->length;
3948                         cmd_sg = sg_next(cmd_sg);
3949                 }
3950
3951                 lba += task->task_sectors;
3952                 sectors -= task->task_sectors;
3953
3954                 spin_lock_irqsave(&cmd->t_state_lock, flags);
3955                 list_add_tail(&task->t_list, &cmd->t_task_list);
3956                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3957         }
3958
3959         return task_count;
3960 }
3961
3962 static int
3963 transport_allocate_control_task(struct se_cmd *cmd)
3964 {
3965         struct se_task *task;
3966         unsigned long flags;
3967
3968         task = transport_generic_get_task(cmd, cmd->data_direction);
3969         if (!task)
3970                 return -ENOMEM;
3971
3972         task->task_sg = kmalloc(sizeof(struct scatterlist) * cmd->t_data_nents,
3973                                 GFP_KERNEL);
3974         if (!task->task_sg) {
3975                 cmd->se_dev->transport->free_task(task);
3976                 return -ENOMEM;
3977         }
3978
3979         memcpy(task->task_sg, cmd->t_data_sg,
3980                sizeof(struct scatterlist) * cmd->t_data_nents);
3981         task->task_size = cmd->data_length;
3982         task->task_sg_nents = cmd->t_data_nents;
3983
3984         spin_lock_irqsave(&cmd->t_state_lock, flags);
3985         list_add_tail(&task->t_list, &cmd->t_task_list);
3986         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3987
3988         /* Success! Return number of tasks allocated */
3989         return 1;
3990 }
3991
3992 static u32 transport_allocate_tasks(
3993         struct se_cmd *cmd,
3994         unsigned long long lba,
3995         enum dma_data_direction data_direction,
3996         struct scatterlist *sgl,
3997         unsigned int sgl_nents)
3998 {
3999         if (cmd->se_cmd_flags & SCF_SCSI_DATA_SG_IO_CDB) {
4000                 if (transport_cmd_get_valid_sectors(cmd) < 0)
4001                         return -EINVAL;
4002
4003                 return transport_allocate_data_tasks(cmd, lba, data_direction,
4004                                                      sgl, sgl_nents);
4005         } else
4006                 return transport_allocate_control_task(cmd);
4007
4008 }
4009
4010
4011 /*       transport_generic_new_cmd(): Called from transport_processing_thread()
4012  *
4013  *       Allocate storage transport resources from a set of values predefined
4014  *       by transport_generic_cmd_sequencer() from the iSCSI Target RX process.
4015  *       Any non zero return here is treated as an "out of resource' op here.
4016  */
4017         /*
4018          * Generate struct se_task(s) and/or their payloads for this CDB.
4019          */
4020 int transport_generic_new_cmd(struct se_cmd *cmd)
4021 {
4022         int ret = 0;
4023
4024         /*
4025          * Determine is the TCM fabric module has already allocated physical
4026          * memory, and is directly calling transport_generic_map_mem_to_cmd()
4027          * beforehand.
4028          */
4029         if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) &&
4030             cmd->data_length) {
4031                 ret = transport_generic_get_mem(cmd);
4032                 if (ret < 0)
4033                         return ret;
4034         }
4035         /*
4036          * Call transport_new_cmd_obj() to invoke transport_allocate_tasks() for
4037          * control or data CDB types, and perform the map to backend subsystem
4038          * code from SGL memory allocated here by transport_generic_get_mem(), or
4039          * via pre-existing SGL memory setup explictly by fabric module code with
4040          * transport_generic_map_mem_to_cmd().
4041          */
4042         ret = transport_new_cmd_obj(cmd);
4043         if (ret < 0)
4044                 return ret;
4045         /*
4046          * For WRITEs, let the fabric know its buffer is ready..
4047          * This WRITE struct se_cmd (and all of its associated struct se_task's)
4048          * will be added to the struct se_device execution queue after its WRITE
4049          * data has arrived. (ie: It gets handled by the transport processing
4050          * thread a second time)
4051          */
4052         if (cmd->data_direction == DMA_TO_DEVICE) {
4053                 transport_add_tasks_to_state_queue(cmd);
4054                 return transport_generic_write_pending(cmd);
4055         }
4056         /*
4057          * Everything else but a WRITE, add the struct se_cmd's struct se_task's
4058          * to the execution queue.
4059          */
4060         transport_execute_tasks(cmd);
4061         return 0;
4062 }
4063 EXPORT_SYMBOL(transport_generic_new_cmd);
4064
4065 /*      transport_generic_process_write():
4066  *
4067  *
4068  */
4069 void transport_generic_process_write(struct se_cmd *cmd)
4070 {
4071         transport_execute_tasks(cmd);
4072 }
4073 EXPORT_SYMBOL(transport_generic_process_write);
4074
4075 static void transport_write_pending_qf(struct se_cmd *cmd)
4076 {
4077         if (cmd->se_tfo->write_pending(cmd) == -EAGAIN) {
4078                 pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n",
4079                          cmd);
4080                 transport_handle_queue_full(cmd, cmd->se_dev);
4081         }
4082 }
4083
4084 static int transport_generic_write_pending(struct se_cmd *cmd)
4085 {
4086         unsigned long flags;
4087         int ret;
4088
4089         spin_lock_irqsave(&cmd->t_state_lock, flags);
4090         cmd->t_state = TRANSPORT_WRITE_PENDING;
4091         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4092
4093         /*
4094          * Clear the se_cmd for WRITE_PENDING status in order to set
4095          * cmd->t_transport_active=0 so that transport_generic_handle_data
4096          * can be called from HW target mode interrupt code.  This is safe
4097          * to be called with transport_off=1 before the cmd->se_tfo->write_pending
4098          * because the se_cmd->se_lun pointer is not being cleared.
4099          */
4100         transport_cmd_check_stop(cmd, 1, 0);
4101
4102         /*
4103          * Call the fabric write_pending function here to let the
4104          * frontend know that WRITE buffers are ready.
4105          */
4106         ret = cmd->se_tfo->write_pending(cmd);
4107         if (ret == -EAGAIN)
4108                 goto queue_full;
4109         else if (ret < 0)
4110                 return ret;
4111
4112         return PYX_TRANSPORT_WRITE_PENDING;
4113
4114 queue_full:
4115         pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n", cmd);
4116         cmd->t_state = TRANSPORT_COMPLETE_QF_WP;
4117         transport_handle_queue_full(cmd, cmd->se_dev);
4118         return ret;
4119 }
4120
4121 /**
4122  * transport_release_cmd - free a command
4123  * @cmd:       command to free
4124  *
4125  * This routine unconditionally frees a command, and reference counting
4126  * or list removal must be done in the caller.
4127  */
4128 void transport_release_cmd(struct se_cmd *cmd)
4129 {
4130         BUG_ON(!cmd->se_tfo);
4131
4132         if (cmd->se_tmr_req)
4133                 core_tmr_release_req(cmd->se_tmr_req);
4134         if (cmd->t_task_cdb != cmd->__t_task_cdb)
4135                 kfree(cmd->t_task_cdb);
4136         cmd->se_tfo->release_cmd(cmd);
4137 }
4138 EXPORT_SYMBOL(transport_release_cmd);
4139
4140 void transport_generic_free_cmd(struct se_cmd *cmd, int wait_for_tasks)
4141 {
4142         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD)) {
4143                 if (wait_for_tasks && cmd->se_tmr_req)
4144                          transport_wait_for_tasks(cmd);
4145
4146                 transport_release_cmd(cmd);
4147         } else {
4148                 if (wait_for_tasks)
4149                         transport_wait_for_tasks(cmd);
4150
4151                 core_dec_lacl_count(cmd->se_sess->se_node_acl, cmd);
4152
4153                 if (cmd->se_lun)
4154                         transport_lun_remove_cmd(cmd);
4155
4156                 transport_free_dev_tasks(cmd);
4157
4158                 transport_put_cmd(cmd);
4159         }
4160 }
4161 EXPORT_SYMBOL(transport_generic_free_cmd);
4162
4163 /*      transport_lun_wait_for_tasks():
4164  *
4165  *      Called from ConfigFS context to stop the passed struct se_cmd to allow
4166  *      an struct se_lun to be successfully shutdown.
4167  */
4168 static int transport_lun_wait_for_tasks(struct se_cmd *cmd, struct se_lun *lun)
4169 {
4170         unsigned long flags;
4171         int ret;
4172         /*
4173          * If the frontend has already requested this struct se_cmd to
4174          * be stopped, we can safely ignore this struct se_cmd.
4175          */
4176         spin_lock_irqsave(&cmd->t_state_lock, flags);
4177         if (atomic_read(&cmd->t_transport_stop)) {
4178                 atomic_set(&cmd->transport_lun_stop, 0);
4179                 pr_debug("ConfigFS ITT[0x%08x] - t_transport_stop =="
4180                         " TRUE, skipping\n", cmd->se_tfo->get_task_tag(cmd));
4181                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4182                 transport_cmd_check_stop(cmd, 1, 0);
4183                 return -EPERM;
4184         }
4185         atomic_set(&cmd->transport_lun_fe_stop, 1);
4186         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4187
4188         wake_up_interruptible(&cmd->se_dev->dev_queue_obj.thread_wq);
4189
4190         ret = transport_stop_tasks_for_cmd(cmd);
4191
4192         pr_debug("ConfigFS: cmd: %p t_tasks: %d stop tasks ret:"
4193                         " %d\n", cmd, cmd->t_task_list_num, ret);
4194         if (!ret) {
4195                 pr_debug("ConfigFS: ITT[0x%08x] - stopping cmd....\n",
4196                                 cmd->se_tfo->get_task_tag(cmd));
4197                 wait_for_completion(&cmd->transport_lun_stop_comp);
4198                 pr_debug("ConfigFS: ITT[0x%08x] - stopped cmd....\n",
4199                                 cmd->se_tfo->get_task_tag(cmd));
4200         }
4201         transport_remove_cmd_from_queue(cmd);
4202
4203         return 0;
4204 }
4205
4206 static void __transport_clear_lun_from_sessions(struct se_lun *lun)
4207 {
4208         struct se_cmd *cmd = NULL;
4209         unsigned long lun_flags, cmd_flags;
4210         /*
4211          * Do exception processing and return CHECK_CONDITION status to the
4212          * Initiator Port.
4213          */
4214         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
4215         while (!list_empty(&lun->lun_cmd_list)) {
4216                 cmd = list_first_entry(&lun->lun_cmd_list,
4217                        struct se_cmd, se_lun_node);
4218                 list_del(&cmd->se_lun_node);
4219
4220                 atomic_set(&cmd->transport_lun_active, 0);
4221                 /*
4222                  * This will notify iscsi_target_transport.c:
4223                  * transport_cmd_check_stop() that a LUN shutdown is in
4224                  * progress for the iscsi_cmd_t.
4225                  */
4226                 spin_lock(&cmd->t_state_lock);
4227                 pr_debug("SE_LUN[%d] - Setting cmd->transport"
4228                         "_lun_stop for  ITT: 0x%08x\n",
4229                         cmd->se_lun->unpacked_lun,
4230                         cmd->se_tfo->get_task_tag(cmd));
4231                 atomic_set(&cmd->transport_lun_stop, 1);
4232                 spin_unlock(&cmd->t_state_lock);
4233
4234                 spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
4235
4236                 if (!cmd->se_lun) {
4237                         pr_err("ITT: 0x%08x, [i,t]_state: %u/%u\n",
4238                                 cmd->se_tfo->get_task_tag(cmd),
4239                                 cmd->se_tfo->get_cmd_state(cmd), cmd->t_state);
4240                         BUG();
4241                 }
4242                 /*
4243                  * If the Storage engine still owns the iscsi_cmd_t, determine
4244                  * and/or stop its context.
4245                  */
4246                 pr_debug("SE_LUN[%d] - ITT: 0x%08x before transport"
4247                         "_lun_wait_for_tasks()\n", cmd->se_lun->unpacked_lun,
4248                         cmd->se_tfo->get_task_tag(cmd));
4249
4250                 if (transport_lun_wait_for_tasks(cmd, cmd->se_lun) < 0) {
4251                         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
4252                         continue;
4253                 }
4254
4255                 pr_debug("SE_LUN[%d] - ITT: 0x%08x after transport_lun"
4256                         "_wait_for_tasks(): SUCCESS\n",
4257                         cmd->se_lun->unpacked_lun,
4258                         cmd->se_tfo->get_task_tag(cmd));
4259
4260                 spin_lock_irqsave(&cmd->t_state_lock, cmd_flags);
4261                 if (!atomic_read(&cmd->transport_dev_active)) {
4262                         spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
4263                         goto check_cond;
4264                 }
4265                 atomic_set(&cmd->transport_dev_active, 0);
4266                 transport_all_task_dev_remove_state(cmd);
4267                 spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
4268
4269                 transport_free_dev_tasks(cmd);
4270                 /*
4271                  * The Storage engine stopped this struct se_cmd before it was
4272                  * send to the fabric frontend for delivery back to the
4273                  * Initiator Node.  Return this SCSI CDB back with an
4274                  * CHECK_CONDITION status.
4275                  */
4276 check_cond:
4277                 transport_send_check_condition_and_sense(cmd,
4278                                 TCM_NON_EXISTENT_LUN, 0);
4279                 /*
4280                  *  If the fabric frontend is waiting for this iscsi_cmd_t to
4281                  * be released, notify the waiting thread now that LU has
4282                  * finished accessing it.
4283                  */
4284                 spin_lock_irqsave(&cmd->t_state_lock, cmd_flags);
4285                 if (atomic_read(&cmd->transport_lun_fe_stop)) {
4286                         pr_debug("SE_LUN[%d] - Detected FE stop for"
4287                                 " struct se_cmd: %p ITT: 0x%08x\n",
4288                                 lun->unpacked_lun,
4289                                 cmd, cmd->se_tfo->get_task_tag(cmd));
4290
4291                         spin_unlock_irqrestore(&cmd->t_state_lock,
4292                                         cmd_flags);
4293                         transport_cmd_check_stop(cmd, 1, 0);
4294                         complete(&cmd->transport_lun_fe_stop_comp);
4295                         spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
4296                         continue;
4297                 }
4298                 pr_debug("SE_LUN[%d] - ITT: 0x%08x finished processing\n",
4299                         lun->unpacked_lun, cmd->se_tfo->get_task_tag(cmd));
4300
4301                 spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
4302                 spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
4303         }
4304         spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
4305 }
4306
4307 static int transport_clear_lun_thread(void *p)
4308 {
4309         struct se_lun *lun = (struct se_lun *)p;
4310
4311         __transport_clear_lun_from_sessions(lun);
4312         complete(&lun->lun_shutdown_comp);
4313
4314         return 0;
4315 }
4316
4317 int transport_clear_lun_from_sessions(struct se_lun *lun)
4318 {
4319         struct task_struct *kt;
4320
4321         kt = kthread_run(transport_clear_lun_thread, lun,
4322                         "tcm_cl_%u", lun->unpacked_lun);
4323         if (IS_ERR(kt)) {
4324                 pr_err("Unable to start clear_lun thread\n");
4325                 return PTR_ERR(kt);
4326         }
4327         wait_for_completion(&lun->lun_shutdown_comp);
4328
4329         return 0;
4330 }
4331
4332 /**
4333  * transport_wait_for_tasks - wait for completion to occur
4334  * @cmd:        command to wait
4335  *
4336  * Called from frontend fabric context to wait for storage engine
4337  * to pause and/or release frontend generated struct se_cmd.
4338  */
4339 void transport_wait_for_tasks(struct se_cmd *cmd)
4340 {
4341         unsigned long flags;
4342
4343         spin_lock_irqsave(&cmd->t_state_lock, flags);
4344         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) && !(cmd->se_tmr_req)) {
4345                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4346                 return;
4347         }
4348         /*
4349          * Only perform a possible wait_for_tasks if SCF_SUPPORTED_SAM_OPCODE
4350          * has been set in transport_set_supported_SAM_opcode().
4351          */
4352         if (!(cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE) && !cmd->se_tmr_req) {
4353                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4354                 return;
4355         }
4356         /*
4357          * If we are already stopped due to an external event (ie: LUN shutdown)
4358          * sleep until the connection can have the passed struct se_cmd back.
4359          * The cmd->transport_lun_stopped_sem will be upped by
4360          * transport_clear_lun_from_sessions() once the ConfigFS context caller
4361          * has completed its operation on the struct se_cmd.
4362          */
4363         if (atomic_read(&cmd->transport_lun_stop)) {
4364
4365                 pr_debug("wait_for_tasks: Stopping"
4366                         " wait_for_completion(&cmd->t_tasktransport_lun_fe"
4367                         "_stop_comp); for ITT: 0x%08x\n",
4368                         cmd->se_tfo->get_task_tag(cmd));
4369                 /*
4370                  * There is a special case for WRITES where a FE exception +
4371                  * LUN shutdown means ConfigFS context is still sleeping on
4372                  * transport_lun_stop_comp in transport_lun_wait_for_tasks().
4373                  * We go ahead and up transport_lun_stop_comp just to be sure
4374                  * here.
4375                  */
4376                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4377                 complete(&cmd->transport_lun_stop_comp);
4378                 wait_for_completion(&cmd->transport_lun_fe_stop_comp);
4379                 spin_lock_irqsave(&cmd->t_state_lock, flags);
4380
4381                 transport_all_task_dev_remove_state(cmd);
4382                 /*
4383                  * At this point, the frontend who was the originator of this
4384                  * struct se_cmd, now owns the structure and can be released through
4385                  * normal means below.
4386                  */
4387                 pr_debug("wait_for_tasks: Stopped"
4388                         " wait_for_completion(&cmd->t_tasktransport_lun_fe_"
4389                         "stop_comp); for ITT: 0x%08x\n",
4390                         cmd->se_tfo->get_task_tag(cmd));
4391
4392                 atomic_set(&cmd->transport_lun_stop, 0);
4393         }
4394         if (!atomic_read(&cmd->t_transport_active) ||
4395              atomic_read(&cmd->t_transport_aborted)) {
4396                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4397                 return;
4398         }
4399
4400         atomic_set(&cmd->t_transport_stop, 1);
4401
4402         pr_debug("wait_for_tasks: Stopping %p ITT: 0x%08x"
4403                 " i_state: %d, t_state: %d, t_transport_stop = TRUE\n",
4404                 cmd, cmd->se_tfo->get_task_tag(cmd),
4405                 cmd->se_tfo->get_cmd_state(cmd), cmd->t_state);
4406
4407         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4408
4409         wake_up_interruptible(&cmd->se_dev->dev_queue_obj.thread_wq);
4410
4411         wait_for_completion(&cmd->t_transport_stop_comp);
4412
4413         spin_lock_irqsave(&cmd->t_state_lock, flags);
4414         atomic_set(&cmd->t_transport_active, 0);
4415         atomic_set(&cmd->t_transport_stop, 0);
4416
4417         pr_debug("wait_for_tasks: Stopped wait_for_compltion("
4418                 "&cmd->t_transport_stop_comp) for ITT: 0x%08x\n",
4419                 cmd->se_tfo->get_task_tag(cmd));
4420
4421         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4422 }
4423 EXPORT_SYMBOL(transport_wait_for_tasks);
4424
4425 static int transport_get_sense_codes(
4426         struct se_cmd *cmd,
4427         u8 *asc,
4428         u8 *ascq)
4429 {
4430         *asc = cmd->scsi_asc;
4431         *ascq = cmd->scsi_ascq;
4432
4433         return 0;
4434 }
4435
4436 static int transport_set_sense_codes(
4437         struct se_cmd *cmd,
4438         u8 asc,
4439         u8 ascq)
4440 {
4441         cmd->scsi_asc = asc;
4442         cmd->scsi_ascq = ascq;
4443
4444         return 0;
4445 }
4446
4447 int transport_send_check_condition_and_sense(
4448         struct se_cmd *cmd,
4449         u8 reason,
4450         int from_transport)
4451 {
4452         unsigned char *buffer = cmd->sense_buffer;
4453         unsigned long flags;
4454         int offset;
4455         u8 asc = 0, ascq = 0;
4456
4457         spin_lock_irqsave(&cmd->t_state_lock, flags);
4458         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
4459                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4460                 return 0;
4461         }
4462         cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
4463         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4464
4465         if (!reason && from_transport)
4466                 goto after_reason;
4467
4468         if (!from_transport)
4469                 cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
4470         /*
4471          * Data Segment and SenseLength of the fabric response PDU.
4472          *
4473          * TRANSPORT_SENSE_BUFFER is now set to SCSI_SENSE_BUFFERSIZE
4474          * from include/scsi/scsi_cmnd.h
4475          */
4476         offset = cmd->se_tfo->set_fabric_sense_len(cmd,
4477                                 TRANSPORT_SENSE_BUFFER);
4478         /*
4479          * Actual SENSE DATA, see SPC-3 7.23.2  SPC_SENSE_KEY_OFFSET uses
4480          * SENSE KEY values from include/scsi/scsi.h
4481          */
4482         switch (reason) {
4483         case TCM_NON_EXISTENT_LUN:
4484                 /* CURRENT ERROR */
4485                 buffer[offset] = 0x70;
4486                 /* ILLEGAL REQUEST */
4487                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
4488                 /* LOGICAL UNIT NOT SUPPORTED */
4489                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x25;
4490                 break;
4491         case TCM_UNSUPPORTED_SCSI_OPCODE:
4492         case TCM_SECTOR_COUNT_TOO_MANY:
4493                 /* CURRENT ERROR */
4494                 buffer[offset] = 0x70;
4495                 /* ILLEGAL REQUEST */
4496                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
4497                 /* INVALID COMMAND OPERATION CODE */
4498                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x20;
4499                 break;
4500         case TCM_UNKNOWN_MODE_PAGE:
4501                 /* CURRENT ERROR */
4502                 buffer[offset] = 0x70;
4503                 /* ILLEGAL REQUEST */
4504                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
4505                 /* INVALID FIELD IN CDB */
4506                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x24;
4507                 break;
4508         case TCM_CHECK_CONDITION_ABORT_CMD:
4509                 /* CURRENT ERROR */
4510                 buffer[offset] = 0x70;
4511                 /* ABORTED COMMAND */
4512                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
4513                 /* BUS DEVICE RESET FUNCTION OCCURRED */
4514                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x29;
4515                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x03;
4516                 break;
4517         case TCM_INCORRECT_AMOUNT_OF_DATA:
4518                 /* CURRENT ERROR */
4519                 buffer[offset] = 0x70;
4520                 /* ABORTED COMMAND */
4521                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
4522                 /* WRITE ERROR */
4523                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x0c;
4524                 /* NOT ENOUGH UNSOLICITED DATA */
4525                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x0d;
4526                 break;
4527         case TCM_INVALID_CDB_FIELD:
4528                 /* CURRENT ERROR */
4529                 buffer[offset] = 0x70;
4530                 /* ABORTED COMMAND */
4531                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
4532                 /* INVALID FIELD IN CDB */
4533                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x24;
4534                 break;
4535         case TCM_INVALID_PARAMETER_LIST:
4536                 /* CURRENT ERROR */
4537                 buffer[offset] = 0x70;
4538                 /* ABORTED COMMAND */
4539                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
4540                 /* INVALID FIELD IN PARAMETER LIST */
4541                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x26;
4542                 break;
4543         case TCM_UNEXPECTED_UNSOLICITED_DATA:
4544                 /* CURRENT ERROR */
4545                 buffer[offset] = 0x70;
4546                 /* ABORTED COMMAND */
4547                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
4548                 /* WRITE ERROR */
4549                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x0c;
4550                 /* UNEXPECTED_UNSOLICITED_DATA */
4551                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x0c;
4552                 break;
4553         case TCM_SERVICE_CRC_ERROR:
4554                 /* CURRENT ERROR */
4555                 buffer[offset] = 0x70;
4556                 /* ABORTED COMMAND */
4557                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
4558                 /* PROTOCOL SERVICE CRC ERROR */
4559                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x47;
4560                 /* N/A */
4561                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x05;
4562                 break;
4563         case TCM_SNACK_REJECTED:
4564                 /* CURRENT ERROR */
4565                 buffer[offset] = 0x70;
4566                 /* ABORTED COMMAND */
4567                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
4568                 /* READ ERROR */
4569                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x11;
4570                 /* FAILED RETRANSMISSION REQUEST */
4571                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x13;
4572                 break;
4573         case TCM_WRITE_PROTECTED:
4574                 /* CURRENT ERROR */
4575                 buffer[offset] = 0x70;
4576                 /* DATA PROTECT */
4577                 buffer[offset+SPC_SENSE_KEY_OFFSET] = DATA_PROTECT;
4578                 /* WRITE PROTECTED */
4579                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x27;
4580                 break;
4581         case TCM_CHECK_CONDITION_UNIT_ATTENTION:
4582                 /* CURRENT ERROR */
4583                 buffer[offset] = 0x70;
4584                 /* UNIT ATTENTION */
4585                 buffer[offset+SPC_SENSE_KEY_OFFSET] = UNIT_ATTENTION;
4586                 core_scsi3_ua_for_check_condition(cmd, &asc, &ascq);
4587                 buffer[offset+SPC_ASC_KEY_OFFSET] = asc;
4588                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = ascq;
4589                 break;
4590         case TCM_CHECK_CONDITION_NOT_READY:
4591                 /* CURRENT ERROR */
4592                 buffer[offset] = 0x70;
4593                 /* Not Ready */
4594                 buffer[offset+SPC_SENSE_KEY_OFFSET] = NOT_READY;
4595                 transport_get_sense_codes(cmd, &asc, &ascq);
4596                 buffer[offset+SPC_ASC_KEY_OFFSET] = asc;
4597                 buffer[offset+SPC_ASCQ_KEY_OFFSET] = ascq;
4598                 break;
4599         case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
4600         default:
4601                 /* CURRENT ERROR */
4602                 buffer[offset] = 0x70;
4603                 /* ILLEGAL REQUEST */
4604                 buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
4605                 /* LOGICAL UNIT COMMUNICATION FAILURE */
4606                 buffer[offset+SPC_ASC_KEY_OFFSET] = 0x80;
4607                 break;
4608         }
4609         /*
4610          * This code uses linux/include/scsi/scsi.h SAM status codes!
4611          */
4612         cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
4613         /*
4614          * Automatically padded, this value is encoded in the fabric's
4615          * data_length response PDU containing the SCSI defined sense data.
4616          */
4617         cmd->scsi_sense_length  = TRANSPORT_SENSE_BUFFER + offset;
4618
4619 after_reason:
4620         return cmd->se_tfo->queue_status(cmd);
4621 }
4622 EXPORT_SYMBOL(transport_send_check_condition_and_sense);
4623
4624 int transport_check_aborted_status(struct se_cmd *cmd, int send_status)
4625 {
4626         int ret = 0;
4627
4628         if (atomic_read(&cmd->t_transport_aborted) != 0) {
4629                 if (!send_status ||
4630                      (cmd->se_cmd_flags & SCF_SENT_DELAYED_TAS))
4631                         return 1;
4632 #if 0
4633                 pr_debug("Sending delayed SAM_STAT_TASK_ABORTED"
4634                         " status for CDB: 0x%02x ITT: 0x%08x\n",
4635                         cmd->t_task_cdb[0],
4636                         cmd->se_tfo->get_task_tag(cmd));
4637 #endif
4638                 cmd->se_cmd_flags |= SCF_SENT_DELAYED_TAS;
4639                 cmd->se_tfo->queue_status(cmd);
4640                 ret = 1;
4641         }
4642         return ret;
4643 }
4644 EXPORT_SYMBOL(transport_check_aborted_status);
4645
4646 void transport_send_task_abort(struct se_cmd *cmd)
4647 {
4648         unsigned long flags;
4649
4650         spin_lock_irqsave(&cmd->t_state_lock, flags);
4651         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
4652                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4653                 return;
4654         }
4655         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
4656
4657         /*
4658          * If there are still expected incoming fabric WRITEs, we wait
4659          * until until they have completed before sending a TASK_ABORTED
4660          * response.  This response with TASK_ABORTED status will be
4661          * queued back to fabric module by transport_check_aborted_status().
4662          */
4663         if (cmd->data_direction == DMA_TO_DEVICE) {
4664                 if (cmd->se_tfo->write_pending_status(cmd) != 0) {
4665                         atomic_inc(&cmd->t_transport_aborted);
4666                         smp_mb__after_atomic_inc();
4667                         cmd->scsi_status = SAM_STAT_TASK_ABORTED;
4668                         transport_new_cmd_failure(cmd);
4669                         return;
4670                 }
4671         }
4672         cmd->scsi_status = SAM_STAT_TASK_ABORTED;
4673 #if 0
4674         pr_debug("Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x,"
4675                 " ITT: 0x%08x\n", cmd->t_task_cdb[0],
4676                 cmd->se_tfo->get_task_tag(cmd));
4677 #endif
4678         cmd->se_tfo->queue_status(cmd);
4679 }
4680
4681 /*      transport_generic_do_tmr():
4682  *
4683  *
4684  */
4685 int transport_generic_do_tmr(struct se_cmd *cmd)
4686 {
4687         struct se_device *dev = cmd->se_dev;
4688         struct se_tmr_req *tmr = cmd->se_tmr_req;
4689         int ret;
4690
4691         switch (tmr->function) {
4692         case TMR_ABORT_TASK:
4693                 tmr->response = TMR_FUNCTION_REJECTED;
4694                 break;
4695         case TMR_ABORT_TASK_SET:
4696         case TMR_CLEAR_ACA:
4697         case TMR_CLEAR_TASK_SET:
4698                 tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
4699                 break;
4700         case TMR_LUN_RESET:
4701                 ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
4702                 tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
4703                                          TMR_FUNCTION_REJECTED;
4704                 break;
4705         case TMR_TARGET_WARM_RESET:
4706                 tmr->response = TMR_FUNCTION_REJECTED;
4707                 break;
4708         case TMR_TARGET_COLD_RESET:
4709                 tmr->response = TMR_FUNCTION_REJECTED;
4710                 break;
4711         default:
4712                 pr_err("Uknown TMR function: 0x%02x.\n",
4713                                 tmr->function);
4714                 tmr->response = TMR_FUNCTION_REJECTED;
4715                 break;
4716         }
4717
4718         cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
4719         cmd->se_tfo->queue_tm_rsp(cmd);
4720
4721         transport_cmd_check_stop_to_fabric(cmd);
4722         return 0;
4723 }
4724
4725 /*      transport_processing_thread():
4726  *
4727  *
4728  */
4729 static int transport_processing_thread(void *param)
4730 {
4731         int ret;
4732         struct se_cmd *cmd;
4733         struct se_device *dev = (struct se_device *) param;
4734
4735         set_user_nice(current, -20);
4736
4737         while (!kthread_should_stop()) {
4738                 ret = wait_event_interruptible(dev->dev_queue_obj.thread_wq,
4739                                 atomic_read(&dev->dev_queue_obj.queue_cnt) ||
4740                                 kthread_should_stop());
4741                 if (ret < 0)
4742                         goto out;
4743
4744 get_cmd:
4745                 __transport_execute_tasks(dev);
4746
4747                 cmd = transport_get_cmd_from_queue(&dev->dev_queue_obj);
4748                 if (!cmd)
4749                         continue;
4750
4751                 switch (cmd->t_state) {
4752                 case TRANSPORT_NEW_CMD:
4753                         BUG();
4754                         break;
4755                 case TRANSPORT_NEW_CMD_MAP:
4756                         if (!cmd->se_tfo->new_cmd_map) {
4757                                 pr_err("cmd->se_tfo->new_cmd_map is"
4758                                         " NULL for TRANSPORT_NEW_CMD_MAP\n");
4759                                 BUG();
4760                         }
4761                         ret = cmd->se_tfo->new_cmd_map(cmd);
4762                         if (ret < 0) {
4763                                 cmd->transport_error_status = ret;
4764                                 transport_generic_request_failure(cmd,
4765                                                 0, (cmd->data_direction !=
4766                                                     DMA_TO_DEVICE));
4767                                 break;
4768                         }
4769                         ret = transport_generic_new_cmd(cmd);
4770                         if (ret == -EAGAIN)
4771                                 break;
4772                         else if (ret < 0) {
4773                                 cmd->transport_error_status = ret;
4774                                 transport_generic_request_failure(cmd,
4775                                         0, (cmd->data_direction !=
4776                                          DMA_TO_DEVICE));
4777                         }
4778                         break;
4779                 case TRANSPORT_PROCESS_WRITE:
4780                         transport_generic_process_write(cmd);
4781                         break;
4782                 case TRANSPORT_FREE_CMD_INTR:
4783                         transport_generic_free_cmd(cmd, 0);
4784                         break;
4785                 case TRANSPORT_PROCESS_TMR:
4786                         transport_generic_do_tmr(cmd);
4787                         break;
4788                 case TRANSPORT_COMPLETE_QF_WP:
4789                         transport_write_pending_qf(cmd);
4790                         break;
4791                 case TRANSPORT_COMPLETE_QF_OK:
4792                         transport_complete_qf(cmd);
4793                         break;
4794                 default:
4795                         pr_err("Unknown t_state: %d  for ITT: 0x%08x "
4796                                 "i_state: %d on SE LUN: %u\n",
4797                                 cmd->t_state,
4798                                 cmd->se_tfo->get_task_tag(cmd),
4799                                 cmd->se_tfo->get_cmd_state(cmd),
4800                                 cmd->se_lun->unpacked_lun);
4801                         BUG();
4802                 }
4803
4804                 goto get_cmd;
4805         }
4806
4807 out:
4808         WARN_ON(!list_empty(&dev->state_task_list));
4809         WARN_ON(!list_empty(&dev->dev_queue_obj.qobj_list));
4810         dev->process_thread = NULL;
4811         return 0;
4812 }