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