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