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