GNU Linux-libre 4.19.245-gnu1
[releases.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  * (c) Copyright 2002-2013 Datera, Inc.
7  *
8  * Nicholas A. Bellinger <nab@kernel.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23  *
24  ******************************************************************************/
25
26 #include <linux/net.h>
27 #include <linux/delay.h>
28 #include <linux/string.h>
29 #include <linux/timer.h>
30 #include <linux/slab.h>
31 #include <linux/spinlock.h>
32 #include <linux/kthread.h>
33 #include <linux/in.h>
34 #include <linux/cdrom.h>
35 #include <linux/module.h>
36 #include <linux/ratelimit.h>
37 #include <linux/vmalloc.h>
38 #include <asm/unaligned.h>
39 #include <net/sock.h>
40 #include <net/tcp.h>
41 #include <scsi/scsi_proto.h>
42 #include <scsi/scsi_common.h>
43
44 #include <target/target_core_base.h>
45 #include <target/target_core_backend.h>
46 #include <target/target_core_fabric.h>
47
48 #include "target_core_internal.h"
49 #include "target_core_alua.h"
50 #include "target_core_pr.h"
51 #include "target_core_ua.h"
52
53 #define CREATE_TRACE_POINTS
54 #include <trace/events/target.h>
55
56 static struct workqueue_struct *target_completion_wq;
57 static struct kmem_cache *se_sess_cache;
58 struct kmem_cache *se_ua_cache;
59 struct kmem_cache *t10_pr_reg_cache;
60 struct kmem_cache *t10_alua_lu_gp_cache;
61 struct kmem_cache *t10_alua_lu_gp_mem_cache;
62 struct kmem_cache *t10_alua_tg_pt_gp_cache;
63 struct kmem_cache *t10_alua_lba_map_cache;
64 struct kmem_cache *t10_alua_lba_map_mem_cache;
65
66 static void transport_complete_task_attr(struct se_cmd *cmd);
67 static void translate_sense_reason(struct se_cmd *cmd, sense_reason_t reason);
68 static void transport_handle_queue_full(struct se_cmd *cmd,
69                 struct se_device *dev, int err, bool write_pending);
70 static void target_complete_ok_work(struct work_struct *work);
71
72 int init_se_kmem_caches(void)
73 {
74         se_sess_cache = kmem_cache_create("se_sess_cache",
75                         sizeof(struct se_session), __alignof__(struct se_session),
76                         0, NULL);
77         if (!se_sess_cache) {
78                 pr_err("kmem_cache_create() for struct se_session"
79                                 " failed\n");
80                 goto out;
81         }
82         se_ua_cache = kmem_cache_create("se_ua_cache",
83                         sizeof(struct se_ua), __alignof__(struct se_ua),
84                         0, NULL);
85         if (!se_ua_cache) {
86                 pr_err("kmem_cache_create() for struct se_ua failed\n");
87                 goto out_free_sess_cache;
88         }
89         t10_pr_reg_cache = kmem_cache_create("t10_pr_reg_cache",
90                         sizeof(struct t10_pr_registration),
91                         __alignof__(struct t10_pr_registration), 0, NULL);
92         if (!t10_pr_reg_cache) {
93                 pr_err("kmem_cache_create() for struct t10_pr_registration"
94                                 " failed\n");
95                 goto out_free_ua_cache;
96         }
97         t10_alua_lu_gp_cache = kmem_cache_create("t10_alua_lu_gp_cache",
98                         sizeof(struct t10_alua_lu_gp), __alignof__(struct t10_alua_lu_gp),
99                         0, NULL);
100         if (!t10_alua_lu_gp_cache) {
101                 pr_err("kmem_cache_create() for t10_alua_lu_gp_cache"
102                                 " failed\n");
103                 goto out_free_pr_reg_cache;
104         }
105         t10_alua_lu_gp_mem_cache = kmem_cache_create("t10_alua_lu_gp_mem_cache",
106                         sizeof(struct t10_alua_lu_gp_member),
107                         __alignof__(struct t10_alua_lu_gp_member), 0, NULL);
108         if (!t10_alua_lu_gp_mem_cache) {
109                 pr_err("kmem_cache_create() for t10_alua_lu_gp_mem_"
110                                 "cache failed\n");
111                 goto out_free_lu_gp_cache;
112         }
113         t10_alua_tg_pt_gp_cache = kmem_cache_create("t10_alua_tg_pt_gp_cache",
114                         sizeof(struct t10_alua_tg_pt_gp),
115                         __alignof__(struct t10_alua_tg_pt_gp), 0, NULL);
116         if (!t10_alua_tg_pt_gp_cache) {
117                 pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
118                                 "cache failed\n");
119                 goto out_free_lu_gp_mem_cache;
120         }
121         t10_alua_lba_map_cache = kmem_cache_create(
122                         "t10_alua_lba_map_cache",
123                         sizeof(struct t10_alua_lba_map),
124                         __alignof__(struct t10_alua_lba_map), 0, NULL);
125         if (!t10_alua_lba_map_cache) {
126                 pr_err("kmem_cache_create() for t10_alua_lba_map_"
127                                 "cache failed\n");
128                 goto out_free_tg_pt_gp_cache;
129         }
130         t10_alua_lba_map_mem_cache = kmem_cache_create(
131                         "t10_alua_lba_map_mem_cache",
132                         sizeof(struct t10_alua_lba_map_member),
133                         __alignof__(struct t10_alua_lba_map_member), 0, NULL);
134         if (!t10_alua_lba_map_mem_cache) {
135                 pr_err("kmem_cache_create() for t10_alua_lba_map_mem_"
136                                 "cache failed\n");
137                 goto out_free_lba_map_cache;
138         }
139
140         target_completion_wq = alloc_workqueue("target_completion",
141                                                WQ_MEM_RECLAIM, 0);
142         if (!target_completion_wq)
143                 goto out_free_lba_map_mem_cache;
144
145         return 0;
146
147 out_free_lba_map_mem_cache:
148         kmem_cache_destroy(t10_alua_lba_map_mem_cache);
149 out_free_lba_map_cache:
150         kmem_cache_destroy(t10_alua_lba_map_cache);
151 out_free_tg_pt_gp_cache:
152         kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
153 out_free_lu_gp_mem_cache:
154         kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
155 out_free_lu_gp_cache:
156         kmem_cache_destroy(t10_alua_lu_gp_cache);
157 out_free_pr_reg_cache:
158         kmem_cache_destroy(t10_pr_reg_cache);
159 out_free_ua_cache:
160         kmem_cache_destroy(se_ua_cache);
161 out_free_sess_cache:
162         kmem_cache_destroy(se_sess_cache);
163 out:
164         return -ENOMEM;
165 }
166
167 void release_se_kmem_caches(void)
168 {
169         destroy_workqueue(target_completion_wq);
170         kmem_cache_destroy(se_sess_cache);
171         kmem_cache_destroy(se_ua_cache);
172         kmem_cache_destroy(t10_pr_reg_cache);
173         kmem_cache_destroy(t10_alua_lu_gp_cache);
174         kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
175         kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
176         kmem_cache_destroy(t10_alua_lba_map_cache);
177         kmem_cache_destroy(t10_alua_lba_map_mem_cache);
178 }
179
180 /* This code ensures unique mib indexes are handed out. */
181 static DEFINE_SPINLOCK(scsi_mib_index_lock);
182 static u32 scsi_mib_index[SCSI_INDEX_TYPE_MAX];
183
184 /*
185  * Allocate a new row index for the entry type specified
186  */
187 u32 scsi_get_new_index(scsi_index_t type)
188 {
189         u32 new_index;
190
191         BUG_ON((type < 0) || (type >= SCSI_INDEX_TYPE_MAX));
192
193         spin_lock(&scsi_mib_index_lock);
194         new_index = ++scsi_mib_index[type];
195         spin_unlock(&scsi_mib_index_lock);
196
197         return new_index;
198 }
199
200 void transport_subsystem_check_init(void)
201 {
202         int ret;
203         static int sub_api_initialized;
204
205         if (sub_api_initialized)
206                 return;
207
208         ret = request_module("target_core_iblock");
209         if (ret != 0)
210                 pr_err("Unable to load target_core_iblock\n");
211
212         ret = request_module("target_core_file");
213         if (ret != 0)
214                 pr_err("Unable to load target_core_file\n");
215
216         ret = request_module("target_core_pscsi");
217         if (ret != 0)
218                 pr_err("Unable to load target_core_pscsi\n");
219
220         ret = request_module("target_core_user");
221         if (ret != 0)
222                 pr_err("Unable to load target_core_user\n");
223
224         sub_api_initialized = 1;
225 }
226
227 static void target_release_sess_cmd_refcnt(struct percpu_ref *ref)
228 {
229         struct se_session *sess = container_of(ref, typeof(*sess), cmd_count);
230
231         wake_up(&sess->cmd_list_wq);
232 }
233
234 /**
235  * transport_init_session - initialize a session object
236  * @se_sess: Session object pointer.
237  *
238  * The caller must have zero-initialized @se_sess before calling this function.
239  */
240 int transport_init_session(struct se_session *se_sess)
241 {
242         INIT_LIST_HEAD(&se_sess->sess_list);
243         INIT_LIST_HEAD(&se_sess->sess_acl_list);
244         INIT_LIST_HEAD(&se_sess->sess_cmd_list);
245         spin_lock_init(&se_sess->sess_cmd_lock);
246         init_waitqueue_head(&se_sess->cmd_list_wq);
247         return percpu_ref_init(&se_sess->cmd_count,
248                                target_release_sess_cmd_refcnt, 0, GFP_KERNEL);
249 }
250 EXPORT_SYMBOL(transport_init_session);
251
252 /**
253  * transport_alloc_session - allocate a session object and initialize it
254  * @sup_prot_ops: bitmask that defines which T10-PI modes are supported.
255  */
256 struct se_session *transport_alloc_session(enum target_prot_op sup_prot_ops)
257 {
258         struct se_session *se_sess;
259         int ret;
260
261         se_sess = kmem_cache_zalloc(se_sess_cache, GFP_KERNEL);
262         if (!se_sess) {
263                 pr_err("Unable to allocate struct se_session from"
264                                 " se_sess_cache\n");
265                 return ERR_PTR(-ENOMEM);
266         }
267         ret = transport_init_session(se_sess);
268         if (ret < 0) {
269                 kmem_cache_free(se_sess_cache, se_sess);
270                 return ERR_PTR(ret);
271         }
272         se_sess->sup_prot_ops = sup_prot_ops;
273
274         return se_sess;
275 }
276 EXPORT_SYMBOL(transport_alloc_session);
277
278 /**
279  * transport_alloc_session_tags - allocate target driver private data
280  * @se_sess:  Session pointer.
281  * @tag_num:  Maximum number of in-flight commands between initiator and target.
282  * @tag_size: Size in bytes of the private data a target driver associates with
283  *            each command.
284  */
285 int transport_alloc_session_tags(struct se_session *se_sess,
286                                  unsigned int tag_num, unsigned int tag_size)
287 {
288         int rc;
289
290         se_sess->sess_cmd_map = kcalloc(tag_size, tag_num,
291                                         GFP_KERNEL | __GFP_NOWARN | __GFP_RETRY_MAYFAIL);
292         if (!se_sess->sess_cmd_map) {
293                 se_sess->sess_cmd_map = vzalloc(array_size(tag_size, tag_num));
294                 if (!se_sess->sess_cmd_map) {
295                         pr_err("Unable to allocate se_sess->sess_cmd_map\n");
296                         return -ENOMEM;
297                 }
298         }
299
300         rc = sbitmap_queue_init_node(&se_sess->sess_tag_pool, tag_num, -1,
301                         false, GFP_KERNEL, NUMA_NO_NODE);
302         if (rc < 0) {
303                 pr_err("Unable to init se_sess->sess_tag_pool,"
304                         " tag_num: %u\n", tag_num);
305                 kvfree(se_sess->sess_cmd_map);
306                 se_sess->sess_cmd_map = NULL;
307                 return -ENOMEM;
308         }
309
310         return 0;
311 }
312 EXPORT_SYMBOL(transport_alloc_session_tags);
313
314 /**
315  * transport_init_session_tags - allocate a session and target driver private data
316  * @tag_num:  Maximum number of in-flight commands between initiator and target.
317  * @tag_size: Size in bytes of the private data a target driver associates with
318  *            each command.
319  * @sup_prot_ops: bitmask that defines which T10-PI modes are supported.
320  */
321 static struct se_session *
322 transport_init_session_tags(unsigned int tag_num, unsigned int tag_size,
323                             enum target_prot_op sup_prot_ops)
324 {
325         struct se_session *se_sess;
326         int rc;
327
328         if (tag_num != 0 && !tag_size) {
329                 pr_err("init_session_tags called with percpu-ida tag_num:"
330                        " %u, but zero tag_size\n", tag_num);
331                 return ERR_PTR(-EINVAL);
332         }
333         if (!tag_num && tag_size) {
334                 pr_err("init_session_tags called with percpu-ida tag_size:"
335                        " %u, but zero tag_num\n", tag_size);
336                 return ERR_PTR(-EINVAL);
337         }
338
339         se_sess = transport_alloc_session(sup_prot_ops);
340         if (IS_ERR(se_sess))
341                 return se_sess;
342
343         rc = transport_alloc_session_tags(se_sess, tag_num, tag_size);
344         if (rc < 0) {
345                 transport_free_session(se_sess);
346                 return ERR_PTR(-ENOMEM);
347         }
348
349         return se_sess;
350 }
351
352 /*
353  * Called with spin_lock_irqsave(&struct se_portal_group->session_lock called.
354  */
355 void __transport_register_session(
356         struct se_portal_group *se_tpg,
357         struct se_node_acl *se_nacl,
358         struct se_session *se_sess,
359         void *fabric_sess_ptr)
360 {
361         const struct target_core_fabric_ops *tfo = se_tpg->se_tpg_tfo;
362         unsigned char buf[PR_REG_ISID_LEN];
363         unsigned long flags;
364
365         se_sess->se_tpg = se_tpg;
366         se_sess->fabric_sess_ptr = fabric_sess_ptr;
367         /*
368          * Used by struct se_node_acl's under ConfigFS to locate active se_session-t
369          *
370          * Only set for struct se_session's that will actually be moving I/O.
371          * eg: *NOT* discovery sessions.
372          */
373         if (se_nacl) {
374                 /*
375                  *
376                  * Determine if fabric allows for T10-PI feature bits exposed to
377                  * initiators for device backends with !dev->dev_attrib.pi_prot_type.
378                  *
379                  * If so, then always save prot_type on a per se_node_acl node
380                  * basis and re-instate the previous sess_prot_type to avoid
381                  * disabling PI from below any previously initiator side
382                  * registered LUNs.
383                  */
384                 if (se_nacl->saved_prot_type)
385                         se_sess->sess_prot_type = se_nacl->saved_prot_type;
386                 else if (tfo->tpg_check_prot_fabric_only)
387                         se_sess->sess_prot_type = se_nacl->saved_prot_type =
388                                         tfo->tpg_check_prot_fabric_only(se_tpg);
389                 /*
390                  * If the fabric module supports an ISID based TransportID,
391                  * save this value in binary from the fabric I_T Nexus now.
392                  */
393                 if (se_tpg->se_tpg_tfo->sess_get_initiator_sid != NULL) {
394                         memset(&buf[0], 0, PR_REG_ISID_LEN);
395                         se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess,
396                                         &buf[0], PR_REG_ISID_LEN);
397                         se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]);
398                 }
399
400                 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
401                 /*
402                  * The se_nacl->nacl_sess pointer will be set to the
403                  * last active I_T Nexus for each struct se_node_acl.
404                  */
405                 se_nacl->nacl_sess = se_sess;
406
407                 list_add_tail(&se_sess->sess_acl_list,
408                               &se_nacl->acl_sess_list);
409                 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
410         }
411         list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
412
413         pr_debug("TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
414                 se_tpg->se_tpg_tfo->get_fabric_name(), se_sess->fabric_sess_ptr);
415 }
416 EXPORT_SYMBOL(__transport_register_session);
417
418 void transport_register_session(
419         struct se_portal_group *se_tpg,
420         struct se_node_acl *se_nacl,
421         struct se_session *se_sess,
422         void *fabric_sess_ptr)
423 {
424         unsigned long flags;
425
426         spin_lock_irqsave(&se_tpg->session_lock, flags);
427         __transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
428         spin_unlock_irqrestore(&se_tpg->session_lock, flags);
429 }
430 EXPORT_SYMBOL(transport_register_session);
431
432 struct se_session *
433 target_setup_session(struct se_portal_group *tpg,
434                      unsigned int tag_num, unsigned int tag_size,
435                      enum target_prot_op prot_op,
436                      const char *initiatorname, void *private,
437                      int (*callback)(struct se_portal_group *,
438                                      struct se_session *, void *))
439 {
440         struct se_session *sess;
441
442         /*
443          * If the fabric driver is using percpu-ida based pre allocation
444          * of I/O descriptor tags, go ahead and perform that setup now..
445          */
446         if (tag_num != 0)
447                 sess = transport_init_session_tags(tag_num, tag_size, prot_op);
448         else
449                 sess = transport_alloc_session(prot_op);
450
451         if (IS_ERR(sess))
452                 return sess;
453
454         sess->se_node_acl = core_tpg_check_initiator_node_acl(tpg,
455                                         (unsigned char *)initiatorname);
456         if (!sess->se_node_acl) {
457                 transport_free_session(sess);
458                 return ERR_PTR(-EACCES);
459         }
460         /*
461          * Go ahead and perform any remaining fabric setup that is
462          * required before transport_register_session().
463          */
464         if (callback != NULL) {
465                 int rc = callback(tpg, sess, private);
466                 if (rc) {
467                         transport_free_session(sess);
468                         return ERR_PTR(rc);
469                 }
470         }
471
472         transport_register_session(tpg, sess->se_node_acl, sess, private);
473         return sess;
474 }
475 EXPORT_SYMBOL(target_setup_session);
476
477 ssize_t target_show_dynamic_sessions(struct se_portal_group *se_tpg, char *page)
478 {
479         struct se_session *se_sess;
480         ssize_t len = 0;
481
482         spin_lock_bh(&se_tpg->session_lock);
483         list_for_each_entry(se_sess, &se_tpg->tpg_sess_list, sess_list) {
484                 if (!se_sess->se_node_acl)
485                         continue;
486                 if (!se_sess->se_node_acl->dynamic_node_acl)
487                         continue;
488                 if (strlen(se_sess->se_node_acl->initiatorname) + 1 + len > PAGE_SIZE)
489                         break;
490
491                 len += snprintf(page + len, PAGE_SIZE - len, "%s\n",
492                                 se_sess->se_node_acl->initiatorname);
493                 len += 1; /* Include NULL terminator */
494         }
495         spin_unlock_bh(&se_tpg->session_lock);
496
497         return len;
498 }
499 EXPORT_SYMBOL(target_show_dynamic_sessions);
500
501 static void target_complete_nacl(struct kref *kref)
502 {
503         struct se_node_acl *nacl = container_of(kref,
504                                 struct se_node_acl, acl_kref);
505         struct se_portal_group *se_tpg = nacl->se_tpg;
506
507         if (!nacl->dynamic_stop) {
508                 complete(&nacl->acl_free_comp);
509                 return;
510         }
511
512         mutex_lock(&se_tpg->acl_node_mutex);
513         list_del_init(&nacl->acl_list);
514         mutex_unlock(&se_tpg->acl_node_mutex);
515
516         core_tpg_wait_for_nacl_pr_ref(nacl);
517         core_free_device_list_for_node(nacl, se_tpg);
518         kfree(nacl);
519 }
520
521 void target_put_nacl(struct se_node_acl *nacl)
522 {
523         kref_put(&nacl->acl_kref, target_complete_nacl);
524 }
525 EXPORT_SYMBOL(target_put_nacl);
526
527 void transport_deregister_session_configfs(struct se_session *se_sess)
528 {
529         struct se_node_acl *se_nacl;
530         unsigned long flags;
531         /*
532          * Used by struct se_node_acl's under ConfigFS to locate active struct se_session
533          */
534         se_nacl = se_sess->se_node_acl;
535         if (se_nacl) {
536                 spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
537                 if (!list_empty(&se_sess->sess_acl_list))
538                         list_del_init(&se_sess->sess_acl_list);
539                 /*
540                  * If the session list is empty, then clear the pointer.
541                  * Otherwise, set the struct se_session pointer from the tail
542                  * element of the per struct se_node_acl active session list.
543                  */
544                 if (list_empty(&se_nacl->acl_sess_list))
545                         se_nacl->nacl_sess = NULL;
546                 else {
547                         se_nacl->nacl_sess = container_of(
548                                         se_nacl->acl_sess_list.prev,
549                                         struct se_session, sess_acl_list);
550                 }
551                 spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
552         }
553 }
554 EXPORT_SYMBOL(transport_deregister_session_configfs);
555
556 void transport_free_session(struct se_session *se_sess)
557 {
558         struct se_node_acl *se_nacl = se_sess->se_node_acl;
559
560         /*
561          * Drop the se_node_acl->nacl_kref obtained from within
562          * core_tpg_get_initiator_node_acl().
563          */
564         if (se_nacl) {
565                 struct se_portal_group *se_tpg = se_nacl->se_tpg;
566                 const struct target_core_fabric_ops *se_tfo = se_tpg->se_tpg_tfo;
567                 unsigned long flags;
568
569                 se_sess->se_node_acl = NULL;
570
571                 /*
572                  * Also determine if we need to drop the extra ->cmd_kref if
573                  * it had been previously dynamically generated, and
574                  * the endpoint is not caching dynamic ACLs.
575                  */
576                 mutex_lock(&se_tpg->acl_node_mutex);
577                 if (se_nacl->dynamic_node_acl &&
578                     !se_tfo->tpg_check_demo_mode_cache(se_tpg)) {
579                         spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
580                         if (list_empty(&se_nacl->acl_sess_list))
581                                 se_nacl->dynamic_stop = true;
582                         spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
583
584                         if (se_nacl->dynamic_stop)
585                                 list_del_init(&se_nacl->acl_list);
586                 }
587                 mutex_unlock(&se_tpg->acl_node_mutex);
588
589                 if (se_nacl->dynamic_stop)
590                         target_put_nacl(se_nacl);
591
592                 target_put_nacl(se_nacl);
593         }
594         if (se_sess->sess_cmd_map) {
595                 sbitmap_queue_free(&se_sess->sess_tag_pool);
596                 kvfree(se_sess->sess_cmd_map);
597         }
598         percpu_ref_exit(&se_sess->cmd_count);
599         kmem_cache_free(se_sess_cache, se_sess);
600 }
601 EXPORT_SYMBOL(transport_free_session);
602
603 void transport_deregister_session(struct se_session *se_sess)
604 {
605         struct se_portal_group *se_tpg = se_sess->se_tpg;
606         unsigned long flags;
607
608         if (!se_tpg) {
609                 transport_free_session(se_sess);
610                 return;
611         }
612
613         spin_lock_irqsave(&se_tpg->session_lock, flags);
614         list_del(&se_sess->sess_list);
615         se_sess->se_tpg = NULL;
616         se_sess->fabric_sess_ptr = NULL;
617         spin_unlock_irqrestore(&se_tpg->session_lock, flags);
618
619         pr_debug("TARGET_CORE[%s]: Deregistered fabric_sess\n",
620                 se_tpg->se_tpg_tfo->get_fabric_name());
621         /*
622          * If last kref is dropping now for an explicit NodeACL, awake sleeping
623          * ->acl_free_comp caller to wakeup configfs se_node_acl->acl_group
624          * removal context from within transport_free_session() code.
625          *
626          * For dynamic ACL, target_put_nacl() uses target_complete_nacl()
627          * to release all remaining generate_node_acl=1 created ACL resources.
628          */
629
630         transport_free_session(se_sess);
631 }
632 EXPORT_SYMBOL(transport_deregister_session);
633
634 void target_remove_session(struct se_session *se_sess)
635 {
636         transport_deregister_session_configfs(se_sess);
637         transport_deregister_session(se_sess);
638 }
639 EXPORT_SYMBOL(target_remove_session);
640
641 static void target_remove_from_state_list(struct se_cmd *cmd)
642 {
643         struct se_device *dev = cmd->se_dev;
644         unsigned long flags;
645
646         if (!dev)
647                 return;
648
649         spin_lock_irqsave(&dev->execute_task_lock, flags);
650         if (cmd->state_active) {
651                 list_del(&cmd->state_list);
652                 cmd->state_active = false;
653         }
654         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
655 }
656
657 /*
658  * This function is called by the target core after the target core has
659  * finished processing a SCSI command or SCSI TMF. Both the regular command
660  * processing code and the code for aborting commands can call this
661  * function. CMD_T_STOP is set if and only if another thread is waiting
662  * inside transport_wait_for_tasks() for t_transport_stop_comp.
663  */
664 static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
665 {
666         unsigned long flags;
667
668         target_remove_from_state_list(cmd);
669
670         /*
671          * Clear struct se_cmd->se_lun before the handoff to FE.
672          */
673         cmd->se_lun = NULL;
674
675         spin_lock_irqsave(&cmd->t_state_lock, flags);
676         /*
677          * Determine if frontend context caller is requesting the stopping of
678          * this command for frontend exceptions.
679          */
680         if (cmd->transport_state & CMD_T_STOP) {
681                 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
682                         __func__, __LINE__, cmd->tag);
683
684                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
685
686                 complete_all(&cmd->t_transport_stop_comp);
687                 return 1;
688         }
689         cmd->transport_state &= ~CMD_T_ACTIVE;
690         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
691
692         /*
693          * Some fabric modules like tcm_loop can release their internally
694          * allocated I/O reference and struct se_cmd now.
695          *
696          * Fabric modules are expected to return '1' here if the se_cmd being
697          * passed is released at this point, or zero if not being released.
698          */
699         return cmd->se_tfo->check_stop_free(cmd);
700 }
701
702 static void transport_lun_remove_cmd(struct se_cmd *cmd)
703 {
704         struct se_lun *lun = cmd->se_lun;
705
706         if (!lun)
707                 return;
708
709         if (cmpxchg(&cmd->lun_ref_active, true, false))
710                 percpu_ref_put(&lun->lun_ref);
711 }
712
713 int transport_cmd_finish_abort(struct se_cmd *cmd)
714 {
715         bool send_tas = cmd->transport_state & CMD_T_TAS;
716         bool ack_kref = (cmd->se_cmd_flags & SCF_ACK_KREF);
717         int ret = 0;
718
719         if (send_tas)
720                 transport_send_task_abort(cmd);
721
722         if (cmd->se_cmd_flags & SCF_SE_LUN_CMD)
723                 transport_lun_remove_cmd(cmd);
724         /*
725          * Allow the fabric driver to unmap any resources before
726          * releasing the descriptor via TFO->release_cmd()
727          */
728         if (!send_tas)
729                 cmd->se_tfo->aborted_task(cmd);
730
731         if (transport_cmd_check_stop_to_fabric(cmd))
732                 return 1;
733         if (!send_tas && ack_kref)
734                 ret = target_put_sess_cmd(cmd);
735
736         return ret;
737 }
738
739 static void target_complete_failure_work(struct work_struct *work)
740 {
741         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
742
743         transport_generic_request_failure(cmd,
744                         TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE);
745 }
746
747 /*
748  * Used when asking transport to copy Sense Data from the underlying
749  * Linux/SCSI struct scsi_cmnd
750  */
751 static unsigned char *transport_get_sense_buffer(struct se_cmd *cmd)
752 {
753         struct se_device *dev = cmd->se_dev;
754
755         WARN_ON(!cmd->se_lun);
756
757         if (!dev)
758                 return NULL;
759
760         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION)
761                 return NULL;
762
763         cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER;
764
765         pr_debug("HBA_[%u]_PLUG[%s]: Requesting sense for SAM STATUS: 0x%02x\n",
766                 dev->se_hba->hba_id, dev->transport->name, cmd->scsi_status);
767         return cmd->sense_buffer;
768 }
769
770 void transport_copy_sense_to_cmd(struct se_cmd *cmd, unsigned char *sense)
771 {
772         unsigned char *cmd_sense_buf;
773         unsigned long flags;
774
775         spin_lock_irqsave(&cmd->t_state_lock, flags);
776         cmd_sense_buf = transport_get_sense_buffer(cmd);
777         if (!cmd_sense_buf) {
778                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
779                 return;
780         }
781
782         cmd->se_cmd_flags |= SCF_TRANSPORT_TASK_SENSE;
783         memcpy(cmd_sense_buf, sense, cmd->scsi_sense_length);
784         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
785 }
786 EXPORT_SYMBOL(transport_copy_sense_to_cmd);
787
788 void target_complete_cmd(struct se_cmd *cmd, u8 scsi_status)
789 {
790         struct se_device *dev = cmd->se_dev;
791         int success;
792         unsigned long flags;
793
794         cmd->scsi_status = scsi_status;
795
796         spin_lock_irqsave(&cmd->t_state_lock, flags);
797         switch (cmd->scsi_status) {
798         case SAM_STAT_CHECK_CONDITION:
799                 if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
800                         success = 1;
801                 else
802                         success = 0;
803                 break;
804         default:
805                 success = 1;
806                 break;
807         }
808
809         /*
810          * Check for case where an explicit ABORT_TASK has been received
811          * and transport_wait_for_tasks() will be waiting for completion..
812          */
813         if (cmd->transport_state & CMD_T_ABORTED ||
814             cmd->transport_state & CMD_T_STOP) {
815                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
816                 /*
817                  * If COMPARE_AND_WRITE was stopped by __transport_wait_for_tasks(),
818                  * release se_device->caw_sem obtained by sbc_compare_and_write()
819                  * since target_complete_ok_work() or target_complete_failure_work()
820                  * won't be called to invoke the normal CAW completion callbacks.
821                  */
822                 if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) {
823                         up(&dev->caw_sem);
824                 }
825                 complete_all(&cmd->t_transport_stop_comp);
826                 return;
827         } else if (!success) {
828                 INIT_WORK(&cmd->work, target_complete_failure_work);
829         } else {
830                 INIT_WORK(&cmd->work, target_complete_ok_work);
831         }
832
833         cmd->t_state = TRANSPORT_COMPLETE;
834         cmd->transport_state |= (CMD_T_COMPLETE | CMD_T_ACTIVE);
835         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
836
837         if (cmd->se_cmd_flags & SCF_USE_CPUID)
838                 queue_work_on(cmd->cpuid, target_completion_wq, &cmd->work);
839         else
840                 queue_work(target_completion_wq, &cmd->work);
841 }
842 EXPORT_SYMBOL(target_complete_cmd);
843
844 void target_set_cmd_data_length(struct se_cmd *cmd, int length)
845 {
846         if (length < cmd->data_length) {
847                 if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
848                         cmd->residual_count += cmd->data_length - length;
849                 } else {
850                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
851                         cmd->residual_count = cmd->data_length - length;
852                 }
853
854                 cmd->data_length = length;
855         }
856 }
857 EXPORT_SYMBOL(target_set_cmd_data_length);
858
859 void target_complete_cmd_with_length(struct se_cmd *cmd, u8 scsi_status, int length)
860 {
861         if (scsi_status == SAM_STAT_GOOD ||
862             cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) {
863                 target_set_cmd_data_length(cmd, length);
864         }
865
866         target_complete_cmd(cmd, scsi_status);
867 }
868 EXPORT_SYMBOL(target_complete_cmd_with_length);
869
870 static void target_add_to_state_list(struct se_cmd *cmd)
871 {
872         struct se_device *dev = cmd->se_dev;
873         unsigned long flags;
874
875         spin_lock_irqsave(&dev->execute_task_lock, flags);
876         if (!cmd->state_active) {
877                 list_add_tail(&cmd->state_list, &dev->state_list);
878                 cmd->state_active = true;
879         }
880         spin_unlock_irqrestore(&dev->execute_task_lock, flags);
881 }
882
883 /*
884  * Handle QUEUE_FULL / -EAGAIN and -ENOMEM status
885  */
886 static void transport_write_pending_qf(struct se_cmd *cmd);
887 static void transport_complete_qf(struct se_cmd *cmd);
888
889 void target_qf_do_work(struct work_struct *work)
890 {
891         struct se_device *dev = container_of(work, struct se_device,
892                                         qf_work_queue);
893         LIST_HEAD(qf_cmd_list);
894         struct se_cmd *cmd, *cmd_tmp;
895
896         spin_lock_irq(&dev->qf_cmd_lock);
897         list_splice_init(&dev->qf_cmd_list, &qf_cmd_list);
898         spin_unlock_irq(&dev->qf_cmd_lock);
899
900         list_for_each_entry_safe(cmd, cmd_tmp, &qf_cmd_list, se_qf_node) {
901                 list_del(&cmd->se_qf_node);
902                 atomic_dec_mb(&dev->dev_qf_count);
903
904                 pr_debug("Processing %s cmd: %p QUEUE_FULL in work queue"
905                         " context: %s\n", cmd->se_tfo->get_fabric_name(), cmd,
906                         (cmd->t_state == TRANSPORT_COMPLETE_QF_OK) ? "COMPLETE_OK" :
907                         (cmd->t_state == TRANSPORT_COMPLETE_QF_WP) ? "WRITE_PENDING"
908                         : "UNKNOWN");
909
910                 if (cmd->t_state == TRANSPORT_COMPLETE_QF_WP)
911                         transport_write_pending_qf(cmd);
912                 else if (cmd->t_state == TRANSPORT_COMPLETE_QF_OK ||
913                          cmd->t_state == TRANSPORT_COMPLETE_QF_ERR)
914                         transport_complete_qf(cmd);
915         }
916 }
917
918 unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
919 {
920         switch (cmd->data_direction) {
921         case DMA_NONE:
922                 return "NONE";
923         case DMA_FROM_DEVICE:
924                 return "READ";
925         case DMA_TO_DEVICE:
926                 return "WRITE";
927         case DMA_BIDIRECTIONAL:
928                 return "BIDI";
929         default:
930                 break;
931         }
932
933         return "UNKNOWN";
934 }
935
936 void transport_dump_dev_state(
937         struct se_device *dev,
938         char *b,
939         int *bl)
940 {
941         *bl += sprintf(b + *bl, "Status: ");
942         if (dev->export_count)
943                 *bl += sprintf(b + *bl, "ACTIVATED");
944         else
945                 *bl += sprintf(b + *bl, "DEACTIVATED");
946
947         *bl += sprintf(b + *bl, "  Max Queue Depth: %d", dev->queue_depth);
948         *bl += sprintf(b + *bl, "  SectorSize: %u  HwMaxSectors: %u\n",
949                 dev->dev_attrib.block_size,
950                 dev->dev_attrib.hw_max_sectors);
951         *bl += sprintf(b + *bl, "        ");
952 }
953
954 void transport_dump_vpd_proto_id(
955         struct t10_vpd *vpd,
956         unsigned char *p_buf,
957         int p_buf_len)
958 {
959         unsigned char buf[VPD_TMP_BUF_SIZE];
960         int len;
961
962         memset(buf, 0, VPD_TMP_BUF_SIZE);
963         len = sprintf(buf, "T10 VPD Protocol Identifier: ");
964
965         switch (vpd->protocol_identifier) {
966         case 0x00:
967                 sprintf(buf+len, "Fibre Channel\n");
968                 break;
969         case 0x10:
970                 sprintf(buf+len, "Parallel SCSI\n");
971                 break;
972         case 0x20:
973                 sprintf(buf+len, "SSA\n");
974                 break;
975         case 0x30:
976                 sprintf(buf+len, "IEEE 1394\n");
977                 break;
978         case 0x40:
979                 sprintf(buf+len, "SCSI Remote Direct Memory Access"
980                                 " Protocol\n");
981                 break;
982         case 0x50:
983                 sprintf(buf+len, "Internet SCSI (iSCSI)\n");
984                 break;
985         case 0x60:
986                 sprintf(buf+len, "SAS Serial SCSI Protocol\n");
987                 break;
988         case 0x70:
989                 sprintf(buf+len, "Automation/Drive Interface Transport"
990                                 " Protocol\n");
991                 break;
992         case 0x80:
993                 sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
994                 break;
995         default:
996                 sprintf(buf+len, "Unknown 0x%02x\n",
997                                 vpd->protocol_identifier);
998                 break;
999         }
1000
1001         if (p_buf)
1002                 strncpy(p_buf, buf, p_buf_len);
1003         else
1004                 pr_debug("%s", buf);
1005 }
1006
1007 void
1008 transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
1009 {
1010         /*
1011          * Check if the Protocol Identifier Valid (PIV) bit is set..
1012          *
1013          * from spc3r23.pdf section 7.5.1
1014          */
1015          if (page_83[1] & 0x80) {
1016                 vpd->protocol_identifier = (page_83[0] & 0xf0);
1017                 vpd->protocol_identifier_set = 1;
1018                 transport_dump_vpd_proto_id(vpd, NULL, 0);
1019         }
1020 }
1021 EXPORT_SYMBOL(transport_set_vpd_proto_id);
1022
1023 int transport_dump_vpd_assoc(
1024         struct t10_vpd *vpd,
1025         unsigned char *p_buf,
1026         int p_buf_len)
1027 {
1028         unsigned char buf[VPD_TMP_BUF_SIZE];
1029         int ret = 0;
1030         int len;
1031
1032         memset(buf, 0, VPD_TMP_BUF_SIZE);
1033         len = sprintf(buf, "T10 VPD Identifier Association: ");
1034
1035         switch (vpd->association) {
1036         case 0x00:
1037                 sprintf(buf+len, "addressed logical unit\n");
1038                 break;
1039         case 0x10:
1040                 sprintf(buf+len, "target port\n");
1041                 break;
1042         case 0x20:
1043                 sprintf(buf+len, "SCSI target device\n");
1044                 break;
1045         default:
1046                 sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
1047                 ret = -EINVAL;
1048                 break;
1049         }
1050
1051         if (p_buf)
1052                 strncpy(p_buf, buf, p_buf_len);
1053         else
1054                 pr_debug("%s", buf);
1055
1056         return ret;
1057 }
1058
1059 int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
1060 {
1061         /*
1062          * The VPD identification association..
1063          *
1064          * from spc3r23.pdf Section 7.6.3.1 Table 297
1065          */
1066         vpd->association = (page_83[1] & 0x30);
1067         return transport_dump_vpd_assoc(vpd, NULL, 0);
1068 }
1069 EXPORT_SYMBOL(transport_set_vpd_assoc);
1070
1071 int transport_dump_vpd_ident_type(
1072         struct t10_vpd *vpd,
1073         unsigned char *p_buf,
1074         int p_buf_len)
1075 {
1076         unsigned char buf[VPD_TMP_BUF_SIZE];
1077         int ret = 0;
1078         int len;
1079
1080         memset(buf, 0, VPD_TMP_BUF_SIZE);
1081         len = sprintf(buf, "T10 VPD Identifier Type: ");
1082
1083         switch (vpd->device_identifier_type) {
1084         case 0x00:
1085                 sprintf(buf+len, "Vendor specific\n");
1086                 break;
1087         case 0x01:
1088                 sprintf(buf+len, "T10 Vendor ID based\n");
1089                 break;
1090         case 0x02:
1091                 sprintf(buf+len, "EUI-64 based\n");
1092                 break;
1093         case 0x03:
1094                 sprintf(buf+len, "NAA\n");
1095                 break;
1096         case 0x04:
1097                 sprintf(buf+len, "Relative target port identifier\n");
1098                 break;
1099         case 0x08:
1100                 sprintf(buf+len, "SCSI name string\n");
1101                 break;
1102         default:
1103                 sprintf(buf+len, "Unsupported: 0x%02x\n",
1104                                 vpd->device_identifier_type);
1105                 ret = -EINVAL;
1106                 break;
1107         }
1108
1109         if (p_buf) {
1110                 if (p_buf_len < strlen(buf)+1)
1111                         return -EINVAL;
1112                 strncpy(p_buf, buf, p_buf_len);
1113         } else {
1114                 pr_debug("%s", buf);
1115         }
1116
1117         return ret;
1118 }
1119
1120 int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
1121 {
1122         /*
1123          * The VPD identifier type..
1124          *
1125          * from spc3r23.pdf Section 7.6.3.1 Table 298
1126          */
1127         vpd->device_identifier_type = (page_83[1] & 0x0f);
1128         return transport_dump_vpd_ident_type(vpd, NULL, 0);
1129 }
1130 EXPORT_SYMBOL(transport_set_vpd_ident_type);
1131
1132 int transport_dump_vpd_ident(
1133         struct t10_vpd *vpd,
1134         unsigned char *p_buf,
1135         int p_buf_len)
1136 {
1137         unsigned char buf[VPD_TMP_BUF_SIZE];
1138         int ret = 0;
1139
1140         memset(buf, 0, VPD_TMP_BUF_SIZE);
1141
1142         switch (vpd->device_identifier_code_set) {
1143         case 0x01: /* Binary */
1144                 snprintf(buf, sizeof(buf),
1145                         "T10 VPD Binary Device Identifier: %s\n",
1146                         &vpd->device_identifier[0]);
1147                 break;
1148         case 0x02: /* ASCII */
1149                 snprintf(buf, sizeof(buf),
1150                         "T10 VPD ASCII Device Identifier: %s\n",
1151                         &vpd->device_identifier[0]);
1152                 break;
1153         case 0x03: /* UTF-8 */
1154                 snprintf(buf, sizeof(buf),
1155                         "T10 VPD UTF-8 Device Identifier: %s\n",
1156                         &vpd->device_identifier[0]);
1157                 break;
1158         default:
1159                 sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
1160                         " 0x%02x", vpd->device_identifier_code_set);
1161                 ret = -EINVAL;
1162                 break;
1163         }
1164
1165         if (p_buf)
1166                 strncpy(p_buf, buf, p_buf_len);
1167         else
1168                 pr_debug("%s", buf);
1169
1170         return ret;
1171 }
1172
1173 int
1174 transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
1175 {
1176         static const char hex_str[] = "0123456789abcdef";
1177         int j = 0, i = 4; /* offset to start of the identifier */
1178
1179         /*
1180          * The VPD Code Set (encoding)
1181          *
1182          * from spc3r23.pdf Section 7.6.3.1 Table 296
1183          */
1184         vpd->device_identifier_code_set = (page_83[0] & 0x0f);
1185         switch (vpd->device_identifier_code_set) {
1186         case 0x01: /* Binary */
1187                 vpd->device_identifier[j++] =
1188                                 hex_str[vpd->device_identifier_type];
1189                 while (i < (4 + page_83[3])) {
1190                         vpd->device_identifier[j++] =
1191                                 hex_str[(page_83[i] & 0xf0) >> 4];
1192                         vpd->device_identifier[j++] =
1193                                 hex_str[page_83[i] & 0x0f];
1194                         i++;
1195                 }
1196                 break;
1197         case 0x02: /* ASCII */
1198         case 0x03: /* UTF-8 */
1199                 while (i < (4 + page_83[3]))
1200                         vpd->device_identifier[j++] = page_83[i++];
1201                 break;
1202         default:
1203                 break;
1204         }
1205
1206         return transport_dump_vpd_ident(vpd, NULL, 0);
1207 }
1208 EXPORT_SYMBOL(transport_set_vpd_ident);
1209
1210 static sense_reason_t
1211 target_check_max_data_sg_nents(struct se_cmd *cmd, struct se_device *dev,
1212                                unsigned int size)
1213 {
1214         u32 mtl;
1215
1216         if (!cmd->se_tfo->max_data_sg_nents)
1217                 return TCM_NO_SENSE;
1218         /*
1219          * Check if fabric enforced maximum SGL entries per I/O descriptor
1220          * exceeds se_cmd->data_length.  If true, set SCF_UNDERFLOW_BIT +
1221          * residual_count and reduce original cmd->data_length to maximum
1222          * length based on single PAGE_SIZE entry scatter-lists.
1223          */
1224         mtl = (cmd->se_tfo->max_data_sg_nents * PAGE_SIZE);
1225         if (cmd->data_length > mtl) {
1226                 /*
1227                  * If an existing CDB overflow is present, calculate new residual
1228                  * based on CDB size minus fabric maximum transfer length.
1229                  *
1230                  * If an existing CDB underflow is present, calculate new residual
1231                  * based on original cmd->data_length minus fabric maximum transfer
1232                  * length.
1233                  *
1234                  * Otherwise, set the underflow residual based on cmd->data_length
1235                  * minus fabric maximum transfer length.
1236                  */
1237                 if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1238                         cmd->residual_count = (size - mtl);
1239                 } else if (cmd->se_cmd_flags & SCF_UNDERFLOW_BIT) {
1240                         u32 orig_dl = size + cmd->residual_count;
1241                         cmd->residual_count = (orig_dl - mtl);
1242                 } else {
1243                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1244                         cmd->residual_count = (cmd->data_length - mtl);
1245                 }
1246                 cmd->data_length = mtl;
1247                 /*
1248                  * Reset sbc_check_prot() calculated protection payload
1249                  * length based upon the new smaller MTL.
1250                  */
1251                 if (cmd->prot_length) {
1252                         u32 sectors = (mtl / dev->dev_attrib.block_size);
1253                         cmd->prot_length = dev->prot_length * sectors;
1254                 }
1255         }
1256         return TCM_NO_SENSE;
1257 }
1258
1259 sense_reason_t
1260 target_cmd_size_check(struct se_cmd *cmd, unsigned int size)
1261 {
1262         struct se_device *dev = cmd->se_dev;
1263
1264         if (cmd->unknown_data_length) {
1265                 cmd->data_length = size;
1266         } else if (size != cmd->data_length) {
1267                 pr_warn_ratelimited("TARGET_CORE[%s]: Expected Transfer Length:"
1268                         " %u does not match SCSI CDB Length: %u for SAM Opcode:"
1269                         " 0x%02x\n", cmd->se_tfo->get_fabric_name(),
1270                                 cmd->data_length, size, cmd->t_task_cdb[0]);
1271
1272                 if (cmd->data_direction == DMA_TO_DEVICE) {
1273                         if (cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) {
1274                                 pr_err_ratelimited("Rejecting underflow/overflow"
1275                                                    " for WRITE data CDB\n");
1276                                 return TCM_INVALID_CDB_FIELD;
1277                         }
1278                         /*
1279                          * Some fabric drivers like iscsi-target still expect to
1280                          * always reject overflow writes.  Reject this case until
1281                          * full fabric driver level support for overflow writes
1282                          * is introduced tree-wide.
1283                          */
1284                         if (size > cmd->data_length) {
1285                                 pr_err_ratelimited("Rejecting overflow for"
1286                                                    " WRITE control CDB\n");
1287                                 return TCM_INVALID_CDB_FIELD;
1288                         }
1289                 }
1290                 /*
1291                  * Reject READ_* or WRITE_* with overflow/underflow for
1292                  * type SCF_SCSI_DATA_CDB.
1293                  */
1294                 if (dev->dev_attrib.block_size != 512)  {
1295                         pr_err("Failing OVERFLOW/UNDERFLOW for LBA op"
1296                                 " CDB on non 512-byte sector setup subsystem"
1297                                 " plugin: %s\n", dev->transport->name);
1298                         /* Returns CHECK_CONDITION + INVALID_CDB_FIELD */
1299                         return TCM_INVALID_CDB_FIELD;
1300                 }
1301                 /*
1302                  * For the overflow case keep the existing fabric provided
1303                  * ->data_length.  Otherwise for the underflow case, reset
1304                  * ->data_length to the smaller SCSI expected data transfer
1305                  * length.
1306                  */
1307                 if (size > cmd->data_length) {
1308                         cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
1309                         cmd->residual_count = (size - cmd->data_length);
1310                 } else {
1311                         cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1312                         cmd->residual_count = (cmd->data_length - size);
1313                         cmd->data_length = size;
1314                 }
1315         }
1316
1317         return target_check_max_data_sg_nents(cmd, dev, size);
1318
1319 }
1320
1321 /*
1322  * Used by fabric modules containing a local struct se_cmd within their
1323  * fabric dependent per I/O descriptor.
1324  *
1325  * Preserves the value of @cmd->tag.
1326  */
1327 void transport_init_se_cmd(
1328         struct se_cmd *cmd,
1329         const struct target_core_fabric_ops *tfo,
1330         struct se_session *se_sess,
1331         u32 data_length,
1332         int data_direction,
1333         int task_attr,
1334         unsigned char *sense_buffer)
1335 {
1336         INIT_LIST_HEAD(&cmd->se_delayed_node);
1337         INIT_LIST_HEAD(&cmd->se_qf_node);
1338         INIT_LIST_HEAD(&cmd->se_cmd_list);
1339         INIT_LIST_HEAD(&cmd->state_list);
1340         init_completion(&cmd->t_transport_stop_comp);
1341         cmd->compl = NULL;
1342         spin_lock_init(&cmd->t_state_lock);
1343         INIT_WORK(&cmd->work, NULL);
1344         kref_init(&cmd->cmd_kref);
1345
1346         cmd->se_tfo = tfo;
1347         cmd->se_sess = se_sess;
1348         cmd->data_length = data_length;
1349         cmd->data_direction = data_direction;
1350         cmd->sam_task_attr = task_attr;
1351         cmd->sense_buffer = sense_buffer;
1352
1353         cmd->state_active = false;
1354 }
1355 EXPORT_SYMBOL(transport_init_se_cmd);
1356
1357 static sense_reason_t
1358 transport_check_alloc_task_attr(struct se_cmd *cmd)
1359 {
1360         struct se_device *dev = cmd->se_dev;
1361
1362         /*
1363          * Check if SAM Task Attribute emulation is enabled for this
1364          * struct se_device storage object
1365          */
1366         if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
1367                 return 0;
1368
1369         if (cmd->sam_task_attr == TCM_ACA_TAG) {
1370                 pr_debug("SAM Task Attribute ACA"
1371                         " emulation is not supported\n");
1372                 return TCM_INVALID_CDB_FIELD;
1373         }
1374
1375         return 0;
1376 }
1377
1378 sense_reason_t
1379 target_setup_cmd_from_cdb(struct se_cmd *cmd, unsigned char *cdb)
1380 {
1381         struct se_device *dev = cmd->se_dev;
1382         sense_reason_t ret;
1383
1384         /*
1385          * Ensure that the received CDB is less than the max (252 + 8) bytes
1386          * for VARIABLE_LENGTH_CMD
1387          */
1388         if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
1389                 pr_err("Received SCSI CDB with command_size: %d that"
1390                         " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1391                         scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
1392                 return TCM_INVALID_CDB_FIELD;
1393         }
1394         /*
1395          * If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
1396          * allocate the additional extended CDB buffer now..  Otherwise
1397          * setup the pointer from __t_task_cdb to t_task_cdb.
1398          */
1399         if (scsi_command_size(cdb) > sizeof(cmd->__t_task_cdb)) {
1400                 cmd->t_task_cdb = kzalloc(scsi_command_size(cdb),
1401                                                 GFP_KERNEL);
1402                 if (!cmd->t_task_cdb) {
1403                         pr_err("Unable to allocate cmd->t_task_cdb"
1404                                 " %u > sizeof(cmd->__t_task_cdb): %lu ops\n",
1405                                 scsi_command_size(cdb),
1406                                 (unsigned long)sizeof(cmd->__t_task_cdb));
1407                         return TCM_OUT_OF_RESOURCES;
1408                 }
1409         } else
1410                 cmd->t_task_cdb = &cmd->__t_task_cdb[0];
1411         /*
1412          * Copy the original CDB into cmd->
1413          */
1414         memcpy(cmd->t_task_cdb, cdb, scsi_command_size(cdb));
1415
1416         trace_target_sequencer_start(cmd);
1417
1418         ret = dev->transport->parse_cdb(cmd);
1419         if (ret == TCM_UNSUPPORTED_SCSI_OPCODE)
1420                 pr_warn_ratelimited("%s/%s: Unsupported SCSI Opcode 0x%02x, sending CHECK_CONDITION.\n",
1421                                     cmd->se_tfo->get_fabric_name(),
1422                                     cmd->se_sess->se_node_acl->initiatorname,
1423                                     cmd->t_task_cdb[0]);
1424         if (ret)
1425                 return ret;
1426
1427         ret = transport_check_alloc_task_attr(cmd);
1428         if (ret)
1429                 return ret;
1430
1431         cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
1432         atomic_long_inc(&cmd->se_lun->lun_stats.cmd_pdus);
1433         return 0;
1434 }
1435 EXPORT_SYMBOL(target_setup_cmd_from_cdb);
1436
1437 /*
1438  * Used by fabric module frontends to queue tasks directly.
1439  * May only be used from process context.
1440  */
1441 int transport_handle_cdb_direct(
1442         struct se_cmd *cmd)
1443 {
1444         sense_reason_t ret;
1445
1446         if (!cmd->se_lun) {
1447                 dump_stack();
1448                 pr_err("cmd->se_lun is NULL\n");
1449                 return -EINVAL;
1450         }
1451         if (in_interrupt()) {
1452                 dump_stack();
1453                 pr_err("transport_generic_handle_cdb cannot be called"
1454                                 " from interrupt context\n");
1455                 return -EINVAL;
1456         }
1457         /*
1458          * Set TRANSPORT_NEW_CMD state and CMD_T_ACTIVE to ensure that
1459          * outstanding descriptors are handled correctly during shutdown via
1460          * transport_wait_for_tasks()
1461          *
1462          * Also, we don't take cmd->t_state_lock here as we only expect
1463          * this to be called for initial descriptor submission.
1464          */
1465         cmd->t_state = TRANSPORT_NEW_CMD;
1466         cmd->transport_state |= CMD_T_ACTIVE;
1467
1468         /*
1469          * transport_generic_new_cmd() is already handling QUEUE_FULL,
1470          * so follow TRANSPORT_NEW_CMD processing thread context usage
1471          * and call transport_generic_request_failure() if necessary..
1472          */
1473         ret = transport_generic_new_cmd(cmd);
1474         if (ret)
1475                 transport_generic_request_failure(cmd, ret);
1476         return 0;
1477 }
1478 EXPORT_SYMBOL(transport_handle_cdb_direct);
1479
1480 sense_reason_t
1481 transport_generic_map_mem_to_cmd(struct se_cmd *cmd, struct scatterlist *sgl,
1482                 u32 sgl_count, struct scatterlist *sgl_bidi, u32 sgl_bidi_count)
1483 {
1484         if (!sgl || !sgl_count)
1485                 return 0;
1486
1487         /*
1488          * Reject SCSI data overflow with map_mem_to_cmd() as incoming
1489          * scatterlists already have been set to follow what the fabric
1490          * passes for the original expected data transfer length.
1491          */
1492         if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
1493                 pr_warn("Rejecting SCSI DATA overflow for fabric using"
1494                         " SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC\n");
1495                 return TCM_INVALID_CDB_FIELD;
1496         }
1497
1498         cmd->t_data_sg = sgl;
1499         cmd->t_data_nents = sgl_count;
1500         cmd->t_bidi_data_sg = sgl_bidi;
1501         cmd->t_bidi_data_nents = sgl_bidi_count;
1502
1503         cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
1504         return 0;
1505 }
1506
1507 /**
1508  * target_submit_cmd_map_sgls - lookup unpacked lun and submit uninitialized
1509  *                       se_cmd + use pre-allocated SGL memory.
1510  *
1511  * @se_cmd: command descriptor to submit
1512  * @se_sess: associated se_sess for endpoint
1513  * @cdb: pointer to SCSI CDB
1514  * @sense: pointer to SCSI sense buffer
1515  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1516  * @data_length: fabric expected data transfer length
1517  * @task_attr: SAM task attribute
1518  * @data_dir: DMA data direction
1519  * @flags: flags for command submission from target_sc_flags_tables
1520  * @sgl: struct scatterlist memory for unidirectional mapping
1521  * @sgl_count: scatterlist count for unidirectional mapping
1522  * @sgl_bidi: struct scatterlist memory for bidirectional READ mapping
1523  * @sgl_bidi_count: scatterlist count for bidirectional READ mapping
1524  * @sgl_prot: struct scatterlist memory protection information
1525  * @sgl_prot_count: scatterlist count for protection information
1526  *
1527  * Task tags are supported if the caller has set @se_cmd->tag.
1528  *
1529  * Returns non zero to signal active I/O shutdown failure.  All other
1530  * setup exceptions will be returned as a SCSI CHECK_CONDITION response,
1531  * but still return zero here.
1532  *
1533  * This may only be called from process context, and also currently
1534  * assumes internal allocation of fabric payload buffer by target-core.
1535  */
1536 int target_submit_cmd_map_sgls(struct se_cmd *se_cmd, struct se_session *se_sess,
1537                 unsigned char *cdb, unsigned char *sense, u64 unpacked_lun,
1538                 u32 data_length, int task_attr, int data_dir, int flags,
1539                 struct scatterlist *sgl, u32 sgl_count,
1540                 struct scatterlist *sgl_bidi, u32 sgl_bidi_count,
1541                 struct scatterlist *sgl_prot, u32 sgl_prot_count)
1542 {
1543         struct se_portal_group *se_tpg;
1544         sense_reason_t rc;
1545         int ret;
1546
1547         se_tpg = se_sess->se_tpg;
1548         BUG_ON(!se_tpg);
1549         BUG_ON(se_cmd->se_tfo || se_cmd->se_sess);
1550         BUG_ON(in_interrupt());
1551         /*
1552          * Initialize se_cmd for target operation.  From this point
1553          * exceptions are handled by sending exception status via
1554          * target_core_fabric_ops->queue_status() callback
1555          */
1556         transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1557                                 data_length, data_dir, task_attr, sense);
1558
1559         if (flags & TARGET_SCF_USE_CPUID)
1560                 se_cmd->se_cmd_flags |= SCF_USE_CPUID;
1561         else
1562                 se_cmd->cpuid = WORK_CPU_UNBOUND;
1563
1564         if (flags & TARGET_SCF_UNKNOWN_SIZE)
1565                 se_cmd->unknown_data_length = 1;
1566         /*
1567          * Obtain struct se_cmd->cmd_kref reference and add new cmd to
1568          * se_sess->sess_cmd_list.  A second kref_get here is necessary
1569          * for fabrics using TARGET_SCF_ACK_KREF that expect a second
1570          * kref_put() to happen during fabric packet acknowledgement.
1571          */
1572         ret = target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF);
1573         if (ret)
1574                 return ret;
1575         /*
1576          * Signal bidirectional data payloads to target-core
1577          */
1578         if (flags & TARGET_SCF_BIDI_OP)
1579                 se_cmd->se_cmd_flags |= SCF_BIDI;
1580         /*
1581          * Locate se_lun pointer and attach it to struct se_cmd
1582          */
1583         rc = transport_lookup_cmd_lun(se_cmd, unpacked_lun);
1584         if (rc) {
1585                 transport_send_check_condition_and_sense(se_cmd, rc, 0);
1586                 target_put_sess_cmd(se_cmd);
1587                 return 0;
1588         }
1589
1590         rc = target_setup_cmd_from_cdb(se_cmd, cdb);
1591         if (rc != 0) {
1592                 transport_generic_request_failure(se_cmd, rc);
1593                 return 0;
1594         }
1595
1596         /*
1597          * Save pointers for SGLs containing protection information,
1598          * if present.
1599          */
1600         if (sgl_prot_count) {
1601                 se_cmd->t_prot_sg = sgl_prot;
1602                 se_cmd->t_prot_nents = sgl_prot_count;
1603                 se_cmd->se_cmd_flags |= SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC;
1604         }
1605
1606         /*
1607          * When a non zero sgl_count has been passed perform SGL passthrough
1608          * mapping for pre-allocated fabric memory instead of having target
1609          * core perform an internal SGL allocation..
1610          */
1611         if (sgl_count != 0) {
1612                 BUG_ON(!sgl);
1613
1614                 /*
1615                  * A work-around for tcm_loop as some userspace code via
1616                  * scsi-generic do not memset their associated read buffers,
1617                  * so go ahead and do that here for type non-data CDBs.  Also
1618                  * note that this is currently guaranteed to be a single SGL
1619                  * for this case by target core in target_setup_cmd_from_cdb()
1620                  * -> transport_generic_cmd_sequencer().
1621                  */
1622                 if (!(se_cmd->se_cmd_flags & SCF_SCSI_DATA_CDB) &&
1623                      se_cmd->data_direction == DMA_FROM_DEVICE) {
1624                         unsigned char *buf = NULL;
1625
1626                         if (sgl)
1627                                 buf = kmap(sg_page(sgl)) + sgl->offset;
1628
1629                         if (buf) {
1630                                 memset(buf, 0, sgl->length);
1631                                 kunmap(sg_page(sgl));
1632                         }
1633                 }
1634
1635                 rc = transport_generic_map_mem_to_cmd(se_cmd, sgl, sgl_count,
1636                                 sgl_bidi, sgl_bidi_count);
1637                 if (rc != 0) {
1638                         transport_generic_request_failure(se_cmd, rc);
1639                         return 0;
1640                 }
1641         }
1642
1643         /*
1644          * Check if we need to delay processing because of ALUA
1645          * Active/NonOptimized primary access state..
1646          */
1647         core_alua_check_nonop_delay(se_cmd);
1648
1649         transport_handle_cdb_direct(se_cmd);
1650         return 0;
1651 }
1652 EXPORT_SYMBOL(target_submit_cmd_map_sgls);
1653
1654 /**
1655  * target_submit_cmd - lookup unpacked lun and submit uninitialized se_cmd
1656  *
1657  * @se_cmd: command descriptor to submit
1658  * @se_sess: associated se_sess for endpoint
1659  * @cdb: pointer to SCSI CDB
1660  * @sense: pointer to SCSI sense buffer
1661  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1662  * @data_length: fabric expected data transfer length
1663  * @task_attr: SAM task attribute
1664  * @data_dir: DMA data direction
1665  * @flags: flags for command submission from target_sc_flags_tables
1666  *
1667  * Task tags are supported if the caller has set @se_cmd->tag.
1668  *
1669  * Returns non zero to signal active I/O shutdown failure.  All other
1670  * setup exceptions will be returned as a SCSI CHECK_CONDITION response,
1671  * but still return zero here.
1672  *
1673  * This may only be called from process context, and also currently
1674  * assumes internal allocation of fabric payload buffer by target-core.
1675  *
1676  * It also assumes interal target core SGL memory allocation.
1677  */
1678 int target_submit_cmd(struct se_cmd *se_cmd, struct se_session *se_sess,
1679                 unsigned char *cdb, unsigned char *sense, u64 unpacked_lun,
1680                 u32 data_length, int task_attr, int data_dir, int flags)
1681 {
1682         return target_submit_cmd_map_sgls(se_cmd, se_sess, cdb, sense,
1683                         unpacked_lun, data_length, task_attr, data_dir,
1684                         flags, NULL, 0, NULL, 0, NULL, 0);
1685 }
1686 EXPORT_SYMBOL(target_submit_cmd);
1687
1688 static void target_complete_tmr_failure(struct work_struct *work)
1689 {
1690         struct se_cmd *se_cmd = container_of(work, struct se_cmd, work);
1691
1692         se_cmd->se_tmr_req->response = TMR_LUN_DOES_NOT_EXIST;
1693         se_cmd->se_tfo->queue_tm_rsp(se_cmd);
1694
1695         transport_lun_remove_cmd(se_cmd);
1696         transport_cmd_check_stop_to_fabric(se_cmd);
1697 }
1698
1699 static bool target_lookup_lun_from_tag(struct se_session *se_sess, u64 tag,
1700                                        u64 *unpacked_lun)
1701 {
1702         struct se_cmd *se_cmd;
1703         unsigned long flags;
1704         bool ret = false;
1705
1706         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
1707         list_for_each_entry(se_cmd, &se_sess->sess_cmd_list, se_cmd_list) {
1708                 if (se_cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
1709                         continue;
1710
1711                 if (se_cmd->tag == tag) {
1712                         *unpacked_lun = se_cmd->orig_fe_lun;
1713                         ret = true;
1714                         break;
1715                 }
1716         }
1717         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
1718
1719         return ret;
1720 }
1721
1722 /**
1723  * target_submit_tmr - lookup unpacked lun and submit uninitialized se_cmd
1724  *                     for TMR CDBs
1725  *
1726  * @se_cmd: command descriptor to submit
1727  * @se_sess: associated se_sess for endpoint
1728  * @sense: pointer to SCSI sense buffer
1729  * @unpacked_lun: unpacked LUN to reference for struct se_lun
1730  * @fabric_tmr_ptr: fabric context for TMR req
1731  * @tm_type: Type of TM request
1732  * @gfp: gfp type for caller
1733  * @tag: referenced task tag for TMR_ABORT_TASK
1734  * @flags: submit cmd flags
1735  *
1736  * Callable from all contexts.
1737  **/
1738
1739 int target_submit_tmr(struct se_cmd *se_cmd, struct se_session *se_sess,
1740                 unsigned char *sense, u64 unpacked_lun,
1741                 void *fabric_tmr_ptr, unsigned char tm_type,
1742                 gfp_t gfp, u64 tag, int flags)
1743 {
1744         struct se_portal_group *se_tpg;
1745         int ret;
1746
1747         se_tpg = se_sess->se_tpg;
1748         BUG_ON(!se_tpg);
1749
1750         transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1751                               0, DMA_NONE, TCM_SIMPLE_TAG, sense);
1752         /*
1753          * FIXME: Currently expect caller to handle se_cmd->se_tmr_req
1754          * allocation failure.
1755          */
1756         ret = core_tmr_alloc_req(se_cmd, fabric_tmr_ptr, tm_type, gfp);
1757         if (ret < 0)
1758                 return -ENOMEM;
1759
1760         if (tm_type == TMR_ABORT_TASK)
1761                 se_cmd->se_tmr_req->ref_task_tag = tag;
1762
1763         /* See target_submit_cmd for commentary */
1764         ret = target_get_sess_cmd(se_cmd, flags & TARGET_SCF_ACK_KREF);
1765         if (ret) {
1766                 core_tmr_release_req(se_cmd->se_tmr_req);
1767                 return ret;
1768         }
1769         /*
1770          * If this is ABORT_TASK with no explicit fabric provided LUN,
1771          * go ahead and search active session tags for a match to figure
1772          * out unpacked_lun for the original se_cmd.
1773          */
1774         if (tm_type == TMR_ABORT_TASK && (flags & TARGET_SCF_LOOKUP_LUN_FROM_TAG)) {
1775                 if (!target_lookup_lun_from_tag(se_sess, tag, &unpacked_lun))
1776                         goto failure;
1777         }
1778
1779         ret = transport_lookup_tmr_lun(se_cmd, unpacked_lun);
1780         if (ret)
1781                 goto failure;
1782
1783         transport_generic_handle_tmr(se_cmd);
1784         return 0;
1785
1786         /*
1787          * For callback during failure handling, push this work off
1788          * to process context with TMR_LUN_DOES_NOT_EXIST status.
1789          */
1790 failure:
1791         INIT_WORK(&se_cmd->work, target_complete_tmr_failure);
1792         schedule_work(&se_cmd->work);
1793         return 0;
1794 }
1795 EXPORT_SYMBOL(target_submit_tmr);
1796
1797 /*
1798  * Handle SAM-esque emulation for generic transport request failures.
1799  */
1800 void transport_generic_request_failure(struct se_cmd *cmd,
1801                 sense_reason_t sense_reason)
1802 {
1803         int ret = 0, post_ret = 0;
1804
1805         pr_debug("-----[ Storage Engine Exception; sense_reason %d\n",
1806                  sense_reason);
1807         target_show_cmd("-----[ ", cmd);
1808
1809         /*
1810          * For SAM Task Attribute emulation for failed struct se_cmd
1811          */
1812         transport_complete_task_attr(cmd);
1813
1814         /*
1815          * Handle special case for COMPARE_AND_WRITE failure, where the
1816          * callback is expected to drop the per device ->caw_sem.
1817          */
1818         if ((cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) &&
1819              cmd->transport_complete_callback)
1820                 cmd->transport_complete_callback(cmd, false, &post_ret);
1821
1822         if (transport_check_aborted_status(cmd, 1))
1823                 return;
1824
1825         switch (sense_reason) {
1826         case TCM_NON_EXISTENT_LUN:
1827         case TCM_UNSUPPORTED_SCSI_OPCODE:
1828         case TCM_INVALID_CDB_FIELD:
1829         case TCM_INVALID_PARAMETER_LIST:
1830         case TCM_PARAMETER_LIST_LENGTH_ERROR:
1831         case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
1832         case TCM_UNKNOWN_MODE_PAGE:
1833         case TCM_WRITE_PROTECTED:
1834         case TCM_ADDRESS_OUT_OF_RANGE:
1835         case TCM_CHECK_CONDITION_ABORT_CMD:
1836         case TCM_CHECK_CONDITION_UNIT_ATTENTION:
1837         case TCM_CHECK_CONDITION_NOT_READY:
1838         case TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED:
1839         case TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED:
1840         case TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED:
1841         case TCM_COPY_TARGET_DEVICE_NOT_REACHABLE:
1842         case TCM_TOO_MANY_TARGET_DESCS:
1843         case TCM_UNSUPPORTED_TARGET_DESC_TYPE_CODE:
1844         case TCM_TOO_MANY_SEGMENT_DESCS:
1845         case TCM_UNSUPPORTED_SEGMENT_DESC_TYPE_CODE:
1846                 break;
1847         case TCM_OUT_OF_RESOURCES:
1848                 cmd->scsi_status = SAM_STAT_TASK_SET_FULL;
1849                 goto queue_status;
1850         case TCM_LUN_BUSY:
1851                 cmd->scsi_status = SAM_STAT_BUSY;
1852                 goto queue_status;
1853         case TCM_RESERVATION_CONFLICT:
1854                 /*
1855                  * No SENSE Data payload for this case, set SCSI Status
1856                  * and queue the response to $FABRIC_MOD.
1857                  *
1858                  * Uses linux/include/scsi/scsi.h SAM status codes defs
1859                  */
1860                 cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1861                 /*
1862                  * For UA Interlock Code 11b, a RESERVATION CONFLICT will
1863                  * establish a UNIT ATTENTION with PREVIOUS RESERVATION
1864                  * CONFLICT STATUS.
1865                  *
1866                  * See spc4r17, section 7.4.6 Control Mode Page, Table 349
1867                  */
1868                 if (cmd->se_sess &&
1869                     cmd->se_dev->dev_attrib.emulate_ua_intlck_ctrl == 2) {
1870                         target_ua_allocate_lun(cmd->se_sess->se_node_acl,
1871                                                cmd->orig_fe_lun, 0x2C,
1872                                         ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
1873                 }
1874
1875                 goto queue_status;
1876         default:
1877                 pr_err("Unknown transport error for CDB 0x%02x: %d\n",
1878                         cmd->t_task_cdb[0], sense_reason);
1879                 sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
1880                 break;
1881         }
1882
1883         ret = transport_send_check_condition_and_sense(cmd, sense_reason, 0);
1884         if (ret)
1885                 goto queue_full;
1886
1887 check_stop:
1888         transport_lun_remove_cmd(cmd);
1889         transport_cmd_check_stop_to_fabric(cmd);
1890         return;
1891
1892 queue_status:
1893         trace_target_cmd_complete(cmd);
1894         ret = cmd->se_tfo->queue_status(cmd);
1895         if (!ret)
1896                 goto check_stop;
1897 queue_full:
1898         transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
1899 }
1900 EXPORT_SYMBOL(transport_generic_request_failure);
1901
1902 void __target_execute_cmd(struct se_cmd *cmd, bool do_checks)
1903 {
1904         sense_reason_t ret;
1905
1906         if (!cmd->execute_cmd) {
1907                 ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1908                 goto err;
1909         }
1910         if (do_checks) {
1911                 /*
1912                  * Check for an existing UNIT ATTENTION condition after
1913                  * target_handle_task_attr() has done SAM task attr
1914                  * checking, and possibly have already defered execution
1915                  * out to target_restart_delayed_cmds() context.
1916                  */
1917                 ret = target_scsi3_ua_check(cmd);
1918                 if (ret)
1919                         goto err;
1920
1921                 ret = target_alua_state_check(cmd);
1922                 if (ret)
1923                         goto err;
1924
1925                 ret = target_check_reservation(cmd);
1926                 if (ret) {
1927                         cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1928                         goto err;
1929                 }
1930         }
1931
1932         ret = cmd->execute_cmd(cmd);
1933         if (!ret)
1934                 return;
1935 err:
1936         spin_lock_irq(&cmd->t_state_lock);
1937         cmd->transport_state &= ~CMD_T_SENT;
1938         spin_unlock_irq(&cmd->t_state_lock);
1939
1940         transport_generic_request_failure(cmd, ret);
1941 }
1942
1943 static int target_write_prot_action(struct se_cmd *cmd)
1944 {
1945         u32 sectors;
1946         /*
1947          * Perform WRITE_INSERT of PI using software emulation when backend
1948          * device has PI enabled, if the transport has not already generated
1949          * PI using hardware WRITE_INSERT offload.
1950          */
1951         switch (cmd->prot_op) {
1952         case TARGET_PROT_DOUT_INSERT:
1953                 if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_INSERT))
1954                         sbc_dif_generate(cmd);
1955                 break;
1956         case TARGET_PROT_DOUT_STRIP:
1957                 if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DOUT_STRIP)
1958                         break;
1959
1960                 sectors = cmd->data_length >> ilog2(cmd->se_dev->dev_attrib.block_size);
1961                 cmd->pi_err = sbc_dif_verify(cmd, cmd->t_task_lba,
1962                                              sectors, 0, cmd->t_prot_sg, 0);
1963                 if (unlikely(cmd->pi_err)) {
1964                         spin_lock_irq(&cmd->t_state_lock);
1965                         cmd->transport_state &= ~CMD_T_SENT;
1966                         spin_unlock_irq(&cmd->t_state_lock);
1967                         transport_generic_request_failure(cmd, cmd->pi_err);
1968                         return -1;
1969                 }
1970                 break;
1971         default:
1972                 break;
1973         }
1974
1975         return 0;
1976 }
1977
1978 static bool target_handle_task_attr(struct se_cmd *cmd)
1979 {
1980         struct se_device *dev = cmd->se_dev;
1981
1982         if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
1983                 return false;
1984
1985         cmd->se_cmd_flags |= SCF_TASK_ATTR_SET;
1986
1987         /*
1988          * Check for the existence of HEAD_OF_QUEUE, and if true return 1
1989          * to allow the passed struct se_cmd list of tasks to the front of the list.
1990          */
1991         switch (cmd->sam_task_attr) {
1992         case TCM_HEAD_TAG:
1993                 atomic_inc_mb(&dev->non_ordered);
1994                 pr_debug("Added HEAD_OF_QUEUE for CDB: 0x%02x\n",
1995                          cmd->t_task_cdb[0]);
1996                 return false;
1997         case TCM_ORDERED_TAG:
1998                 atomic_inc_mb(&dev->delayed_cmd_count);
1999
2000                 pr_debug("Added ORDERED for CDB: 0x%02x to ordered list\n",
2001                          cmd->t_task_cdb[0]);
2002                 break;
2003         default:
2004                 /*
2005                  * For SIMPLE and UNTAGGED Task Attribute commands
2006                  */
2007                 atomic_inc_mb(&dev->non_ordered);
2008
2009                 if (atomic_read(&dev->delayed_cmd_count) == 0)
2010                         return false;
2011                 break;
2012         }
2013
2014         if (cmd->sam_task_attr != TCM_ORDERED_TAG) {
2015                 atomic_inc_mb(&dev->delayed_cmd_count);
2016                 /*
2017                  * We will account for this when we dequeue from the delayed
2018                  * list.
2019                  */
2020                 atomic_dec_mb(&dev->non_ordered);
2021         }
2022
2023         spin_lock(&dev->delayed_cmd_lock);
2024         list_add_tail(&cmd->se_delayed_node, &dev->delayed_cmd_list);
2025         spin_unlock(&dev->delayed_cmd_lock);
2026
2027         pr_debug("Added CDB: 0x%02x Task Attr: 0x%02x to delayed CMD listn",
2028                 cmd->t_task_cdb[0], cmd->sam_task_attr);
2029         /*
2030          * We may have no non ordered cmds when this function started or we
2031          * could have raced with the last simple/head cmd completing, so kick
2032          * the delayed handler here.
2033          */
2034         schedule_work(&dev->delayed_cmd_work);
2035         return true;
2036 }
2037
2038 static int __transport_check_aborted_status(struct se_cmd *, int);
2039
2040 void target_execute_cmd(struct se_cmd *cmd)
2041 {
2042         /*
2043          * Determine if frontend context caller is requesting the stopping of
2044          * this command for frontend exceptions.
2045          *
2046          * If the received CDB has aleady been aborted stop processing it here.
2047          */
2048         spin_lock_irq(&cmd->t_state_lock);
2049         if (__transport_check_aborted_status(cmd, 1)) {
2050                 spin_unlock_irq(&cmd->t_state_lock);
2051                 return;
2052         }
2053         if (cmd->transport_state & CMD_T_STOP) {
2054                 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
2055                         __func__, __LINE__, cmd->tag);
2056
2057                 spin_unlock_irq(&cmd->t_state_lock);
2058                 complete_all(&cmd->t_transport_stop_comp);
2059                 return;
2060         }
2061
2062         cmd->t_state = TRANSPORT_PROCESSING;
2063         cmd->transport_state &= ~CMD_T_PRE_EXECUTE;
2064         cmd->transport_state |= CMD_T_ACTIVE | CMD_T_SENT;
2065         spin_unlock_irq(&cmd->t_state_lock);
2066
2067         if (target_write_prot_action(cmd))
2068                 return;
2069
2070         if (target_handle_task_attr(cmd)) {
2071                 spin_lock_irq(&cmd->t_state_lock);
2072                 cmd->transport_state &= ~CMD_T_SENT;
2073                 spin_unlock_irq(&cmd->t_state_lock);
2074                 return;
2075         }
2076
2077         __target_execute_cmd(cmd, true);
2078 }
2079 EXPORT_SYMBOL(target_execute_cmd);
2080
2081 /*
2082  * Process all commands up to the last received ORDERED task attribute which
2083  * requires another blocking boundary
2084  */
2085 void target_do_delayed_work(struct work_struct *work)
2086 {
2087         struct se_device *dev = container_of(work, struct se_device,
2088                                              delayed_cmd_work);
2089
2090         spin_lock(&dev->delayed_cmd_lock);
2091         while (!dev->ordered_sync_in_progress) {
2092                 struct se_cmd *cmd;
2093
2094                 if (list_empty(&dev->delayed_cmd_list))
2095                         break;
2096
2097                 cmd = list_entry(dev->delayed_cmd_list.next,
2098                                  struct se_cmd, se_delayed_node);
2099
2100                 if (cmd->sam_task_attr == TCM_ORDERED_TAG) {
2101                         /*
2102                          * Check if we started with:
2103                          * [ordered] [simple] [ordered]
2104                          * and we are now at the last ordered so we have to wait
2105                          * for the simple cmd.
2106                          */
2107                         if (atomic_read(&dev->non_ordered) > 0)
2108                                 break;
2109
2110                         dev->ordered_sync_in_progress = true;
2111                 }
2112
2113                 list_del(&cmd->se_delayed_node);
2114                 atomic_dec_mb(&dev->delayed_cmd_count);
2115                 spin_unlock(&dev->delayed_cmd_lock);
2116
2117                 if (cmd->sam_task_attr != TCM_ORDERED_TAG)
2118                         atomic_inc_mb(&dev->non_ordered);
2119
2120                 cmd->transport_state |= CMD_T_SENT;
2121
2122                 __target_execute_cmd(cmd, true);
2123
2124                 spin_lock(&dev->delayed_cmd_lock);
2125         }
2126         spin_unlock(&dev->delayed_cmd_lock);
2127 }
2128
2129 /*
2130  * Called from I/O completion to determine which dormant/delayed
2131  * and ordered cmds need to have their tasks added to the execution queue.
2132  */
2133 static void transport_complete_task_attr(struct se_cmd *cmd)
2134 {
2135         struct se_device *dev = cmd->se_dev;
2136
2137         if (dev->transport->transport_flags & TRANSPORT_FLAG_PASSTHROUGH)
2138                 return;
2139
2140         if (!(cmd->se_cmd_flags & SCF_TASK_ATTR_SET))
2141                 goto restart;
2142
2143         if (cmd->sam_task_attr == TCM_SIMPLE_TAG) {
2144                 atomic_dec_mb(&dev->non_ordered);
2145                 dev->dev_cur_ordered_id++;
2146         } else if (cmd->sam_task_attr == TCM_HEAD_TAG) {
2147                 atomic_dec_mb(&dev->non_ordered);
2148                 dev->dev_cur_ordered_id++;
2149                 pr_debug("Incremented dev_cur_ordered_id: %u for HEAD_OF_QUEUE\n",
2150                          dev->dev_cur_ordered_id);
2151         } else if (cmd->sam_task_attr == TCM_ORDERED_TAG) {
2152                 spin_lock(&dev->delayed_cmd_lock);
2153                 dev->ordered_sync_in_progress = false;
2154                 spin_unlock(&dev->delayed_cmd_lock);
2155
2156                 dev->dev_cur_ordered_id++;
2157                 pr_debug("Incremented dev_cur_ordered_id: %u for ORDERED\n",
2158                          dev->dev_cur_ordered_id);
2159         }
2160         cmd->se_cmd_flags &= ~SCF_TASK_ATTR_SET;
2161
2162 restart:
2163         if (atomic_read(&dev->delayed_cmd_count) > 0)
2164                 schedule_work(&dev->delayed_cmd_work);
2165 }
2166
2167 static void transport_complete_qf(struct se_cmd *cmd)
2168 {
2169         int ret = 0;
2170
2171         transport_complete_task_attr(cmd);
2172         /*
2173          * If a fabric driver ->write_pending() or ->queue_data_in() callback
2174          * has returned neither -ENOMEM or -EAGAIN, assume it's fatal and
2175          * the same callbacks should not be retried.  Return CHECK_CONDITION
2176          * if a scsi_status is not already set.
2177          *
2178          * If a fabric driver ->queue_status() has returned non zero, always
2179          * keep retrying no matter what..
2180          */
2181         if (cmd->t_state == TRANSPORT_COMPLETE_QF_ERR) {
2182                 if (cmd->scsi_status)
2183                         goto queue_status;
2184
2185                 translate_sense_reason(cmd, TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE);
2186                 goto queue_status;
2187         }
2188
2189         /*
2190          * Check if we need to send a sense buffer from
2191          * the struct se_cmd in question. We do NOT want
2192          * to take this path of the IO has been marked as
2193          * needing to be treated like a "normal read". This
2194          * is the case if it's a tape read, and either the
2195          * FM, EOM, or ILI bits are set, but there is no
2196          * sense data.
2197          */
2198         if (!(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
2199             cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
2200                 goto queue_status;
2201
2202         switch (cmd->data_direction) {
2203         case DMA_FROM_DEVICE:
2204                 /* queue status if not treating this as a normal read */
2205                 if (cmd->scsi_status &&
2206                     !(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL))
2207                         goto queue_status;
2208
2209                 trace_target_cmd_complete(cmd);
2210                 ret = cmd->se_tfo->queue_data_in(cmd);
2211                 break;
2212         case DMA_TO_DEVICE:
2213                 if (cmd->se_cmd_flags & SCF_BIDI) {
2214                         ret = cmd->se_tfo->queue_data_in(cmd);
2215                         break;
2216                 }
2217                 /* fall through */
2218         case DMA_NONE:
2219 queue_status:
2220                 trace_target_cmd_complete(cmd);
2221                 ret = cmd->se_tfo->queue_status(cmd);
2222                 break;
2223         default:
2224                 break;
2225         }
2226
2227         if (ret < 0) {
2228                 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2229                 return;
2230         }
2231         transport_lun_remove_cmd(cmd);
2232         transport_cmd_check_stop_to_fabric(cmd);
2233 }
2234
2235 static void transport_handle_queue_full(struct se_cmd *cmd, struct se_device *dev,
2236                                         int err, bool write_pending)
2237 {
2238         /*
2239          * -EAGAIN or -ENOMEM signals retry of ->write_pending() and/or
2240          * ->queue_data_in() callbacks from new process context.
2241          *
2242          * Otherwise for other errors, transport_complete_qf() will send
2243          * CHECK_CONDITION via ->queue_status() instead of attempting to
2244          * retry associated fabric driver data-transfer callbacks.
2245          */
2246         if (err == -EAGAIN || err == -ENOMEM) {
2247                 cmd->t_state = (write_pending) ? TRANSPORT_COMPLETE_QF_WP :
2248                                                  TRANSPORT_COMPLETE_QF_OK;
2249         } else {
2250                 pr_warn_ratelimited("Got unknown fabric queue status: %d\n", err);
2251                 cmd->t_state = TRANSPORT_COMPLETE_QF_ERR;
2252         }
2253
2254         spin_lock_irq(&dev->qf_cmd_lock);
2255         list_add_tail(&cmd->se_qf_node, &cmd->se_dev->qf_cmd_list);
2256         atomic_inc_mb(&dev->dev_qf_count);
2257         spin_unlock_irq(&cmd->se_dev->qf_cmd_lock);
2258
2259         schedule_work(&cmd->se_dev->qf_work_queue);
2260 }
2261
2262 static bool target_read_prot_action(struct se_cmd *cmd)
2263 {
2264         switch (cmd->prot_op) {
2265         case TARGET_PROT_DIN_STRIP:
2266                 if (!(cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_STRIP)) {
2267                         u32 sectors = cmd->data_length >>
2268                                   ilog2(cmd->se_dev->dev_attrib.block_size);
2269
2270                         cmd->pi_err = sbc_dif_verify(cmd, cmd->t_task_lba,
2271                                                      sectors, 0, cmd->t_prot_sg,
2272                                                      0);
2273                         if (cmd->pi_err)
2274                                 return true;
2275                 }
2276                 break;
2277         case TARGET_PROT_DIN_INSERT:
2278                 if (cmd->se_sess->sup_prot_ops & TARGET_PROT_DIN_INSERT)
2279                         break;
2280
2281                 sbc_dif_generate(cmd);
2282                 break;
2283         default:
2284                 break;
2285         }
2286
2287         return false;
2288 }
2289
2290 static void target_complete_ok_work(struct work_struct *work)
2291 {
2292         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
2293         int ret;
2294
2295         /*
2296          * Check if we need to move delayed/dormant tasks from cmds on the
2297          * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
2298          * Attribute.
2299          */
2300         transport_complete_task_attr(cmd);
2301
2302         /*
2303          * Check to schedule QUEUE_FULL work, or execute an existing
2304          * cmd->transport_qf_callback()
2305          */
2306         if (atomic_read(&cmd->se_dev->dev_qf_count) != 0)
2307                 schedule_work(&cmd->se_dev->qf_work_queue);
2308
2309         /*
2310          * Check if we need to send a sense buffer from
2311          * the struct se_cmd in question. We do NOT want
2312          * to take this path of the IO has been marked as
2313          * needing to be treated like a "normal read". This
2314          * is the case if it's a tape read, and either the
2315          * FM, EOM, or ILI bits are set, but there is no
2316          * sense data.
2317          */
2318         if (!(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL) &&
2319             cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
2320                 WARN_ON(!cmd->scsi_status);
2321                 ret = transport_send_check_condition_and_sense(
2322                                         cmd, 0, 1);
2323                 if (ret)
2324                         goto queue_full;
2325
2326                 transport_lun_remove_cmd(cmd);
2327                 transport_cmd_check_stop_to_fabric(cmd);
2328                 return;
2329         }
2330         /*
2331          * Check for a callback, used by amongst other things
2332          * XDWRITE_READ_10 and COMPARE_AND_WRITE emulation.
2333          */
2334         if (cmd->transport_complete_callback) {
2335                 sense_reason_t rc;
2336                 bool caw = (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE);
2337                 bool zero_dl = !(cmd->data_length);
2338                 int post_ret = 0;
2339
2340                 rc = cmd->transport_complete_callback(cmd, true, &post_ret);
2341                 if (!rc && !post_ret) {
2342                         if (caw && zero_dl)
2343                                 goto queue_rsp;
2344
2345                         return;
2346                 } else if (rc) {
2347                         ret = transport_send_check_condition_and_sense(cmd,
2348                                                 rc, 0);
2349                         if (ret)
2350                                 goto queue_full;
2351
2352                         transport_lun_remove_cmd(cmd);
2353                         transport_cmd_check_stop_to_fabric(cmd);
2354                         return;
2355                 }
2356         }
2357
2358 queue_rsp:
2359         switch (cmd->data_direction) {
2360         case DMA_FROM_DEVICE:
2361                 /*
2362                  * if this is a READ-type IO, but SCSI status
2363                  * is set, then skip returning data and just
2364                  * return the status -- unless this IO is marked
2365                  * as needing to be treated as a normal read,
2366                  * in which case we want to go ahead and return
2367                  * the data. This happens, for example, for tape
2368                  * reads with the FM, EOM, or ILI bits set, with
2369                  * no sense data.
2370                  */
2371                 if (cmd->scsi_status &&
2372                     !(cmd->se_cmd_flags & SCF_TREAT_READ_AS_NORMAL))
2373                         goto queue_status;
2374
2375                 atomic_long_add(cmd->data_length,
2376                                 &cmd->se_lun->lun_stats.tx_data_octets);
2377                 /*
2378                  * Perform READ_STRIP of PI using software emulation when
2379                  * backend had PI enabled, if the transport will not be
2380                  * performing hardware READ_STRIP offload.
2381                  */
2382                 if (target_read_prot_action(cmd)) {
2383                         ret = transport_send_check_condition_and_sense(cmd,
2384                                                 cmd->pi_err, 0);
2385                         if (ret)
2386                                 goto queue_full;
2387
2388                         transport_lun_remove_cmd(cmd);
2389                         transport_cmd_check_stop_to_fabric(cmd);
2390                         return;
2391                 }
2392
2393                 trace_target_cmd_complete(cmd);
2394                 ret = cmd->se_tfo->queue_data_in(cmd);
2395                 if (ret)
2396                         goto queue_full;
2397                 break;
2398         case DMA_TO_DEVICE:
2399                 atomic_long_add(cmd->data_length,
2400                                 &cmd->se_lun->lun_stats.rx_data_octets);
2401                 /*
2402                  * Check if we need to send READ payload for BIDI-COMMAND
2403                  */
2404                 if (cmd->se_cmd_flags & SCF_BIDI) {
2405                         atomic_long_add(cmd->data_length,
2406                                         &cmd->se_lun->lun_stats.tx_data_octets);
2407                         ret = cmd->se_tfo->queue_data_in(cmd);
2408                         if (ret)
2409                                 goto queue_full;
2410                         break;
2411                 }
2412                 /* fall through */
2413         case DMA_NONE:
2414 queue_status:
2415                 trace_target_cmd_complete(cmd);
2416                 ret = cmd->se_tfo->queue_status(cmd);
2417                 if (ret)
2418                         goto queue_full;
2419                 break;
2420         default:
2421                 break;
2422         }
2423
2424         transport_lun_remove_cmd(cmd);
2425         transport_cmd_check_stop_to_fabric(cmd);
2426         return;
2427
2428 queue_full:
2429         pr_debug("Handling complete_ok QUEUE_FULL: se_cmd: %p,"
2430                 " data_direction: %d\n", cmd, cmd->data_direction);
2431
2432         transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
2433 }
2434
2435 void target_free_sgl(struct scatterlist *sgl, int nents)
2436 {
2437         sgl_free_n_order(sgl, nents, 0);
2438 }
2439 EXPORT_SYMBOL(target_free_sgl);
2440
2441 static inline void transport_reset_sgl_orig(struct se_cmd *cmd)
2442 {
2443         /*
2444          * Check for saved t_data_sg that may be used for COMPARE_AND_WRITE
2445          * emulation, and free + reset pointers if necessary..
2446          */
2447         if (!cmd->t_data_sg_orig)
2448                 return;
2449
2450         kfree(cmd->t_data_sg);
2451         cmd->t_data_sg = cmd->t_data_sg_orig;
2452         cmd->t_data_sg_orig = NULL;
2453         cmd->t_data_nents = cmd->t_data_nents_orig;
2454         cmd->t_data_nents_orig = 0;
2455 }
2456
2457 static inline void transport_free_pages(struct se_cmd *cmd)
2458 {
2459         if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC)) {
2460                 target_free_sgl(cmd->t_prot_sg, cmd->t_prot_nents);
2461                 cmd->t_prot_sg = NULL;
2462                 cmd->t_prot_nents = 0;
2463         }
2464
2465         if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) {
2466                 /*
2467                  * Release special case READ buffer payload required for
2468                  * SG_TO_MEM_NOALLOC to function with COMPARE_AND_WRITE
2469                  */
2470                 if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) {
2471                         target_free_sgl(cmd->t_bidi_data_sg,
2472                                            cmd->t_bidi_data_nents);
2473                         cmd->t_bidi_data_sg = NULL;
2474                         cmd->t_bidi_data_nents = 0;
2475                 }
2476                 transport_reset_sgl_orig(cmd);
2477                 return;
2478         }
2479         transport_reset_sgl_orig(cmd);
2480
2481         target_free_sgl(cmd->t_data_sg, cmd->t_data_nents);
2482         cmd->t_data_sg = NULL;
2483         cmd->t_data_nents = 0;
2484
2485         target_free_sgl(cmd->t_bidi_data_sg, cmd->t_bidi_data_nents);
2486         cmd->t_bidi_data_sg = NULL;
2487         cmd->t_bidi_data_nents = 0;
2488 }
2489
2490 void *transport_kmap_data_sg(struct se_cmd *cmd)
2491 {
2492         struct scatterlist *sg = cmd->t_data_sg;
2493         struct page **pages;
2494         int i;
2495
2496         /*
2497          * We need to take into account a possible offset here for fabrics like
2498          * tcm_loop who may be using a contig buffer from the SCSI midlayer for
2499          * control CDBs passed as SGLs via transport_generic_map_mem_to_cmd()
2500          */
2501         if (!cmd->t_data_nents)
2502                 return NULL;
2503
2504         BUG_ON(!sg);
2505         if (cmd->t_data_nents == 1)
2506                 return kmap(sg_page(sg)) + sg->offset;
2507
2508         /* >1 page. use vmap */
2509         pages = kmalloc_array(cmd->t_data_nents, sizeof(*pages), GFP_KERNEL);
2510         if (!pages)
2511                 return NULL;
2512
2513         /* convert sg[] to pages[] */
2514         for_each_sg(cmd->t_data_sg, sg, cmd->t_data_nents, i) {
2515                 pages[i] = sg_page(sg);
2516         }
2517
2518         cmd->t_data_vmap = vmap(pages, cmd->t_data_nents,  VM_MAP, PAGE_KERNEL);
2519         kfree(pages);
2520         if (!cmd->t_data_vmap)
2521                 return NULL;
2522
2523         return cmd->t_data_vmap + cmd->t_data_sg[0].offset;
2524 }
2525 EXPORT_SYMBOL(transport_kmap_data_sg);
2526
2527 void transport_kunmap_data_sg(struct se_cmd *cmd)
2528 {
2529         if (!cmd->t_data_nents) {
2530                 return;
2531         } else if (cmd->t_data_nents == 1) {
2532                 kunmap(sg_page(cmd->t_data_sg));
2533                 return;
2534         }
2535
2536         vunmap(cmd->t_data_vmap);
2537         cmd->t_data_vmap = NULL;
2538 }
2539 EXPORT_SYMBOL(transport_kunmap_data_sg);
2540
2541 int
2542 target_alloc_sgl(struct scatterlist **sgl, unsigned int *nents, u32 length,
2543                  bool zero_page, bool chainable)
2544 {
2545         gfp_t gfp = GFP_KERNEL | (zero_page ? __GFP_ZERO : 0);
2546
2547         *sgl = sgl_alloc_order(length, 0, chainable, gfp, nents);
2548         return *sgl ? 0 : -ENOMEM;
2549 }
2550 EXPORT_SYMBOL(target_alloc_sgl);
2551
2552 /*
2553  * Allocate any required resources to execute the command.  For writes we
2554  * might not have the payload yet, so notify the fabric via a call to
2555  * ->write_pending instead. Otherwise place it on the execution queue.
2556  */
2557 sense_reason_t
2558 transport_generic_new_cmd(struct se_cmd *cmd)
2559 {
2560         unsigned long flags;
2561         int ret = 0;
2562         bool zero_flag = !(cmd->se_cmd_flags & SCF_SCSI_DATA_CDB);
2563
2564         if (cmd->prot_op != TARGET_PROT_NORMAL &&
2565             !(cmd->se_cmd_flags & SCF_PASSTHROUGH_PROT_SG_TO_MEM_NOALLOC)) {
2566                 ret = target_alloc_sgl(&cmd->t_prot_sg, &cmd->t_prot_nents,
2567                                        cmd->prot_length, true, false);
2568                 if (ret < 0)
2569                         return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2570         }
2571
2572         /*
2573          * Determine is the TCM fabric module has already allocated physical
2574          * memory, and is directly calling transport_generic_map_mem_to_cmd()
2575          * beforehand.
2576          */
2577         if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) &&
2578             cmd->data_length) {
2579
2580                 if ((cmd->se_cmd_flags & SCF_BIDI) ||
2581                     (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)) {
2582                         u32 bidi_length;
2583
2584                         if (cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE)
2585                                 bidi_length = cmd->t_task_nolb *
2586                                               cmd->se_dev->dev_attrib.block_size;
2587                         else
2588                                 bidi_length = cmd->data_length;
2589
2590                         ret = target_alloc_sgl(&cmd->t_bidi_data_sg,
2591                                                &cmd->t_bidi_data_nents,
2592                                                bidi_length, zero_flag, false);
2593                         if (ret < 0)
2594                                 return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2595                 }
2596
2597                 ret = target_alloc_sgl(&cmd->t_data_sg, &cmd->t_data_nents,
2598                                        cmd->data_length, zero_flag, false);
2599                 if (ret < 0)
2600                         return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2601         } else if ((cmd->se_cmd_flags & SCF_COMPARE_AND_WRITE) &&
2602                     cmd->data_length) {
2603                 /*
2604                  * Special case for COMPARE_AND_WRITE with fabrics
2605                  * using SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC.
2606                  */
2607                 u32 caw_length = cmd->t_task_nolb *
2608                                  cmd->se_dev->dev_attrib.block_size;
2609
2610                 ret = target_alloc_sgl(&cmd->t_bidi_data_sg,
2611                                        &cmd->t_bidi_data_nents,
2612                                        caw_length, zero_flag, false);
2613                 if (ret < 0)
2614                         return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2615         }
2616         /*
2617          * If this command is not a write we can execute it right here,
2618          * for write buffers we need to notify the fabric driver first
2619          * and let it call back once the write buffers are ready.
2620          */
2621         target_add_to_state_list(cmd);
2622         if (cmd->data_direction != DMA_TO_DEVICE || cmd->data_length == 0) {
2623                 target_execute_cmd(cmd);
2624                 return 0;
2625         }
2626
2627         spin_lock_irqsave(&cmd->t_state_lock, flags);
2628         cmd->t_state = TRANSPORT_WRITE_PENDING;
2629         /*
2630          * Determine if frontend context caller is requesting the stopping of
2631          * this command for frontend exceptions.
2632          */
2633         if (cmd->transport_state & CMD_T_STOP) {
2634                 pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08llx\n",
2635                          __func__, __LINE__, cmd->tag);
2636
2637                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2638
2639                 complete_all(&cmd->t_transport_stop_comp);
2640                 return 0;
2641         }
2642         cmd->transport_state &= ~CMD_T_ACTIVE;
2643         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2644
2645         ret = cmd->se_tfo->write_pending(cmd);
2646         if (ret)
2647                 goto queue_full;
2648
2649         return 0;
2650
2651 queue_full:
2652         pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n", cmd);
2653         transport_handle_queue_full(cmd, cmd->se_dev, ret, true);
2654         return 0;
2655 }
2656 EXPORT_SYMBOL(transport_generic_new_cmd);
2657
2658 static void transport_write_pending_qf(struct se_cmd *cmd)
2659 {
2660         unsigned long flags;
2661         int ret;
2662         bool stop;
2663
2664         spin_lock_irqsave(&cmd->t_state_lock, flags);
2665         stop = (cmd->transport_state & (CMD_T_STOP | CMD_T_ABORTED));
2666         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2667
2668         if (stop) {
2669                 pr_debug("%s:%d CMD_T_STOP|CMD_T_ABORTED for ITT: 0x%08llx\n",
2670                         __func__, __LINE__, cmd->tag);
2671                 complete_all(&cmd->t_transport_stop_comp);
2672                 return;
2673         }
2674
2675         ret = cmd->se_tfo->write_pending(cmd);
2676         if (ret) {
2677                 pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n",
2678                          cmd);
2679                 transport_handle_queue_full(cmd, cmd->se_dev, ret, true);
2680         }
2681 }
2682
2683 static bool
2684 __transport_wait_for_tasks(struct se_cmd *, bool, bool *, bool *,
2685                            unsigned long *flags);
2686
2687 static void target_wait_free_cmd(struct se_cmd *cmd, bool *aborted, bool *tas)
2688 {
2689         unsigned long flags;
2690
2691         spin_lock_irqsave(&cmd->t_state_lock, flags);
2692         __transport_wait_for_tasks(cmd, true, aborted, tas, &flags);
2693         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2694 }
2695
2696 /*
2697  * This function is called by frontend drivers after processing of a command
2698  * has finished.
2699  *
2700  * The protocol for ensuring that either the regular flow or the TMF
2701  * code drops one reference is as follows:
2702  * - Calling .queue_data_in(), .queue_status() or queue_tm_rsp() will cause
2703  *   the frontend driver to drop one reference, synchronously or asynchronously.
2704  * - During regular command processing the target core sets CMD_T_COMPLETE
2705  *   before invoking one of the .queue_*() functions.
2706  * - The code that aborts commands skips commands and TMFs for which
2707  *   CMD_T_COMPLETE has been set.
2708  * - CMD_T_ABORTED is set atomically after the CMD_T_COMPLETE check for
2709  *   commands that will be aborted.
2710  * - If the CMD_T_ABORTED flag is set but CMD_T_TAS has not been set
2711  *   transport_generic_free_cmd() skips its call to target_put_sess_cmd().
2712  * - For aborted commands for which CMD_T_TAS has been set .queue_status() will
2713  *   be called and will drop a reference.
2714  * - For aborted commands for which CMD_T_TAS has not been set .aborted_task()
2715  *   will be called. transport_cmd_finish_abort() will drop the final reference.
2716  */
2717 int transport_generic_free_cmd(struct se_cmd *cmd, int wait_for_tasks)
2718 {
2719         DECLARE_COMPLETION_ONSTACK(compl);
2720         int ret = 0;
2721         bool aborted = false, tas = false;
2722
2723         if (wait_for_tasks)
2724                 target_wait_free_cmd(cmd, &aborted, &tas);
2725
2726         if (cmd->se_cmd_flags & SCF_SE_LUN_CMD) {
2727                 /*
2728                  * Handle WRITE failure case where transport_generic_new_cmd()
2729                  * has already added se_cmd to state_list, but fabric has
2730                  * failed command before I/O submission.
2731                  */
2732                 if (cmd->state_active)
2733                         target_remove_from_state_list(cmd);
2734
2735                 if (cmd->se_lun)
2736                         transport_lun_remove_cmd(cmd);
2737         }
2738         if (aborted)
2739                 cmd->compl = &compl;
2740         if (!aborted || tas)
2741                 ret = target_put_sess_cmd(cmd);
2742         if (aborted) {
2743                 pr_debug("Detected CMD_T_ABORTED for ITT: %llu\n", cmd->tag);
2744                 wait_for_completion(&compl);
2745                 ret = 1;
2746         }
2747         return ret;
2748 }
2749 EXPORT_SYMBOL(transport_generic_free_cmd);
2750
2751 /**
2752  * target_get_sess_cmd - Add command to active ->sess_cmd_list
2753  * @se_cmd:     command descriptor to add
2754  * @ack_kref:   Signal that fabric will perform an ack target_put_sess_cmd()
2755  */
2756 int target_get_sess_cmd(struct se_cmd *se_cmd, bool ack_kref)
2757 {
2758         struct se_session *se_sess = se_cmd->se_sess;
2759         unsigned long flags;
2760         int ret = 0;
2761
2762         /*
2763          * Add a second kref if the fabric caller is expecting to handle
2764          * fabric acknowledgement that requires two target_put_sess_cmd()
2765          * invocations before se_cmd descriptor release.
2766          */
2767         if (ack_kref) {
2768                 if (!kref_get_unless_zero(&se_cmd->cmd_kref))
2769                         return -EINVAL;
2770
2771                 se_cmd->se_cmd_flags |= SCF_ACK_KREF;
2772         }
2773
2774         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2775         if (se_sess->sess_tearing_down) {
2776                 ret = -ESHUTDOWN;
2777                 goto out;
2778         }
2779         se_cmd->transport_state |= CMD_T_PRE_EXECUTE;
2780         list_add_tail(&se_cmd->se_cmd_list, &se_sess->sess_cmd_list);
2781         percpu_ref_get(&se_sess->cmd_count);
2782 out:
2783         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2784
2785         if (ret && ack_kref)
2786                 target_put_sess_cmd(se_cmd);
2787
2788         return ret;
2789 }
2790 EXPORT_SYMBOL(target_get_sess_cmd);
2791
2792 static void target_free_cmd_mem(struct se_cmd *cmd)
2793 {
2794         transport_free_pages(cmd);
2795
2796         if (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
2797                 core_tmr_release_req(cmd->se_tmr_req);
2798         if (cmd->t_task_cdb != cmd->__t_task_cdb)
2799                 kfree(cmd->t_task_cdb);
2800 }
2801
2802 static void target_release_cmd_kref(struct kref *kref)
2803 {
2804         struct se_cmd *se_cmd = container_of(kref, struct se_cmd, cmd_kref);
2805         struct se_session *se_sess = se_cmd->se_sess;
2806         struct completion *compl = se_cmd->compl;
2807         unsigned long flags;
2808
2809         if (se_sess) {
2810                 spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2811                 list_del_init(&se_cmd->se_cmd_list);
2812                 spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2813         }
2814
2815         target_free_cmd_mem(se_cmd);
2816         se_cmd->se_tfo->release_cmd(se_cmd);
2817         if (compl)
2818                 complete(compl);
2819
2820         percpu_ref_put(&se_sess->cmd_count);
2821 }
2822
2823 /**
2824  * target_put_sess_cmd - decrease the command reference count
2825  * @se_cmd:     command to drop a reference from
2826  *
2827  * Returns 1 if and only if this target_put_sess_cmd() call caused the
2828  * refcount to drop to zero. Returns zero otherwise.
2829  */
2830 int target_put_sess_cmd(struct se_cmd *se_cmd)
2831 {
2832         return kref_put(&se_cmd->cmd_kref, target_release_cmd_kref);
2833 }
2834 EXPORT_SYMBOL(target_put_sess_cmd);
2835
2836 static const char *data_dir_name(enum dma_data_direction d)
2837 {
2838         switch (d) {
2839         case DMA_BIDIRECTIONAL: return "BIDI";
2840         case DMA_TO_DEVICE:     return "WRITE";
2841         case DMA_FROM_DEVICE:   return "READ";
2842         case DMA_NONE:          return "NONE";
2843         }
2844
2845         return "(?)";
2846 }
2847
2848 static const char *cmd_state_name(enum transport_state_table t)
2849 {
2850         switch (t) {
2851         case TRANSPORT_NO_STATE:        return "NO_STATE";
2852         case TRANSPORT_NEW_CMD:         return "NEW_CMD";
2853         case TRANSPORT_WRITE_PENDING:   return "WRITE_PENDING";
2854         case TRANSPORT_PROCESSING:      return "PROCESSING";
2855         case TRANSPORT_COMPLETE:        return "COMPLETE";
2856         case TRANSPORT_ISTATE_PROCESSING:
2857                                         return "ISTATE_PROCESSING";
2858         case TRANSPORT_COMPLETE_QF_WP:  return "COMPLETE_QF_WP";
2859         case TRANSPORT_COMPLETE_QF_OK:  return "COMPLETE_QF_OK";
2860         case TRANSPORT_COMPLETE_QF_ERR: return "COMPLETE_QF_ERR";
2861         }
2862
2863         return "(?)";
2864 }
2865
2866 static void target_append_str(char **str, const char *txt)
2867 {
2868         char *prev = *str;
2869
2870         *str = *str ? kasprintf(GFP_ATOMIC, "%s,%s", *str, txt) :
2871                 kstrdup(txt, GFP_ATOMIC);
2872         kfree(prev);
2873 }
2874
2875 /*
2876  * Convert a transport state bitmask into a string. The caller is
2877  * responsible for freeing the returned pointer.
2878  */
2879 static char *target_ts_to_str(u32 ts)
2880 {
2881         char *str = NULL;
2882
2883         if (ts & CMD_T_ABORTED)
2884                 target_append_str(&str, "aborted");
2885         if (ts & CMD_T_ACTIVE)
2886                 target_append_str(&str, "active");
2887         if (ts & CMD_T_COMPLETE)
2888                 target_append_str(&str, "complete");
2889         if (ts & CMD_T_SENT)
2890                 target_append_str(&str, "sent");
2891         if (ts & CMD_T_STOP)
2892                 target_append_str(&str, "stop");
2893         if (ts & CMD_T_FABRIC_STOP)
2894                 target_append_str(&str, "fabric_stop");
2895
2896         return str;
2897 }
2898
2899 static const char *target_tmf_name(enum tcm_tmreq_table tmf)
2900 {
2901         switch (tmf) {
2902         case TMR_ABORT_TASK:            return "ABORT_TASK";
2903         case TMR_ABORT_TASK_SET:        return "ABORT_TASK_SET";
2904         case TMR_CLEAR_ACA:             return "CLEAR_ACA";
2905         case TMR_CLEAR_TASK_SET:        return "CLEAR_TASK_SET";
2906         case TMR_LUN_RESET:             return "LUN_RESET";
2907         case TMR_TARGET_WARM_RESET:     return "TARGET_WARM_RESET";
2908         case TMR_TARGET_COLD_RESET:     return "TARGET_COLD_RESET";
2909         case TMR_UNKNOWN:               break;
2910         }
2911         return "(?)";
2912 }
2913
2914 void target_show_cmd(const char *pfx, struct se_cmd *cmd)
2915 {
2916         char *ts_str = target_ts_to_str(cmd->transport_state);
2917         const u8 *cdb = cmd->t_task_cdb;
2918         struct se_tmr_req *tmf = cmd->se_tmr_req;
2919
2920         if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
2921                 pr_debug("%scmd %#02x:%#02x with tag %#llx dir %s i_state %d t_state %s len %d refcnt %d transport_state %s\n",
2922                          pfx, cdb[0], cdb[1], cmd->tag,
2923                          data_dir_name(cmd->data_direction),
2924                          cmd->se_tfo->get_cmd_state(cmd),
2925                          cmd_state_name(cmd->t_state), cmd->data_length,
2926                          kref_read(&cmd->cmd_kref), ts_str);
2927         } else {
2928                 pr_debug("%stmf %s with tag %#llx ref_task_tag %#llx i_state %d t_state %s refcnt %d transport_state %s\n",
2929                          pfx, target_tmf_name(tmf->function), cmd->tag,
2930                          tmf->ref_task_tag, cmd->se_tfo->get_cmd_state(cmd),
2931                          cmd_state_name(cmd->t_state),
2932                          kref_read(&cmd->cmd_kref), ts_str);
2933         }
2934         kfree(ts_str);
2935 }
2936 EXPORT_SYMBOL(target_show_cmd);
2937
2938 /**
2939  * target_sess_cmd_list_set_waiting - Set sess_tearing_down so no new commands are queued.
2940  * @se_sess:    session to flag
2941  */
2942 void target_sess_cmd_list_set_waiting(struct se_session *se_sess)
2943 {
2944         unsigned long flags;
2945
2946         spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2947         se_sess->sess_tearing_down = 1;
2948         spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2949
2950         percpu_ref_kill(&se_sess->cmd_count);
2951 }
2952 EXPORT_SYMBOL(target_sess_cmd_list_set_waiting);
2953
2954 /**
2955  * target_wait_for_sess_cmds - Wait for outstanding commands
2956  * @se_sess:    session to wait for active I/O
2957  */
2958 void target_wait_for_sess_cmds(struct se_session *se_sess)
2959 {
2960         struct se_cmd *cmd;
2961         int ret;
2962
2963         WARN_ON_ONCE(!se_sess->sess_tearing_down);
2964
2965         do {
2966                 ret = wait_event_timeout(se_sess->cmd_list_wq,
2967                                 percpu_ref_is_zero(&se_sess->cmd_count),
2968                                 180 * HZ);
2969                 list_for_each_entry(cmd, &se_sess->sess_cmd_list, se_cmd_list)
2970                         target_show_cmd("session shutdown: still waiting for ",
2971                                         cmd);
2972         } while (ret <= 0);
2973 }
2974 EXPORT_SYMBOL(target_wait_for_sess_cmds);
2975
2976 static void target_lun_confirm(struct percpu_ref *ref)
2977 {
2978         struct se_lun *lun = container_of(ref, struct se_lun, lun_ref);
2979
2980         complete(&lun->lun_ref_comp);
2981 }
2982
2983 void transport_clear_lun_ref(struct se_lun *lun)
2984 {
2985         /*
2986          * Mark the percpu-ref as DEAD, switch to atomic_t mode, drop
2987          * the initial reference and schedule confirm kill to be
2988          * executed after one full RCU grace period has completed.
2989          */
2990         percpu_ref_kill_and_confirm(&lun->lun_ref, target_lun_confirm);
2991         /*
2992          * The first completion waits for percpu_ref_switch_to_atomic_rcu()
2993          * to call target_lun_confirm after lun->lun_ref has been marked
2994          * as __PERCPU_REF_DEAD on all CPUs, and switches to atomic_t
2995          * mode so that percpu_ref_tryget_live() lookup of lun->lun_ref
2996          * fails for all new incoming I/O.
2997          */
2998         wait_for_completion(&lun->lun_ref_comp);
2999         /*
3000          * The second completion waits for percpu_ref_put_many() to
3001          * invoke ->release() after lun->lun_ref has switched to
3002          * atomic_t mode, and lun->lun_ref.count has reached zero.
3003          *
3004          * At this point all target-core lun->lun_ref references have
3005          * been dropped via transport_lun_remove_cmd(), and it's safe
3006          * to proceed with the remaining LUN shutdown.
3007          */
3008         wait_for_completion(&lun->lun_shutdown_comp);
3009 }
3010
3011 static bool
3012 __transport_wait_for_tasks(struct se_cmd *cmd, bool fabric_stop,
3013                            bool *aborted, bool *tas, unsigned long *flags)
3014         __releases(&cmd->t_state_lock)
3015         __acquires(&cmd->t_state_lock)
3016 {
3017         lockdep_assert_held(&cmd->t_state_lock);
3018
3019         if (fabric_stop)
3020                 cmd->transport_state |= CMD_T_FABRIC_STOP;
3021
3022         if (cmd->transport_state & CMD_T_ABORTED)
3023                 *aborted = true;
3024
3025         if (cmd->transport_state & CMD_T_TAS)
3026                 *tas = true;
3027
3028         if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) &&
3029             !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
3030                 return false;
3031
3032         if (!(cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE) &&
3033             !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
3034                 return false;
3035
3036         if (!(cmd->transport_state & CMD_T_ACTIVE))
3037                 return false;
3038
3039         if (fabric_stop && *aborted)
3040                 return false;
3041
3042         cmd->transport_state |= CMD_T_STOP;
3043
3044         target_show_cmd("wait_for_tasks: Stopping ", cmd);
3045
3046         spin_unlock_irqrestore(&cmd->t_state_lock, *flags);
3047
3048         while (!wait_for_completion_timeout(&cmd->t_transport_stop_comp,
3049                                             180 * HZ))
3050                 target_show_cmd("wait for tasks: ", cmd);
3051
3052         spin_lock_irqsave(&cmd->t_state_lock, *flags);
3053         cmd->transport_state &= ~(CMD_T_ACTIVE | CMD_T_STOP);
3054
3055         pr_debug("wait_for_tasks: Stopped wait_for_completion(&cmd->"
3056                  "t_transport_stop_comp) for ITT: 0x%08llx\n", cmd->tag);
3057
3058         return true;
3059 }
3060
3061 /**
3062  * transport_wait_for_tasks - set CMD_T_STOP and wait for t_transport_stop_comp
3063  * @cmd: command to wait on
3064  */
3065 bool transport_wait_for_tasks(struct se_cmd *cmd)
3066 {
3067         unsigned long flags;
3068         bool ret, aborted = false, tas = false;
3069
3070         spin_lock_irqsave(&cmd->t_state_lock, flags);
3071         ret = __transport_wait_for_tasks(cmd, false, &aborted, &tas, &flags);
3072         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3073
3074         return ret;
3075 }
3076 EXPORT_SYMBOL(transport_wait_for_tasks);
3077
3078 struct sense_info {
3079         u8 key;
3080         u8 asc;
3081         u8 ascq;
3082         bool add_sector_info;
3083 };
3084
3085 static const struct sense_info sense_info_table[] = {
3086         [TCM_NO_SENSE] = {
3087                 .key = NOT_READY
3088         },
3089         [TCM_NON_EXISTENT_LUN] = {
3090                 .key = ILLEGAL_REQUEST,
3091                 .asc = 0x25 /* LOGICAL UNIT NOT SUPPORTED */
3092         },
3093         [TCM_UNSUPPORTED_SCSI_OPCODE] = {
3094                 .key = ILLEGAL_REQUEST,
3095                 .asc = 0x20, /* INVALID COMMAND OPERATION CODE */
3096         },
3097         [TCM_SECTOR_COUNT_TOO_MANY] = {
3098                 .key = ILLEGAL_REQUEST,
3099                 .asc = 0x20, /* INVALID COMMAND OPERATION CODE */
3100         },
3101         [TCM_UNKNOWN_MODE_PAGE] = {
3102                 .key = ILLEGAL_REQUEST,
3103                 .asc = 0x24, /* INVALID FIELD IN CDB */
3104         },
3105         [TCM_CHECK_CONDITION_ABORT_CMD] = {
3106                 .key = ABORTED_COMMAND,
3107                 .asc = 0x29, /* BUS DEVICE RESET FUNCTION OCCURRED */
3108                 .ascq = 0x03,
3109         },
3110         [TCM_INCORRECT_AMOUNT_OF_DATA] = {
3111                 .key = ABORTED_COMMAND,
3112                 .asc = 0x0c, /* WRITE ERROR */
3113                 .ascq = 0x0d, /* NOT ENOUGH UNSOLICITED DATA */
3114         },
3115         [TCM_INVALID_CDB_FIELD] = {
3116                 .key = ILLEGAL_REQUEST,
3117                 .asc = 0x24, /* INVALID FIELD IN CDB */
3118         },
3119         [TCM_INVALID_PARAMETER_LIST] = {
3120                 .key = ILLEGAL_REQUEST,
3121                 .asc = 0x26, /* INVALID FIELD IN PARAMETER LIST */
3122         },
3123         [TCM_TOO_MANY_TARGET_DESCS] = {
3124                 .key = ILLEGAL_REQUEST,
3125                 .asc = 0x26,
3126                 .ascq = 0x06, /* TOO MANY TARGET DESCRIPTORS */
3127         },
3128         [TCM_UNSUPPORTED_TARGET_DESC_TYPE_CODE] = {
3129                 .key = ILLEGAL_REQUEST,
3130                 .asc = 0x26,
3131                 .ascq = 0x07, /* UNSUPPORTED TARGET DESCRIPTOR TYPE CODE */
3132         },
3133         [TCM_TOO_MANY_SEGMENT_DESCS] = {
3134                 .key = ILLEGAL_REQUEST,
3135                 .asc = 0x26,
3136                 .ascq = 0x08, /* TOO MANY SEGMENT DESCRIPTORS */
3137         },
3138         [TCM_UNSUPPORTED_SEGMENT_DESC_TYPE_CODE] = {
3139                 .key = ILLEGAL_REQUEST,
3140                 .asc = 0x26,
3141                 .ascq = 0x09, /* UNSUPPORTED SEGMENT DESCRIPTOR TYPE CODE */
3142         },
3143         [TCM_PARAMETER_LIST_LENGTH_ERROR] = {
3144                 .key = ILLEGAL_REQUEST,
3145                 .asc = 0x1a, /* PARAMETER LIST LENGTH ERROR */
3146         },
3147         [TCM_UNEXPECTED_UNSOLICITED_DATA] = {
3148                 .key = ILLEGAL_REQUEST,
3149                 .asc = 0x0c, /* WRITE ERROR */
3150                 .ascq = 0x0c, /* UNEXPECTED_UNSOLICITED_DATA */
3151         },
3152         [TCM_SERVICE_CRC_ERROR] = {
3153                 .key = ABORTED_COMMAND,
3154                 .asc = 0x47, /* PROTOCOL SERVICE CRC ERROR */
3155                 .ascq = 0x05, /* N/A */
3156         },
3157         [TCM_SNACK_REJECTED] = {
3158                 .key = ABORTED_COMMAND,
3159                 .asc = 0x11, /* READ ERROR */
3160                 .ascq = 0x13, /* FAILED RETRANSMISSION REQUEST */
3161         },
3162         [TCM_WRITE_PROTECTED] = {
3163                 .key = DATA_PROTECT,
3164                 .asc = 0x27, /* WRITE PROTECTED */
3165         },
3166         [TCM_ADDRESS_OUT_OF_RANGE] = {
3167                 .key = ILLEGAL_REQUEST,
3168                 .asc = 0x21, /* LOGICAL BLOCK ADDRESS OUT OF RANGE */
3169         },
3170         [TCM_CHECK_CONDITION_UNIT_ATTENTION] = {
3171                 .key = UNIT_ATTENTION,
3172         },
3173         [TCM_CHECK_CONDITION_NOT_READY] = {
3174                 .key = NOT_READY,
3175         },
3176         [TCM_MISCOMPARE_VERIFY] = {
3177                 .key = MISCOMPARE,
3178                 .asc = 0x1d, /* MISCOMPARE DURING VERIFY OPERATION */
3179                 .ascq = 0x00,
3180         },
3181         [TCM_LOGICAL_BLOCK_GUARD_CHECK_FAILED] = {
3182                 .key = ABORTED_COMMAND,
3183                 .asc = 0x10,
3184                 .ascq = 0x01, /* LOGICAL BLOCK GUARD CHECK FAILED */
3185                 .add_sector_info = true,
3186         },
3187         [TCM_LOGICAL_BLOCK_APP_TAG_CHECK_FAILED] = {
3188                 .key = ABORTED_COMMAND,
3189                 .asc = 0x10,
3190                 .ascq = 0x02, /* LOGICAL BLOCK APPLICATION TAG CHECK FAILED */
3191                 .add_sector_info = true,
3192         },
3193         [TCM_LOGICAL_BLOCK_REF_TAG_CHECK_FAILED] = {
3194                 .key = ABORTED_COMMAND,
3195                 .asc = 0x10,
3196                 .ascq = 0x03, /* LOGICAL BLOCK REFERENCE TAG CHECK FAILED */
3197                 .add_sector_info = true,
3198         },
3199         [TCM_COPY_TARGET_DEVICE_NOT_REACHABLE] = {
3200                 .key = COPY_ABORTED,
3201                 .asc = 0x0d,
3202                 .ascq = 0x02, /* COPY TARGET DEVICE NOT REACHABLE */
3203
3204         },
3205         [TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE] = {
3206                 /*
3207                  * Returning ILLEGAL REQUEST would cause immediate IO errors on
3208                  * Solaris initiators.  Returning NOT READY instead means the
3209                  * operations will be retried a finite number of times and we
3210                  * can survive intermittent errors.
3211                  */
3212                 .key = NOT_READY,
3213                 .asc = 0x08, /* LOGICAL UNIT COMMUNICATION FAILURE */
3214         },
3215         [TCM_INSUFFICIENT_REGISTRATION_RESOURCES] = {
3216                 /*
3217                  * From spc4r22 section5.7.7,5.7.8
3218                  * If a PERSISTENT RESERVE OUT command with a REGISTER service action
3219                  * or a REGISTER AND IGNORE EXISTING KEY service action or
3220                  * REGISTER AND MOVE service actionis attempted,
3221                  * but there are insufficient device server resources to complete the
3222                  * operation, then the command shall be terminated with CHECK CONDITION
3223                  * status, with the sense key set to ILLEGAL REQUEST,and the additonal
3224                  * sense code set to INSUFFICIENT REGISTRATION RESOURCES.
3225                  */
3226                 .key = ILLEGAL_REQUEST,
3227                 .asc = 0x55,
3228                 .ascq = 0x04, /* INSUFFICIENT REGISTRATION RESOURCES */
3229         },
3230 };
3231
3232 /**
3233  * translate_sense_reason - translate a sense reason into T10 key, asc and ascq
3234  * @cmd: SCSI command in which the resulting sense buffer or SCSI status will
3235  *   be stored.
3236  * @reason: LIO sense reason code. If this argument has the value
3237  *   TCM_CHECK_CONDITION_UNIT_ATTENTION, try to dequeue a unit attention. If
3238  *   dequeuing a unit attention fails due to multiple commands being processed
3239  *   concurrently, set the command status to BUSY.
3240  *
3241  * Return: 0 upon success or -EINVAL if the sense buffer is too small.
3242  */
3243 static void translate_sense_reason(struct se_cmd *cmd, sense_reason_t reason)
3244 {
3245         const struct sense_info *si;
3246         u8 *buffer = cmd->sense_buffer;
3247         int r = (__force int)reason;
3248         u8 key, asc, ascq;
3249         bool desc_format = target_sense_desc_format(cmd->se_dev);
3250
3251         if (r < ARRAY_SIZE(sense_info_table) && sense_info_table[r].key)
3252                 si = &sense_info_table[r];
3253         else
3254                 si = &sense_info_table[(__force int)
3255                                        TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE];
3256
3257         key = si->key;
3258         if (reason == TCM_CHECK_CONDITION_UNIT_ATTENTION) {
3259                 if (!core_scsi3_ua_for_check_condition(cmd, &key, &asc,
3260                                                        &ascq)) {
3261                         cmd->scsi_status = SAM_STAT_BUSY;
3262                         return;
3263                 }
3264         } else if (si->asc == 0) {
3265                 WARN_ON_ONCE(cmd->scsi_asc == 0);
3266                 asc = cmd->scsi_asc;
3267                 ascq = cmd->scsi_ascq;
3268         } else {
3269                 asc = si->asc;
3270                 ascq = si->ascq;
3271         }
3272
3273         cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
3274         cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
3275         cmd->scsi_sense_length  = TRANSPORT_SENSE_BUFFER;
3276         scsi_build_sense_buffer(desc_format, buffer, key, asc, ascq);
3277         if (si->add_sector_info)
3278                 WARN_ON_ONCE(scsi_set_sense_information(buffer,
3279                                                         cmd->scsi_sense_length,
3280                                                         cmd->bad_sector) < 0);
3281 }
3282
3283 int
3284 transport_send_check_condition_and_sense(struct se_cmd *cmd,
3285                 sense_reason_t reason, int from_transport)
3286 {
3287         unsigned long flags;
3288
3289         spin_lock_irqsave(&cmd->t_state_lock, flags);
3290         if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
3291                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3292                 return 0;
3293         }
3294         cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
3295         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3296
3297         if (!from_transport)
3298                 translate_sense_reason(cmd, reason);
3299
3300         trace_target_cmd_complete(cmd);
3301         return cmd->se_tfo->queue_status(cmd);
3302 }
3303 EXPORT_SYMBOL(transport_send_check_condition_and_sense);
3304
3305 static int __transport_check_aborted_status(struct se_cmd *cmd, int send_status)
3306         __releases(&cmd->t_state_lock)
3307         __acquires(&cmd->t_state_lock)
3308 {
3309         int ret;
3310
3311         assert_spin_locked(&cmd->t_state_lock);
3312         WARN_ON_ONCE(!irqs_disabled());
3313
3314         if (!(cmd->transport_state & CMD_T_ABORTED))
3315                 return 0;
3316         /*
3317          * If cmd has been aborted but either no status is to be sent or it has
3318          * already been sent, just return
3319          */
3320         if (!send_status || !(cmd->se_cmd_flags & SCF_SEND_DELAYED_TAS)) {
3321                 if (send_status)
3322                         cmd->se_cmd_flags |= SCF_SEND_DELAYED_TAS;
3323                 return 1;
3324         }
3325
3326         pr_debug("Sending delayed SAM_STAT_TASK_ABORTED status for CDB:"
3327                 " 0x%02x ITT: 0x%08llx\n", cmd->t_task_cdb[0], cmd->tag);
3328
3329         cmd->se_cmd_flags &= ~SCF_SEND_DELAYED_TAS;
3330         cmd->scsi_status = SAM_STAT_TASK_ABORTED;
3331         trace_target_cmd_complete(cmd);
3332
3333         spin_unlock_irq(&cmd->t_state_lock);
3334         ret = cmd->se_tfo->queue_status(cmd);
3335         if (ret)
3336                 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
3337         spin_lock_irq(&cmd->t_state_lock);
3338
3339         return 1;
3340 }
3341
3342 int transport_check_aborted_status(struct se_cmd *cmd, int send_status)
3343 {
3344         int ret;
3345
3346         spin_lock_irq(&cmd->t_state_lock);
3347         ret = __transport_check_aborted_status(cmd, send_status);
3348         spin_unlock_irq(&cmd->t_state_lock);
3349
3350         return ret;
3351 }
3352 EXPORT_SYMBOL(transport_check_aborted_status);
3353
3354 void transport_send_task_abort(struct se_cmd *cmd)
3355 {
3356         unsigned long flags;
3357         int ret;
3358
3359         spin_lock_irqsave(&cmd->t_state_lock, flags);
3360         if (cmd->se_cmd_flags & (SCF_SENT_CHECK_CONDITION)) {
3361                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3362                 return;
3363         }
3364         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3365
3366         /*
3367          * If there are still expected incoming fabric WRITEs, we wait
3368          * until until they have completed before sending a TASK_ABORTED
3369          * response.  This response with TASK_ABORTED status will be
3370          * queued back to fabric module by transport_check_aborted_status().
3371          */
3372         if (cmd->data_direction == DMA_TO_DEVICE) {
3373                 if (cmd->se_tfo->write_pending_status(cmd) != 0) {
3374                         spin_lock_irqsave(&cmd->t_state_lock, flags);
3375                         if (cmd->se_cmd_flags & SCF_SEND_DELAYED_TAS) {
3376                                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3377                                 goto send_abort;
3378                         }
3379                         cmd->se_cmd_flags |= SCF_SEND_DELAYED_TAS;
3380                         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3381                         return;
3382                 }
3383         }
3384 send_abort:
3385         cmd->scsi_status = SAM_STAT_TASK_ABORTED;
3386
3387         transport_lun_remove_cmd(cmd);
3388
3389         pr_debug("Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x, ITT: 0x%08llx\n",
3390                  cmd->t_task_cdb[0], cmd->tag);
3391
3392         trace_target_cmd_complete(cmd);
3393         ret = cmd->se_tfo->queue_status(cmd);
3394         if (ret)
3395                 transport_handle_queue_full(cmd, cmd->se_dev, ret, false);
3396 }
3397
3398 static void target_tmr_work(struct work_struct *work)
3399 {
3400         struct se_cmd *cmd = container_of(work, struct se_cmd, work);
3401         struct se_device *dev = cmd->se_dev;
3402         struct se_tmr_req *tmr = cmd->se_tmr_req;
3403         unsigned long flags;
3404         int ret;
3405
3406         spin_lock_irqsave(&cmd->t_state_lock, flags);
3407         if (cmd->transport_state & CMD_T_ABORTED) {
3408                 tmr->response = TMR_FUNCTION_REJECTED;
3409                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3410                 goto check_stop;
3411         }
3412         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3413
3414         switch (tmr->function) {
3415         case TMR_ABORT_TASK:
3416                 core_tmr_abort_task(dev, tmr, cmd->se_sess);
3417                 break;
3418         case TMR_ABORT_TASK_SET:
3419         case TMR_CLEAR_ACA:
3420         case TMR_CLEAR_TASK_SET:
3421                 tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
3422                 break;
3423         case TMR_LUN_RESET:
3424                 ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
3425                 tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
3426                                          TMR_FUNCTION_REJECTED;
3427                 if (tmr->response == TMR_FUNCTION_COMPLETE) {
3428                         target_ua_allocate_lun(cmd->se_sess->se_node_acl,
3429                                                cmd->orig_fe_lun, 0x29,
3430                                                ASCQ_29H_BUS_DEVICE_RESET_FUNCTION_OCCURRED);
3431                 }
3432                 break;
3433         case TMR_TARGET_WARM_RESET:
3434                 tmr->response = TMR_FUNCTION_REJECTED;
3435                 break;
3436         case TMR_TARGET_COLD_RESET:
3437                 tmr->response = TMR_FUNCTION_REJECTED;
3438                 break;
3439         default:
3440                 pr_err("Unknown TMR function: 0x%02x.\n",
3441                                 tmr->function);
3442                 tmr->response = TMR_FUNCTION_REJECTED;
3443                 break;
3444         }
3445
3446         spin_lock_irqsave(&cmd->t_state_lock, flags);
3447         if (cmd->transport_state & CMD_T_ABORTED) {
3448                 spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3449                 goto check_stop;
3450         }
3451         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3452
3453         cmd->se_tfo->queue_tm_rsp(cmd);
3454
3455 check_stop:
3456         transport_lun_remove_cmd(cmd);
3457         transport_cmd_check_stop_to_fabric(cmd);
3458 }
3459
3460 int transport_generic_handle_tmr(
3461         struct se_cmd *cmd)
3462 {
3463         unsigned long flags;
3464         bool aborted = false;
3465
3466         spin_lock_irqsave(&cmd->t_state_lock, flags);
3467         if (cmd->transport_state & CMD_T_ABORTED) {
3468                 aborted = true;
3469         } else {
3470                 cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
3471                 cmd->transport_state |= CMD_T_ACTIVE;
3472         }
3473         spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3474
3475         if (aborted) {
3476                 pr_warn_ratelimited("handle_tmr caught CMD_T_ABORTED TMR %d"
3477                         "ref_tag: %llu tag: %llu\n", cmd->se_tmr_req->function,
3478                         cmd->se_tmr_req->ref_task_tag, cmd->tag);
3479                 transport_lun_remove_cmd(cmd);
3480                 transport_cmd_check_stop_to_fabric(cmd);
3481                 return 0;
3482         }
3483
3484         INIT_WORK(&cmd->work, target_tmr_work);
3485         queue_work(cmd->se_dev->tmr_wq, &cmd->work);
3486         return 0;
3487 }
3488 EXPORT_SYMBOL(transport_generic_handle_tmr);
3489
3490 bool
3491 target_check_wce(struct se_device *dev)
3492 {
3493         bool wce = false;
3494
3495         if (dev->transport->get_write_cache)
3496                 wce = dev->transport->get_write_cache(dev);
3497         else if (dev->dev_attrib.emulate_write_cache > 0)
3498                 wce = true;
3499
3500         return wce;
3501 }
3502
3503 bool
3504 target_check_fua(struct se_device *dev)
3505 {
3506         return target_check_wce(dev) && dev->dev_attrib.emulate_fua_write > 0;
3507 }