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