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