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