GNU Linux-libre 4.19.295-gnu1
[releases.git] / drivers / scsi / libiscsi.c
1 /*
2  * iSCSI lib functions
3  *
4  * Copyright (C) 2006 Red Hat, Inc.  All rights reserved.
5  * Copyright (C) 2004 - 2006 Mike Christie
6  * Copyright (C) 2004 - 2005 Dmitry Yusupov
7  * Copyright (C) 2004 - 2005 Alex Aizman
8  * maintained by open-iscsi@googlegroups.com
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 #include <linux/types.h>
25 #include <linux/kfifo.h>
26 #include <linux/delay.h>
27 #include <linux/log2.h>
28 #include <linux/slab.h>
29 #include <linux/sched/signal.h>
30 #include <linux/module.h>
31 #include <asm/unaligned.h>
32 #include <net/tcp.h>
33 #include <scsi/scsi_cmnd.h>
34 #include <scsi/scsi_device.h>
35 #include <scsi/scsi_eh.h>
36 #include <scsi/scsi_tcq.h>
37 #include <scsi/scsi_host.h>
38 #include <scsi/scsi.h>
39 #include <scsi/iscsi_proto.h>
40 #include <scsi/scsi_transport.h>
41 #include <scsi/scsi_transport_iscsi.h>
42 #include <scsi/libiscsi.h>
43
44 static int iscsi_dbg_lib_conn;
45 module_param_named(debug_libiscsi_conn, iscsi_dbg_lib_conn, int,
46                    S_IRUGO | S_IWUSR);
47 MODULE_PARM_DESC(debug_libiscsi_conn,
48                  "Turn on debugging for connections in libiscsi module. "
49                  "Set to 1 to turn on, and zero to turn off. Default is off.");
50
51 static int iscsi_dbg_lib_session;
52 module_param_named(debug_libiscsi_session, iscsi_dbg_lib_session, int,
53                    S_IRUGO | S_IWUSR);
54 MODULE_PARM_DESC(debug_libiscsi_session,
55                  "Turn on debugging for sessions in libiscsi module. "
56                  "Set to 1 to turn on, and zero to turn off. Default is off.");
57
58 static int iscsi_dbg_lib_eh;
59 module_param_named(debug_libiscsi_eh, iscsi_dbg_lib_eh, int,
60                    S_IRUGO | S_IWUSR);
61 MODULE_PARM_DESC(debug_libiscsi_eh,
62                  "Turn on debugging for error handling in libiscsi module. "
63                  "Set to 1 to turn on, and zero to turn off. Default is off.");
64
65 #define ISCSI_DBG_CONN(_conn, dbg_fmt, arg...)                  \
66         do {                                                    \
67                 if (iscsi_dbg_lib_conn)                         \
68                         iscsi_conn_printk(KERN_INFO, _conn,     \
69                                              "%s " dbg_fmt,     \
70                                              __func__, ##arg);  \
71         } while (0);
72
73 #define ISCSI_DBG_SESSION(_session, dbg_fmt, arg...)                    \
74         do {                                                            \
75                 if (iscsi_dbg_lib_session)                              \
76                         iscsi_session_printk(KERN_INFO, _session,       \
77                                              "%s " dbg_fmt,             \
78                                              __func__, ##arg);          \
79         } while (0);
80
81 #define ISCSI_DBG_EH(_session, dbg_fmt, arg...)                         \
82         do {                                                            \
83                 if (iscsi_dbg_lib_eh)                                   \
84                         iscsi_session_printk(KERN_INFO, _session,       \
85                                              "%s " dbg_fmt,             \
86                                              __func__, ##arg);          \
87         } while (0);
88
89 inline void iscsi_conn_queue_work(struct iscsi_conn *conn)
90 {
91         struct Scsi_Host *shost = conn->session->host;
92         struct iscsi_host *ihost = shost_priv(shost);
93
94         if (ihost->workq)
95                 queue_work(ihost->workq, &conn->xmitwork);
96 }
97 EXPORT_SYMBOL_GPL(iscsi_conn_queue_work);
98
99 static void __iscsi_update_cmdsn(struct iscsi_session *session,
100                                  uint32_t exp_cmdsn, uint32_t max_cmdsn)
101 {
102         /*
103          * standard specifies this check for when to update expected and
104          * max sequence numbers
105          */
106         if (iscsi_sna_lt(max_cmdsn, exp_cmdsn - 1))
107                 return;
108
109         if (exp_cmdsn != session->exp_cmdsn &&
110             !iscsi_sna_lt(exp_cmdsn, session->exp_cmdsn))
111                 session->exp_cmdsn = exp_cmdsn;
112
113         if (max_cmdsn != session->max_cmdsn &&
114             !iscsi_sna_lt(max_cmdsn, session->max_cmdsn))
115                 session->max_cmdsn = max_cmdsn;
116 }
117
118 void iscsi_update_cmdsn(struct iscsi_session *session, struct iscsi_nopin *hdr)
119 {
120         __iscsi_update_cmdsn(session, be32_to_cpu(hdr->exp_cmdsn),
121                              be32_to_cpu(hdr->max_cmdsn));
122 }
123 EXPORT_SYMBOL_GPL(iscsi_update_cmdsn);
124
125 /**
126  * iscsi_prep_data_out_pdu - initialize Data-Out
127  * @task: scsi command task
128  * @r2t: R2T info
129  * @hdr: iscsi data in pdu
130  *
131  * Notes:
132  *      Initialize Data-Out within this R2T sequence and finds
133  *      proper data_offset within this SCSI command.
134  *
135  *      This function is called with connection lock taken.
136  **/
137 void iscsi_prep_data_out_pdu(struct iscsi_task *task, struct iscsi_r2t_info *r2t,
138                            struct iscsi_data *hdr)
139 {
140         struct iscsi_conn *conn = task->conn;
141         unsigned int left = r2t->data_length - r2t->sent;
142
143         task->hdr_len = sizeof(struct iscsi_data);
144
145         memset(hdr, 0, sizeof(struct iscsi_data));
146         hdr->ttt = r2t->ttt;
147         hdr->datasn = cpu_to_be32(r2t->datasn);
148         r2t->datasn++;
149         hdr->opcode = ISCSI_OP_SCSI_DATA_OUT;
150         hdr->lun = task->lun;
151         hdr->itt = task->hdr_itt;
152         hdr->exp_statsn = r2t->exp_statsn;
153         hdr->offset = cpu_to_be32(r2t->data_offset + r2t->sent);
154         if (left > conn->max_xmit_dlength) {
155                 hton24(hdr->dlength, conn->max_xmit_dlength);
156                 r2t->data_count = conn->max_xmit_dlength;
157                 hdr->flags = 0;
158         } else {
159                 hton24(hdr->dlength, left);
160                 r2t->data_count = left;
161                 hdr->flags = ISCSI_FLAG_CMD_FINAL;
162         }
163         conn->dataout_pdus_cnt++;
164 }
165 EXPORT_SYMBOL_GPL(iscsi_prep_data_out_pdu);
166
167 static int iscsi_add_hdr(struct iscsi_task *task, unsigned len)
168 {
169         unsigned exp_len = task->hdr_len + len;
170
171         if (exp_len > task->hdr_max) {
172                 WARN_ON(1);
173                 return -EINVAL;
174         }
175
176         WARN_ON(len & (ISCSI_PAD_LEN - 1)); /* caller must pad the AHS */
177         task->hdr_len = exp_len;
178         return 0;
179 }
180
181 /*
182  * make an extended cdb AHS
183  */
184 static int iscsi_prep_ecdb_ahs(struct iscsi_task *task)
185 {
186         struct scsi_cmnd *cmd = task->sc;
187         unsigned rlen, pad_len;
188         unsigned short ahslength;
189         struct iscsi_ecdb_ahdr *ecdb_ahdr;
190         int rc;
191
192         ecdb_ahdr = iscsi_next_hdr(task);
193         rlen = cmd->cmd_len - ISCSI_CDB_SIZE;
194
195         BUG_ON(rlen > sizeof(ecdb_ahdr->ecdb));
196         ahslength = rlen + sizeof(ecdb_ahdr->reserved);
197
198         pad_len = iscsi_padding(rlen);
199
200         rc = iscsi_add_hdr(task, sizeof(ecdb_ahdr->ahslength) +
201                            sizeof(ecdb_ahdr->ahstype) + ahslength + pad_len);
202         if (rc)
203                 return rc;
204
205         if (pad_len)
206                 memset(&ecdb_ahdr->ecdb[rlen], 0, pad_len);
207
208         ecdb_ahdr->ahslength = cpu_to_be16(ahslength);
209         ecdb_ahdr->ahstype = ISCSI_AHSTYPE_CDB;
210         ecdb_ahdr->reserved = 0;
211         memcpy(ecdb_ahdr->ecdb, cmd->cmnd + ISCSI_CDB_SIZE, rlen);
212
213         ISCSI_DBG_SESSION(task->conn->session,
214                           "iscsi_prep_ecdb_ahs: varlen_cdb_len %d "
215                           "rlen %d pad_len %d ahs_length %d iscsi_headers_size "
216                           "%u\n", cmd->cmd_len, rlen, pad_len, ahslength,
217                           task->hdr_len);
218         return 0;
219 }
220
221 static int iscsi_prep_bidi_ahs(struct iscsi_task *task)
222 {
223         struct scsi_cmnd *sc = task->sc;
224         struct iscsi_rlength_ahdr *rlen_ahdr;
225         int rc;
226
227         rlen_ahdr = iscsi_next_hdr(task);
228         rc = iscsi_add_hdr(task, sizeof(*rlen_ahdr));
229         if (rc)
230                 return rc;
231
232         rlen_ahdr->ahslength =
233                 cpu_to_be16(sizeof(rlen_ahdr->read_length) +
234                                                   sizeof(rlen_ahdr->reserved));
235         rlen_ahdr->ahstype = ISCSI_AHSTYPE_RLENGTH;
236         rlen_ahdr->reserved = 0;
237         rlen_ahdr->read_length = cpu_to_be32(scsi_in(sc)->length);
238
239         ISCSI_DBG_SESSION(task->conn->session,
240                           "bidi-in rlen_ahdr->read_length(%d) "
241                           "rlen_ahdr->ahslength(%d)\n",
242                           be32_to_cpu(rlen_ahdr->read_length),
243                           be16_to_cpu(rlen_ahdr->ahslength));
244         return 0;
245 }
246
247 /**
248  * iscsi_check_tmf_restrictions - check if a task is affected by TMF
249  * @task: iscsi task
250  * @opcode: opcode to check for
251  *
252  * During TMF a task has to be checked if it's affected.
253  * All unrelated I/O can be passed through, but I/O to the
254  * affected LUN should be restricted.
255  * If 'fast_abort' is set we won't be sending any I/O to the
256  * affected LUN.
257  * Otherwise the target is waiting for all TTTs to be completed,
258  * so we have to send all outstanding Data-Out PDUs to the target.
259  */
260 static int iscsi_check_tmf_restrictions(struct iscsi_task *task, int opcode)
261 {
262         struct iscsi_session *session = task->conn->session;
263         struct iscsi_tm *tmf = &session->tmhdr;
264         u64 hdr_lun;
265
266         if (session->tmf_state == TMF_INITIAL)
267                 return 0;
268
269         if ((tmf->opcode & ISCSI_OPCODE_MASK) != ISCSI_OP_SCSI_TMFUNC)
270                 return 0;
271
272         switch (ISCSI_TM_FUNC_VALUE(tmf)) {
273         case ISCSI_TM_FUNC_LOGICAL_UNIT_RESET:
274                 /*
275                  * Allow PDUs for unrelated LUNs
276                  */
277                 hdr_lun = scsilun_to_int(&tmf->lun);
278                 if (hdr_lun != task->sc->device->lun)
279                         return 0;
280                 /* fall through */
281         case ISCSI_TM_FUNC_TARGET_WARM_RESET:
282                 /*
283                  * Fail all SCSI cmd PDUs
284                  */
285                 if (opcode != ISCSI_OP_SCSI_DATA_OUT) {
286                         iscsi_session_printk(KERN_INFO, session,
287                                              "task [op %x itt 0x%x/0x%x] rejected.\n",
288                                              opcode, task->itt, task->hdr_itt);
289                         return -EACCES;
290                 }
291                 /*
292                  * And also all data-out PDUs in response to R2T
293                  * if fast_abort is set.
294                  */
295                 if (session->fast_abort) {
296                         iscsi_session_printk(KERN_INFO, session,
297                                              "task [op %x itt 0x%x/0x%x] fast abort.\n",
298                                              opcode, task->itt, task->hdr_itt);
299                         return -EACCES;
300                 }
301                 break;
302         case ISCSI_TM_FUNC_ABORT_TASK:
303                 /*
304                  * the caller has already checked if the task
305                  * they want to abort was in the pending queue so if
306                  * we are here the cmd pdu has gone out already, and
307                  * we will only hit this for data-outs
308                  */
309                 if (opcode == ISCSI_OP_SCSI_DATA_OUT &&
310                     task->hdr_itt == tmf->rtt) {
311                         ISCSI_DBG_SESSION(session,
312                                           "Preventing task %x/%x from sending "
313                                           "data-out due to abort task in "
314                                           "progress\n", task->itt,
315                                           task->hdr_itt);
316                         return -EACCES;
317                 }
318                 break;
319         }
320
321         return 0;
322 }
323
324 /**
325  * iscsi_prep_scsi_cmd_pdu - prep iscsi scsi cmd pdu
326  * @task: iscsi task
327  *
328  * Prep basic iSCSI PDU fields for a scsi cmd pdu. The LLD should set
329  * fields like dlength or final based on how much data it sends
330  */
331 static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task)
332 {
333         struct iscsi_conn *conn = task->conn;
334         struct iscsi_session *session = conn->session;
335         struct scsi_cmnd *sc = task->sc;
336         struct iscsi_scsi_req *hdr;
337         unsigned hdrlength, cmd_len, transfer_length;
338         itt_t itt;
339         int rc;
340
341         rc = iscsi_check_tmf_restrictions(task, ISCSI_OP_SCSI_CMD);
342         if (rc)
343                 return rc;
344
345         if (conn->session->tt->alloc_pdu) {
346                 rc = conn->session->tt->alloc_pdu(task, ISCSI_OP_SCSI_CMD);
347                 if (rc)
348                         return rc;
349         }
350         hdr = (struct iscsi_scsi_req *)task->hdr;
351         itt = hdr->itt;
352         memset(hdr, 0, sizeof(*hdr));
353
354         if (session->tt->parse_pdu_itt)
355                 hdr->itt = task->hdr_itt = itt;
356         else
357                 hdr->itt = task->hdr_itt = build_itt(task->itt,
358                                                      task->conn->session->age);
359         task->hdr_len = 0;
360         rc = iscsi_add_hdr(task, sizeof(*hdr));
361         if (rc)
362                 return rc;
363         hdr->opcode = ISCSI_OP_SCSI_CMD;
364         hdr->flags = ISCSI_ATTR_SIMPLE;
365         int_to_scsilun(sc->device->lun, &hdr->lun);
366         task->lun = hdr->lun;
367         hdr->exp_statsn = cpu_to_be32(conn->exp_statsn);
368         cmd_len = sc->cmd_len;
369         if (cmd_len < ISCSI_CDB_SIZE)
370                 memset(&hdr->cdb[cmd_len], 0, ISCSI_CDB_SIZE - cmd_len);
371         else if (cmd_len > ISCSI_CDB_SIZE) {
372                 rc = iscsi_prep_ecdb_ahs(task);
373                 if (rc)
374                         return rc;
375                 cmd_len = ISCSI_CDB_SIZE;
376         }
377         memcpy(hdr->cdb, sc->cmnd, cmd_len);
378
379         task->imm_count = 0;
380         if (scsi_bidi_cmnd(sc)) {
381                 hdr->flags |= ISCSI_FLAG_CMD_READ;
382                 rc = iscsi_prep_bidi_ahs(task);
383                 if (rc)
384                         return rc;
385         }
386
387         if (scsi_get_prot_op(sc) != SCSI_PROT_NORMAL)
388                 task->protected = true;
389
390         transfer_length = scsi_transfer_length(sc);
391         hdr->data_length = cpu_to_be32(transfer_length);
392         if (sc->sc_data_direction == DMA_TO_DEVICE) {
393                 struct iscsi_r2t_info *r2t = &task->unsol_r2t;
394
395                 hdr->flags |= ISCSI_FLAG_CMD_WRITE;
396                 /*
397                  * Write counters:
398                  *
399                  *      imm_count       bytes to be sent right after
400                  *                      SCSI PDU Header
401                  *
402                  *      unsol_count     bytes(as Data-Out) to be sent
403                  *                      without R2T ack right after
404                  *                      immediate data
405                  *
406                  *      r2t data_length bytes to be sent via R2T ack's
407                  *
408                  *      pad_count       bytes to be sent as zero-padding
409                  */
410                 memset(r2t, 0, sizeof(*r2t));
411
412                 if (session->imm_data_en) {
413                         if (transfer_length >= session->first_burst)
414                                 task->imm_count = min(session->first_burst,
415                                                         conn->max_xmit_dlength);
416                         else
417                                 task->imm_count = min(transfer_length,
418                                                       conn->max_xmit_dlength);
419                         hton24(hdr->dlength, task->imm_count);
420                 } else
421                         zero_data(hdr->dlength);
422
423                 if (!session->initial_r2t_en) {
424                         r2t->data_length = min(session->first_burst,
425                                                transfer_length) -
426                                                task->imm_count;
427                         r2t->data_offset = task->imm_count;
428                         r2t->ttt = cpu_to_be32(ISCSI_RESERVED_TAG);
429                         r2t->exp_statsn = cpu_to_be32(conn->exp_statsn);
430                 }
431
432                 if (!task->unsol_r2t.data_length)
433                         /* No unsolicit Data-Out's */
434                         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
435         } else {
436                 hdr->flags |= ISCSI_FLAG_CMD_FINAL;
437                 zero_data(hdr->dlength);
438
439                 if (sc->sc_data_direction == DMA_FROM_DEVICE)
440                         hdr->flags |= ISCSI_FLAG_CMD_READ;
441         }
442
443         /* calculate size of additional header segments (AHSs) */
444         hdrlength = task->hdr_len - sizeof(*hdr);
445
446         WARN_ON(hdrlength & (ISCSI_PAD_LEN-1));
447         hdrlength /= ISCSI_PAD_LEN;
448
449         WARN_ON(hdrlength >= 256);
450         hdr->hlength = hdrlength & 0xFF;
451         hdr->cmdsn = task->cmdsn = cpu_to_be32(session->cmdsn);
452
453         if (session->tt->init_task && session->tt->init_task(task))
454                 return -EIO;
455
456         task->state = ISCSI_TASK_RUNNING;
457         session->cmdsn++;
458
459         conn->scsicmd_pdus_cnt++;
460         ISCSI_DBG_SESSION(session, "iscsi prep [%s cid %d sc %p cdb 0x%x "
461                           "itt 0x%x len %d bidi_len %d cmdsn %d win %d]\n",
462                           scsi_bidi_cmnd(sc) ? "bidirectional" :
463                           sc->sc_data_direction == DMA_TO_DEVICE ?
464                           "write" : "read", conn->id, sc, sc->cmnd[0],
465                           task->itt, transfer_length,
466                           scsi_bidi_cmnd(sc) ? scsi_in(sc)->length : 0,
467                           session->cmdsn,
468                           session->max_cmdsn - session->exp_cmdsn + 1);
469         return 0;
470 }
471
472 /**
473  * iscsi_free_task - free a task
474  * @task: iscsi cmd task
475  *
476  * Must be called with session back_lock.
477  * This function returns the scsi command to scsi-ml or cleans
478  * up mgmt tasks then returns the task to the pool.
479  */
480 static void iscsi_free_task(struct iscsi_task *task)
481 {
482         struct iscsi_conn *conn = task->conn;
483         struct iscsi_session *session = conn->session;
484         struct scsi_cmnd *sc = task->sc;
485         int oldstate = task->state;
486
487         ISCSI_DBG_SESSION(session, "freeing task itt 0x%x state %d sc %p\n",
488                           task->itt, task->state, task->sc);
489
490         session->tt->cleanup_task(task);
491         task->state = ISCSI_TASK_FREE;
492         task->sc = NULL;
493         /*
494          * login task is preallocated so do not free
495          */
496         if (conn->login_task == task)
497                 return;
498
499         kfifo_in(&session->cmdpool.queue, (void*)&task, sizeof(void*));
500
501         if (sc) {
502                 /* SCSI eh reuses commands to verify us */
503                 sc->SCp.ptr = NULL;
504                 /*
505                  * queue command may call this to free the task, so
506                  * it will decide how to return sc to scsi-ml.
507                  */
508                 if (oldstate != ISCSI_TASK_REQUEUE_SCSIQ)
509                         sc->scsi_done(sc);
510         }
511 }
512
513 void __iscsi_get_task(struct iscsi_task *task)
514 {
515         refcount_inc(&task->refcount);
516 }
517 EXPORT_SYMBOL_GPL(__iscsi_get_task);
518
519 void __iscsi_put_task(struct iscsi_task *task)
520 {
521         if (refcount_dec_and_test(&task->refcount))
522                 iscsi_free_task(task);
523 }
524 EXPORT_SYMBOL_GPL(__iscsi_put_task);
525
526 void iscsi_put_task(struct iscsi_task *task)
527 {
528         struct iscsi_session *session = task->conn->session;
529
530         /* regular RX path uses back_lock */
531         spin_lock_bh(&session->back_lock);
532         __iscsi_put_task(task);
533         spin_unlock_bh(&session->back_lock);
534 }
535 EXPORT_SYMBOL_GPL(iscsi_put_task);
536
537 /**
538  * iscsi_complete_task - finish a task
539  * @task: iscsi cmd task
540  * @state: state to complete task with
541  *
542  * Must be called with session back_lock.
543  */
544 static void iscsi_complete_task(struct iscsi_task *task, int state)
545 {
546         struct iscsi_conn *conn = task->conn;
547
548         ISCSI_DBG_SESSION(conn->session,
549                           "complete task itt 0x%x state %d sc %p\n",
550                           task->itt, task->state, task->sc);
551         if (task->state == ISCSI_TASK_COMPLETED ||
552             task->state == ISCSI_TASK_ABRT_TMF ||
553             task->state == ISCSI_TASK_ABRT_SESS_RECOV ||
554             task->state == ISCSI_TASK_REQUEUE_SCSIQ)
555                 return;
556         WARN_ON_ONCE(task->state == ISCSI_TASK_FREE);
557         task->state = state;
558
559         spin_lock_bh(&conn->taskqueuelock);
560         if (!list_empty(&task->running)) {
561                 pr_debug_once("%s while task on list", __func__);
562                 list_del_init(&task->running);
563         }
564         spin_unlock_bh(&conn->taskqueuelock);
565
566         if (conn->task == task)
567                 conn->task = NULL;
568
569         if (READ_ONCE(conn->ping_task) == task)
570                 WRITE_ONCE(conn->ping_task, NULL);
571
572         /* release get from queueing */
573         __iscsi_put_task(task);
574 }
575
576 /**
577  * iscsi_complete_scsi_task - finish scsi task normally
578  * @task: iscsi task for scsi cmd
579  * @exp_cmdsn: expected cmd sn in cpu format
580  * @max_cmdsn: max cmd sn in cpu format
581  *
582  * This is used when drivers do not need or cannot perform
583  * lower level pdu processing.
584  *
585  * Called with session back_lock
586  */
587 void iscsi_complete_scsi_task(struct iscsi_task *task,
588                               uint32_t exp_cmdsn, uint32_t max_cmdsn)
589 {
590         struct iscsi_conn *conn = task->conn;
591
592         ISCSI_DBG_SESSION(conn->session, "[itt 0x%x]\n", task->itt);
593
594         conn->last_recv = jiffies;
595         __iscsi_update_cmdsn(conn->session, exp_cmdsn, max_cmdsn);
596         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
597 }
598 EXPORT_SYMBOL_GPL(iscsi_complete_scsi_task);
599
600
601 /*
602  * session back_lock must be held and if not called for a task that is
603  * still pending or from the xmit thread, then xmit thread must
604  * be suspended.
605  */
606 static void fail_scsi_task(struct iscsi_task *task, int err)
607 {
608         struct iscsi_conn *conn = task->conn;
609         struct scsi_cmnd *sc;
610         int state;
611
612         /*
613          * if a command completes and we get a successful tmf response
614          * we will hit this because the scsi eh abort code does not take
615          * a ref to the task.
616          */
617         sc = task->sc;
618         if (!sc)
619                 return;
620
621         if (task->state == ISCSI_TASK_PENDING) {
622                 /*
623                  * cmd never made it to the xmit thread, so we should not count
624                  * the cmd in the sequencing
625                  */
626                 conn->session->queued_cmdsn--;
627                 /* it was never sent so just complete like normal */
628                 state = ISCSI_TASK_COMPLETED;
629         } else if (err == DID_TRANSPORT_DISRUPTED)
630                 state = ISCSI_TASK_ABRT_SESS_RECOV;
631         else
632                 state = ISCSI_TASK_ABRT_TMF;
633
634         sc->result = err << 16;
635         if (!scsi_bidi_cmnd(sc))
636                 scsi_set_resid(sc, scsi_bufflen(sc));
637         else {
638                 scsi_out(sc)->resid = scsi_out(sc)->length;
639                 scsi_in(sc)->resid = scsi_in(sc)->length;
640         }
641
642         /* regular RX path uses back_lock */
643         spin_lock_bh(&conn->session->back_lock);
644         iscsi_complete_task(task, state);
645         spin_unlock_bh(&conn->session->back_lock);
646 }
647
648 static int iscsi_prep_mgmt_task(struct iscsi_conn *conn,
649                                 struct iscsi_task *task)
650 {
651         struct iscsi_session *session = conn->session;
652         struct iscsi_hdr *hdr = task->hdr;
653         struct iscsi_nopout *nop = (struct iscsi_nopout *)hdr;
654         uint8_t opcode = hdr->opcode & ISCSI_OPCODE_MASK;
655
656         if (conn->session->state == ISCSI_STATE_LOGGING_OUT)
657                 return -ENOTCONN;
658
659         if (opcode != ISCSI_OP_LOGIN && opcode != ISCSI_OP_TEXT)
660                 nop->exp_statsn = cpu_to_be32(conn->exp_statsn);
661         /*
662          * pre-format CmdSN for outgoing PDU.
663          */
664         nop->cmdsn = cpu_to_be32(session->cmdsn);
665         if (hdr->itt != RESERVED_ITT) {
666                 /*
667                  * TODO: We always use immediate for normal session pdus.
668                  * If we start to send tmfs or nops as non-immediate then
669                  * we should start checking the cmdsn numbers for mgmt tasks.
670                  *
671                  * During discovery sessions iscsid sends TEXT as non immediate,
672                  * but we always only send one PDU at a time.
673                  */
674                 if (conn->c_stage == ISCSI_CONN_STARTED &&
675                     !(hdr->opcode & ISCSI_OP_IMMEDIATE)) {
676                         session->queued_cmdsn++;
677                         session->cmdsn++;
678                 }
679         }
680
681         if (session->tt->init_task && session->tt->init_task(task))
682                 return -EIO;
683
684         if ((hdr->opcode & ISCSI_OPCODE_MASK) == ISCSI_OP_LOGOUT)
685                 session->state = ISCSI_STATE_LOGGING_OUT;
686
687         task->state = ISCSI_TASK_RUNNING;
688         ISCSI_DBG_SESSION(session, "mgmtpdu [op 0x%x hdr->itt 0x%x "
689                           "datalen %d]\n", hdr->opcode & ISCSI_OPCODE_MASK,
690                           hdr->itt, task->data_count);
691         return 0;
692 }
693
694 static struct iscsi_task *
695 __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
696                       char *data, uint32_t data_size)
697 {
698         struct iscsi_session *session = conn->session;
699         struct iscsi_host *ihost = shost_priv(session->host);
700         uint8_t opcode = hdr->opcode & ISCSI_OPCODE_MASK;
701         struct iscsi_task *task;
702         itt_t itt;
703
704         if (session->state == ISCSI_STATE_TERMINATE)
705                 return NULL;
706
707         if (opcode == ISCSI_OP_LOGIN || opcode == ISCSI_OP_TEXT) {
708                 /*
709                  * Login and Text are sent serially, in
710                  * request-followed-by-response sequence.
711                  * Same task can be used. Same ITT must be used.
712                  * Note that login_task is preallocated at conn_create().
713                  */
714                 if (conn->login_task->state != ISCSI_TASK_FREE) {
715                         iscsi_conn_printk(KERN_ERR, conn, "Login/Text in "
716                                           "progress. Cannot start new task.\n");
717                         return NULL;
718                 }
719
720                 if (data_size > ISCSI_DEF_MAX_RECV_SEG_LEN) {
721                         iscsi_conn_printk(KERN_ERR, conn, "Invalid buffer len of %u for login task. Max len is %u\n", data_size, ISCSI_DEF_MAX_RECV_SEG_LEN);
722                         return NULL;
723                 }
724
725                 task = conn->login_task;
726         } else {
727                 if (session->state != ISCSI_STATE_LOGGED_IN)
728                         return NULL;
729
730                 if (data_size != 0) {
731                         iscsi_conn_printk(KERN_ERR, conn, "Can not send data buffer of len %u for op 0x%x\n", data_size, opcode);
732                         return NULL;
733                 }
734
735                 BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE);
736                 BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED);
737
738                 if (!kfifo_out(&session->cmdpool.queue,
739                                  (void*)&task, sizeof(void*)))
740                         return NULL;
741         }
742         /*
743          * released in complete pdu for task we expect a response for, and
744          * released by the lld when it has transmitted the task for
745          * pdus we do not expect a response for.
746          */
747         refcount_set(&task->refcount, 1);
748         task->conn = conn;
749         task->sc = NULL;
750         INIT_LIST_HEAD(&task->running);
751         task->state = ISCSI_TASK_PENDING;
752
753         if (data_size) {
754                 memcpy(task->data, data, data_size);
755                 task->data_count = data_size;
756         } else
757                 task->data_count = 0;
758
759         if (conn->session->tt->alloc_pdu) {
760                 if (conn->session->tt->alloc_pdu(task, hdr->opcode)) {
761                         iscsi_conn_printk(KERN_ERR, conn, "Could not allocate "
762                                          "pdu for mgmt task.\n");
763                         goto free_task;
764                 }
765         }
766
767         itt = task->hdr->itt;
768         task->hdr_len = sizeof(struct iscsi_hdr);
769         memcpy(task->hdr, hdr, sizeof(struct iscsi_hdr));
770
771         if (hdr->itt != RESERVED_ITT) {
772                 if (session->tt->parse_pdu_itt)
773                         task->hdr->itt = itt;
774                 else
775                         task->hdr->itt = build_itt(task->itt,
776                                                    task->conn->session->age);
777         }
778
779         if (unlikely(READ_ONCE(conn->ping_task) == INVALID_SCSI_TASK))
780                 WRITE_ONCE(conn->ping_task, task);
781
782         if (!ihost->workq) {
783                 if (iscsi_prep_mgmt_task(conn, task))
784                         goto free_task;
785
786                 if (session->tt->xmit_task(task))
787                         goto free_task;
788         } else {
789                 spin_lock_bh(&conn->taskqueuelock);
790                 list_add_tail(&task->running, &conn->mgmtqueue);
791                 spin_unlock_bh(&conn->taskqueuelock);
792                 iscsi_conn_queue_work(conn);
793         }
794
795         return task;
796
797 free_task:
798         /* regular RX path uses back_lock */
799         spin_lock(&session->back_lock);
800         __iscsi_put_task(task);
801         spin_unlock(&session->back_lock);
802         return NULL;
803 }
804
805 int iscsi_conn_send_pdu(struct iscsi_cls_conn *cls_conn, struct iscsi_hdr *hdr,
806                         char *data, uint32_t data_size)
807 {
808         struct iscsi_conn *conn = cls_conn->dd_data;
809         struct iscsi_session *session = conn->session;
810         int err = 0;
811
812         spin_lock_bh(&session->frwd_lock);
813         if (!__iscsi_conn_send_pdu(conn, hdr, data, data_size))
814                 err = -EPERM;
815         spin_unlock_bh(&session->frwd_lock);
816         return err;
817 }
818 EXPORT_SYMBOL_GPL(iscsi_conn_send_pdu);
819
820 /**
821  * iscsi_cmd_rsp - SCSI Command Response processing
822  * @conn: iscsi connection
823  * @hdr: iscsi header
824  * @task: scsi command task
825  * @data: cmd data buffer
826  * @datalen: len of buffer
827  *
828  * iscsi_cmd_rsp sets up the scsi_cmnd fields based on the PDU and
829  * then completes the command and task.
830  **/
831 static void iscsi_scsi_cmd_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
832                                struct iscsi_task *task, char *data,
833                                int datalen)
834 {
835         struct iscsi_scsi_rsp *rhdr = (struct iscsi_scsi_rsp *)hdr;
836         struct iscsi_session *session = conn->session;
837         struct scsi_cmnd *sc = task->sc;
838
839         iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr);
840         conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
841
842         sc->result = (DID_OK << 16) | rhdr->cmd_status;
843
844         if (task->protected) {
845                 sector_t sector;
846                 u8 ascq;
847
848                 /**
849                  * Transports that didn't implement check_protection
850                  * callback but still published T10-PI support to scsi-mid
851                  * deserve this BUG_ON.
852                  **/
853                 BUG_ON(!session->tt->check_protection);
854
855                 ascq = session->tt->check_protection(task, &sector);
856                 if (ascq) {
857                         sc->result = DRIVER_SENSE << 24 |
858                                      SAM_STAT_CHECK_CONDITION;
859                         scsi_build_sense_buffer(1, sc->sense_buffer,
860                                                 ILLEGAL_REQUEST, 0x10, ascq);
861                         scsi_set_sense_information(sc->sense_buffer,
862                                                    SCSI_SENSE_BUFFERSIZE,
863                                                    sector);
864                         goto out;
865                 }
866         }
867
868         if (rhdr->response != ISCSI_STATUS_CMD_COMPLETED) {
869                 sc->result = DID_ERROR << 16;
870                 goto out;
871         }
872
873         if (rhdr->cmd_status == SAM_STAT_CHECK_CONDITION) {
874                 uint16_t senselen;
875
876                 if (datalen < 2) {
877 invalid_datalen:
878                         iscsi_conn_printk(KERN_ERR,  conn,
879                                          "Got CHECK_CONDITION but invalid data "
880                                          "buffer size of %d\n", datalen);
881                         sc->result = DID_BAD_TARGET << 16;
882                         goto out;
883                 }
884
885                 senselen = get_unaligned_be16(data);
886                 if (datalen < senselen)
887                         goto invalid_datalen;
888
889                 memcpy(sc->sense_buffer, data + 2,
890                        min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE));
891                 ISCSI_DBG_SESSION(session, "copied %d bytes of sense\n",
892                                   min_t(uint16_t, senselen,
893                                   SCSI_SENSE_BUFFERSIZE));
894         }
895
896         if (rhdr->flags & (ISCSI_FLAG_CMD_BIDI_UNDERFLOW |
897                            ISCSI_FLAG_CMD_BIDI_OVERFLOW)) {
898                 int res_count = be32_to_cpu(rhdr->bi_residual_count);
899
900                 if (scsi_bidi_cmnd(sc) && res_count > 0 &&
901                                 (rhdr->flags & ISCSI_FLAG_CMD_BIDI_OVERFLOW ||
902                                  res_count <= scsi_in(sc)->length))
903                         scsi_in(sc)->resid = res_count;
904                 else
905                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
906         }
907
908         if (rhdr->flags & (ISCSI_FLAG_CMD_UNDERFLOW |
909                            ISCSI_FLAG_CMD_OVERFLOW)) {
910                 int res_count = be32_to_cpu(rhdr->residual_count);
911
912                 if (res_count > 0 &&
913                     (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW ||
914                      res_count <= scsi_bufflen(sc)))
915                         /* write side for bidi or uni-io set_resid */
916                         scsi_set_resid(sc, res_count);
917                 else
918                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
919         }
920 out:
921         ISCSI_DBG_SESSION(session, "cmd rsp done [sc %p res %d itt 0x%x]\n",
922                           sc, sc->result, task->itt);
923         conn->scsirsp_pdus_cnt++;
924         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
925 }
926
927 /**
928  * iscsi_data_in_rsp - SCSI Data-In Response processing
929  * @conn: iscsi connection
930  * @hdr:  iscsi pdu
931  * @task: scsi command task
932  **/
933 static void
934 iscsi_data_in_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
935                   struct iscsi_task *task)
936 {
937         struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)hdr;
938         struct scsi_cmnd *sc = task->sc;
939
940         if (!(rhdr->flags & ISCSI_FLAG_DATA_STATUS))
941                 return;
942
943         iscsi_update_cmdsn(conn->session, (struct iscsi_nopin *)hdr);
944         sc->result = (DID_OK << 16) | rhdr->cmd_status;
945         conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1;
946         if (rhdr->flags & (ISCSI_FLAG_DATA_UNDERFLOW |
947                            ISCSI_FLAG_DATA_OVERFLOW)) {
948                 int res_count = be32_to_cpu(rhdr->residual_count);
949
950                 if (res_count > 0 &&
951                     (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW ||
952                      res_count <= scsi_in(sc)->length))
953                         scsi_in(sc)->resid = res_count;
954                 else
955                         sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status;
956         }
957
958         ISCSI_DBG_SESSION(conn->session, "data in with status done "
959                           "[sc %p res %d itt 0x%x]\n",
960                           sc, sc->result, task->itt);
961         conn->scsirsp_pdus_cnt++;
962         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
963 }
964
965 static void iscsi_tmf_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr)
966 {
967         struct iscsi_tm_rsp *tmf = (struct iscsi_tm_rsp *)hdr;
968         struct iscsi_session *session = conn->session;
969
970         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
971         conn->tmfrsp_pdus_cnt++;
972
973         if (session->tmf_state != TMF_QUEUED)
974                 return;
975
976         if (tmf->response == ISCSI_TMF_RSP_COMPLETE)
977                 session->tmf_state = TMF_SUCCESS;
978         else if (tmf->response == ISCSI_TMF_RSP_NO_TASK)
979                 session->tmf_state = TMF_NOT_FOUND;
980         else
981                 session->tmf_state = TMF_FAILED;
982         wake_up(&session->ehwait);
983 }
984
985 static int iscsi_send_nopout(struct iscsi_conn *conn, struct iscsi_nopin *rhdr)
986 {
987         struct iscsi_nopout hdr;
988         struct iscsi_task *task;
989
990         if (!rhdr) {
991                 if (READ_ONCE(conn->ping_task))
992                         return -EINVAL;
993                 WRITE_ONCE(conn->ping_task, INVALID_SCSI_TASK);
994         }
995
996         memset(&hdr, 0, sizeof(struct iscsi_nopout));
997         hdr.opcode = ISCSI_OP_NOOP_OUT | ISCSI_OP_IMMEDIATE;
998         hdr.flags = ISCSI_FLAG_CMD_FINAL;
999
1000         if (rhdr) {
1001                 hdr.lun = rhdr->lun;
1002                 hdr.ttt = rhdr->ttt;
1003                 hdr.itt = RESERVED_ITT;
1004         } else
1005                 hdr.ttt = RESERVED_ITT;
1006
1007         task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)&hdr, NULL, 0);
1008         if (!task) {
1009                 if (!rhdr)
1010                         WRITE_ONCE(conn->ping_task, NULL);
1011                 iscsi_conn_printk(KERN_ERR, conn, "Could not send nopout\n");
1012                 return -EIO;
1013         } else if (!rhdr) {
1014                 /* only track our nops */
1015                 conn->last_ping = jiffies;
1016         }
1017
1018         return 0;
1019 }
1020
1021 static int iscsi_nop_out_rsp(struct iscsi_task *task,
1022                              struct iscsi_nopin *nop, char *data, int datalen)
1023 {
1024         struct iscsi_conn *conn = task->conn;
1025         int rc = 0;
1026
1027         if (READ_ONCE(conn->ping_task) != task) {
1028                 /*
1029                  * If this is not in response to one of our
1030                  * nops then it must be from userspace.
1031                  */
1032                 if (iscsi_recv_pdu(conn->cls_conn, (struct iscsi_hdr *)nop,
1033                                    data, datalen))
1034                         rc = ISCSI_ERR_CONN_FAILED;
1035         } else
1036                 mod_timer(&conn->transport_timer, jiffies + conn->recv_timeout);
1037         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
1038         return rc;
1039 }
1040
1041 static int iscsi_handle_reject(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
1042                                char *data, int datalen)
1043 {
1044         struct iscsi_reject *reject = (struct iscsi_reject *)hdr;
1045         struct iscsi_hdr rejected_pdu;
1046         int opcode, rc = 0;
1047
1048         conn->exp_statsn = be32_to_cpu(reject->statsn) + 1;
1049
1050         if (ntoh24(reject->dlength) > datalen ||
1051             ntoh24(reject->dlength) < sizeof(struct iscsi_hdr)) {
1052                 iscsi_conn_printk(KERN_ERR, conn, "Cannot handle rejected "
1053                                   "pdu. Invalid data length (pdu dlength "
1054                                   "%u, datalen %d\n", ntoh24(reject->dlength),
1055                                   datalen);
1056                 return ISCSI_ERR_PROTO;
1057         }
1058         memcpy(&rejected_pdu, data, sizeof(struct iscsi_hdr));
1059         opcode = rejected_pdu.opcode & ISCSI_OPCODE_MASK;
1060
1061         switch (reject->reason) {
1062         case ISCSI_REASON_DATA_DIGEST_ERROR:
1063                 iscsi_conn_printk(KERN_ERR, conn,
1064                                   "pdu (op 0x%x itt 0x%x) rejected "
1065                                   "due to DataDigest error.\n",
1066                                   opcode, rejected_pdu.itt);
1067                 break;
1068         case ISCSI_REASON_IMM_CMD_REJECT:
1069                 iscsi_conn_printk(KERN_ERR, conn,
1070                                   "pdu (op 0x%x itt 0x%x) rejected. Too many "
1071                                   "immediate commands.\n",
1072                                   opcode, rejected_pdu.itt);
1073                 /*
1074                  * We only send one TMF at a time so if the target could not
1075                  * handle it, then it should get fixed (RFC mandates that
1076                  * a target can handle one immediate TMF per conn).
1077                  *
1078                  * For nops-outs, we could have sent more than one if
1079                  * the target is sending us lots of nop-ins
1080                  */
1081                 if (opcode != ISCSI_OP_NOOP_OUT)
1082                         return 0;
1083
1084                 if (rejected_pdu.itt == cpu_to_be32(ISCSI_RESERVED_TAG)) {
1085                         /*
1086                          * nop-out in response to target's nop-out rejected.
1087                          * Just resend.
1088                          */
1089                         /* In RX path we are under back lock */
1090                         spin_unlock(&conn->session->back_lock);
1091                         spin_lock(&conn->session->frwd_lock);
1092                         iscsi_send_nopout(conn,
1093                                           (struct iscsi_nopin*)&rejected_pdu);
1094                         spin_unlock(&conn->session->frwd_lock);
1095                         spin_lock(&conn->session->back_lock);
1096                 } else {
1097                         struct iscsi_task *task;
1098                         /*
1099                          * Our nop as ping got dropped. We know the target
1100                          * and transport are ok so just clean up
1101                          */
1102                         task = iscsi_itt_to_task(conn, rejected_pdu.itt);
1103                         if (!task) {
1104                                 iscsi_conn_printk(KERN_ERR, conn,
1105                                                  "Invalid pdu reject. Could "
1106                                                  "not lookup rejected task.\n");
1107                                 rc = ISCSI_ERR_BAD_ITT;
1108                         } else
1109                                 rc = iscsi_nop_out_rsp(task,
1110                                         (struct iscsi_nopin*)&rejected_pdu,
1111                                         NULL, 0);
1112                 }
1113                 break;
1114         default:
1115                 iscsi_conn_printk(KERN_ERR, conn,
1116                                   "pdu (op 0x%x itt 0x%x) rejected. Reason "
1117                                   "code 0x%x\n", rejected_pdu.opcode,
1118                                   rejected_pdu.itt, reject->reason);
1119                 break;
1120         }
1121         return rc;
1122 }
1123
1124 /**
1125  * iscsi_itt_to_task - look up task by itt
1126  * @conn: iscsi connection
1127  * @itt: itt
1128  *
1129  * This should be used for mgmt tasks like login and nops, or if
1130  * the LDD's itt space does not include the session age.
1131  *
1132  * The session back_lock must be held.
1133  */
1134 struct iscsi_task *iscsi_itt_to_task(struct iscsi_conn *conn, itt_t itt)
1135 {
1136         struct iscsi_session *session = conn->session;
1137         int i;
1138
1139         if (itt == RESERVED_ITT)
1140                 return NULL;
1141
1142         if (session->tt->parse_pdu_itt)
1143                 session->tt->parse_pdu_itt(conn, itt, &i, NULL);
1144         else
1145                 i = get_itt(itt);
1146         if (i >= session->cmds_max)
1147                 return NULL;
1148
1149         return session->cmds[i];
1150 }
1151 EXPORT_SYMBOL_GPL(iscsi_itt_to_task);
1152
1153 /**
1154  * __iscsi_complete_pdu - complete pdu
1155  * @conn: iscsi conn
1156  * @hdr: iscsi header
1157  * @data: data buffer
1158  * @datalen: len of data buffer
1159  *
1160  * Completes pdu processing by freeing any resources allocated at
1161  * queuecommand or send generic. session back_lock must be held and verify
1162  * itt must have been called.
1163  */
1164 int __iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
1165                          char *data, int datalen)
1166 {
1167         struct iscsi_session *session = conn->session;
1168         int opcode = hdr->opcode & ISCSI_OPCODE_MASK, rc = 0;
1169         struct iscsi_task *task;
1170         uint32_t itt;
1171
1172         conn->last_recv = jiffies;
1173         rc = iscsi_verify_itt(conn, hdr->itt);
1174         if (rc)
1175                 return rc;
1176
1177         if (hdr->itt != RESERVED_ITT)
1178                 itt = get_itt(hdr->itt);
1179         else
1180                 itt = ~0U;
1181
1182         ISCSI_DBG_SESSION(session, "[op 0x%x cid %d itt 0x%x len %d]\n",
1183                           opcode, conn->id, itt, datalen);
1184
1185         if (itt == ~0U) {
1186                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1187
1188                 switch(opcode) {
1189                 case ISCSI_OP_NOOP_IN:
1190                         if (datalen) {
1191                                 rc = ISCSI_ERR_PROTO;
1192                                 break;
1193                         }
1194
1195                         if (hdr->ttt == cpu_to_be32(ISCSI_RESERVED_TAG))
1196                                 break;
1197
1198                         /* In RX path we are under back lock */
1199                         spin_unlock(&session->back_lock);
1200                         spin_lock(&session->frwd_lock);
1201                         iscsi_send_nopout(conn, (struct iscsi_nopin*)hdr);
1202                         spin_unlock(&session->frwd_lock);
1203                         spin_lock(&session->back_lock);
1204                         break;
1205                 case ISCSI_OP_REJECT:
1206                         rc = iscsi_handle_reject(conn, hdr, data, datalen);
1207                         break;
1208                 case ISCSI_OP_ASYNC_EVENT:
1209                         conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
1210                         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
1211                                 rc = ISCSI_ERR_CONN_FAILED;
1212                         break;
1213                 default:
1214                         rc = ISCSI_ERR_BAD_OPCODE;
1215                         break;
1216                 }
1217                 goto out;
1218         }
1219
1220         switch(opcode) {
1221         case ISCSI_OP_SCSI_CMD_RSP:
1222         case ISCSI_OP_SCSI_DATA_IN:
1223                 task = iscsi_itt_to_ctask(conn, hdr->itt);
1224                 if (!task)
1225                         return ISCSI_ERR_BAD_ITT;
1226                 task->last_xfer = jiffies;
1227                 break;
1228         case ISCSI_OP_R2T:
1229                 /*
1230                  * LLD handles R2Ts if they need to.
1231                  */
1232                 return 0;
1233         case ISCSI_OP_LOGOUT_RSP:
1234         case ISCSI_OP_LOGIN_RSP:
1235         case ISCSI_OP_TEXT_RSP:
1236         case ISCSI_OP_SCSI_TMFUNC_RSP:
1237         case ISCSI_OP_NOOP_IN:
1238                 task = iscsi_itt_to_task(conn, hdr->itt);
1239                 if (!task)
1240                         return ISCSI_ERR_BAD_ITT;
1241                 break;
1242         default:
1243                 return ISCSI_ERR_BAD_OPCODE;
1244         }
1245
1246         switch(opcode) {
1247         case ISCSI_OP_SCSI_CMD_RSP:
1248                 iscsi_scsi_cmd_rsp(conn, hdr, task, data, datalen);
1249                 break;
1250         case ISCSI_OP_SCSI_DATA_IN:
1251                 iscsi_data_in_rsp(conn, hdr, task);
1252                 break;
1253         case ISCSI_OP_LOGOUT_RSP:
1254                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1255                 if (datalen) {
1256                         rc = ISCSI_ERR_PROTO;
1257                         break;
1258                 }
1259                 conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
1260                 goto recv_pdu;
1261         case ISCSI_OP_LOGIN_RSP:
1262         case ISCSI_OP_TEXT_RSP:
1263                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1264                 /*
1265                  * login related PDU's exp_statsn is handled in
1266                  * userspace
1267                  */
1268                 goto recv_pdu;
1269         case ISCSI_OP_SCSI_TMFUNC_RSP:
1270                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1271                 if (datalen) {
1272                         rc = ISCSI_ERR_PROTO;
1273                         break;
1274                 }
1275
1276                 iscsi_tmf_rsp(conn, hdr);
1277                 iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
1278                 break;
1279         case ISCSI_OP_NOOP_IN:
1280                 iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr);
1281                 if (hdr->ttt != cpu_to_be32(ISCSI_RESERVED_TAG) || datalen) {
1282                         rc = ISCSI_ERR_PROTO;
1283                         break;
1284                 }
1285                 conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1;
1286
1287                 rc = iscsi_nop_out_rsp(task, (struct iscsi_nopin*)hdr,
1288                                        data, datalen);
1289                 break;
1290         default:
1291                 rc = ISCSI_ERR_BAD_OPCODE;
1292                 break;
1293         }
1294
1295 out:
1296         return rc;
1297 recv_pdu:
1298         if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen))
1299                 rc = ISCSI_ERR_CONN_FAILED;
1300         iscsi_complete_task(task, ISCSI_TASK_COMPLETED);
1301         return rc;
1302 }
1303 EXPORT_SYMBOL_GPL(__iscsi_complete_pdu);
1304
1305 int iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr,
1306                        char *data, int datalen)
1307 {
1308         int rc;
1309
1310         spin_lock(&conn->session->back_lock);
1311         rc = __iscsi_complete_pdu(conn, hdr, data, datalen);
1312         spin_unlock(&conn->session->back_lock);
1313         return rc;
1314 }
1315 EXPORT_SYMBOL_GPL(iscsi_complete_pdu);
1316
1317 int iscsi_verify_itt(struct iscsi_conn *conn, itt_t itt)
1318 {
1319         struct iscsi_session *session = conn->session;
1320         int age = 0, i = 0;
1321
1322         if (itt == RESERVED_ITT)
1323                 return 0;
1324
1325         if (session->tt->parse_pdu_itt)
1326                 session->tt->parse_pdu_itt(conn, itt, &i, &age);
1327         else {
1328                 i = get_itt(itt);
1329                 age = ((__force u32)itt >> ISCSI_AGE_SHIFT) & ISCSI_AGE_MASK;
1330         }
1331
1332         if (age != session->age) {
1333                 iscsi_conn_printk(KERN_ERR, conn,
1334                                   "received itt %x expected session age (%x)\n",
1335                                   (__force u32)itt, session->age);
1336                 return ISCSI_ERR_BAD_ITT;
1337         }
1338
1339         if (i >= session->cmds_max) {
1340                 iscsi_conn_printk(KERN_ERR, conn,
1341                                   "received invalid itt index %u (max cmds "
1342                                    "%u.\n", i, session->cmds_max);
1343                 return ISCSI_ERR_BAD_ITT;
1344         }
1345         return 0;
1346 }
1347 EXPORT_SYMBOL_GPL(iscsi_verify_itt);
1348
1349 /**
1350  * iscsi_itt_to_ctask - look up ctask by itt
1351  * @conn: iscsi connection
1352  * @itt: itt
1353  *
1354  * This should be used for cmd tasks.
1355  *
1356  * The session back_lock must be held.
1357  */
1358 struct iscsi_task *iscsi_itt_to_ctask(struct iscsi_conn *conn, itt_t itt)
1359 {
1360         struct iscsi_task *task;
1361
1362         if (iscsi_verify_itt(conn, itt))
1363                 return NULL;
1364
1365         task = iscsi_itt_to_task(conn, itt);
1366         if (!task || !task->sc)
1367                 return NULL;
1368
1369         if (task->sc->SCp.phase != conn->session->age) {
1370                 iscsi_session_printk(KERN_ERR, conn->session,
1371                                   "task's session age %d, expected %d\n",
1372                                   task->sc->SCp.phase, conn->session->age);
1373                 return NULL;
1374         }
1375
1376         return task;
1377 }
1378 EXPORT_SYMBOL_GPL(iscsi_itt_to_ctask);
1379
1380 void iscsi_session_failure(struct iscsi_session *session,
1381                            enum iscsi_err err)
1382 {
1383         struct iscsi_conn *conn;
1384
1385         spin_lock_bh(&session->frwd_lock);
1386         conn = session->leadconn;
1387         if (session->state == ISCSI_STATE_TERMINATE || !conn) {
1388                 spin_unlock_bh(&session->frwd_lock);
1389                 return;
1390         }
1391
1392         iscsi_get_conn(conn->cls_conn);
1393         spin_unlock_bh(&session->frwd_lock);
1394         /*
1395          * if the host is being removed bypass the connection
1396          * recovery initialization because we are going to kill
1397          * the session.
1398          */
1399         if (err == ISCSI_ERR_INVALID_HOST)
1400                 iscsi_conn_error_event(conn->cls_conn, err);
1401         else
1402                 iscsi_conn_failure(conn, err);
1403         iscsi_put_conn(conn->cls_conn);
1404 }
1405 EXPORT_SYMBOL_GPL(iscsi_session_failure);
1406
1407 void iscsi_conn_failure(struct iscsi_conn *conn, enum iscsi_err err)
1408 {
1409         struct iscsi_session *session = conn->session;
1410
1411         spin_lock_bh(&session->frwd_lock);
1412         if (session->state == ISCSI_STATE_FAILED) {
1413                 spin_unlock_bh(&session->frwd_lock);
1414                 return;
1415         }
1416
1417         if (conn->stop_stage == 0)
1418                 session->state = ISCSI_STATE_FAILED;
1419         spin_unlock_bh(&session->frwd_lock);
1420
1421         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1422         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
1423         iscsi_conn_error_event(conn->cls_conn, err);
1424 }
1425 EXPORT_SYMBOL_GPL(iscsi_conn_failure);
1426
1427 static int iscsi_check_cmdsn_window_closed(struct iscsi_conn *conn)
1428 {
1429         struct iscsi_session *session = conn->session;
1430
1431         /*
1432          * Check for iSCSI window and take care of CmdSN wrap-around
1433          */
1434         if (!iscsi_sna_lte(session->queued_cmdsn, session->max_cmdsn)) {
1435                 ISCSI_DBG_SESSION(session, "iSCSI CmdSN closed. ExpCmdSn "
1436                                   "%u MaxCmdSN %u CmdSN %u/%u\n",
1437                                   session->exp_cmdsn, session->max_cmdsn,
1438                                   session->cmdsn, session->queued_cmdsn);
1439                 return -ENOSPC;
1440         }
1441         return 0;
1442 }
1443
1444 static int iscsi_xmit_task(struct iscsi_conn *conn)
1445 {
1446         struct iscsi_task *task = conn->task;
1447         int rc;
1448
1449         if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx))
1450                 return -ENODATA;
1451
1452         spin_lock_bh(&conn->session->back_lock);
1453         if (conn->task == NULL) {
1454                 spin_unlock_bh(&conn->session->back_lock);
1455                 return -ENODATA;
1456         }
1457         __iscsi_get_task(task);
1458         spin_unlock_bh(&conn->session->back_lock);
1459         spin_unlock_bh(&conn->session->frwd_lock);
1460         rc = conn->session->tt->xmit_task(task);
1461         spin_lock_bh(&conn->session->frwd_lock);
1462         if (!rc) {
1463                 /* done with this task */
1464                 task->last_xfer = jiffies;
1465                 conn->task = NULL;
1466         }
1467         /* regular RX path uses back_lock */
1468         spin_lock(&conn->session->back_lock);
1469         __iscsi_put_task(task);
1470         spin_unlock(&conn->session->back_lock);
1471         return rc;
1472 }
1473
1474 /**
1475  * iscsi_requeue_task - requeue task to run from session workqueue
1476  * @task: task to requeue
1477  *
1478  * LLDs that need to run a task from the session workqueue should call
1479  * this. The session frwd_lock must be held. This should only be called
1480  * by software drivers.
1481  */
1482 void iscsi_requeue_task(struct iscsi_task *task)
1483 {
1484         struct iscsi_conn *conn = task->conn;
1485
1486         /*
1487          * this may be on the requeue list already if the xmit_task callout
1488          * is handling the r2ts while we are adding new ones
1489          */
1490         spin_lock_bh(&conn->taskqueuelock);
1491         if (list_empty(&task->running))
1492                 list_add_tail(&task->running, &conn->requeue);
1493         spin_unlock_bh(&conn->taskqueuelock);
1494         iscsi_conn_queue_work(conn);
1495 }
1496 EXPORT_SYMBOL_GPL(iscsi_requeue_task);
1497
1498 /**
1499  * iscsi_data_xmit - xmit any command into the scheduled connection
1500  * @conn: iscsi connection
1501  *
1502  * Notes:
1503  *      The function can return -EAGAIN in which case the caller must
1504  *      re-schedule it again later or recover. '0' return code means
1505  *      successful xmit.
1506  **/
1507 static int iscsi_data_xmit(struct iscsi_conn *conn)
1508 {
1509         struct iscsi_task *task;
1510         int rc = 0;
1511
1512         spin_lock_bh(&conn->session->frwd_lock);
1513         if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx)) {
1514                 ISCSI_DBG_SESSION(conn->session, "Tx suspended!\n");
1515                 spin_unlock_bh(&conn->session->frwd_lock);
1516                 return -ENODATA;
1517         }
1518
1519         if (conn->task) {
1520                 rc = iscsi_xmit_task(conn);
1521                 if (rc)
1522                         goto done;
1523         }
1524
1525         /*
1526          * process mgmt pdus like nops before commands since we should
1527          * only have one nop-out as a ping from us and targets should not
1528          * overflow us with nop-ins
1529          */
1530         spin_lock_bh(&conn->taskqueuelock);
1531 check_mgmt:
1532         while (!list_empty(&conn->mgmtqueue)) {
1533                 conn->task = list_entry(conn->mgmtqueue.next,
1534                                          struct iscsi_task, running);
1535                 list_del_init(&conn->task->running);
1536                 spin_unlock_bh(&conn->taskqueuelock);
1537                 if (iscsi_prep_mgmt_task(conn, conn->task)) {
1538                         /* regular RX path uses back_lock */
1539                         spin_lock_bh(&conn->session->back_lock);
1540                         __iscsi_put_task(conn->task);
1541                         spin_unlock_bh(&conn->session->back_lock);
1542                         conn->task = NULL;
1543                         spin_lock_bh(&conn->taskqueuelock);
1544                         continue;
1545                 }
1546                 rc = iscsi_xmit_task(conn);
1547                 if (rc)
1548                         goto done;
1549                 spin_lock_bh(&conn->taskqueuelock);
1550         }
1551
1552         /* process pending command queue */
1553         while (!list_empty(&conn->cmdqueue)) {
1554                 conn->task = list_entry(conn->cmdqueue.next, struct iscsi_task,
1555                                         running);
1556                 list_del_init(&conn->task->running);
1557                 spin_unlock_bh(&conn->taskqueuelock);
1558                 if (conn->session->state == ISCSI_STATE_LOGGING_OUT) {
1559                         fail_scsi_task(conn->task, DID_IMM_RETRY);
1560                         spin_lock_bh(&conn->taskqueuelock);
1561                         continue;
1562                 }
1563                 rc = iscsi_prep_scsi_cmd_pdu(conn->task);
1564                 if (rc) {
1565                         if (rc == -ENOMEM || rc == -EACCES)
1566                                 fail_scsi_task(conn->task, DID_IMM_RETRY);
1567                         else
1568                                 fail_scsi_task(conn->task, DID_ABORT);
1569                         spin_lock_bh(&conn->taskqueuelock);
1570                         continue;
1571                 }
1572                 rc = iscsi_xmit_task(conn);
1573                 if (rc)
1574                         goto done;
1575                 /*
1576                  * we could continuously get new task requests so
1577                  * we need to check the mgmt queue for nops that need to
1578                  * be sent to aviod starvation
1579                  */
1580                 spin_lock_bh(&conn->taskqueuelock);
1581                 if (!list_empty(&conn->mgmtqueue))
1582                         goto check_mgmt;
1583         }
1584
1585         while (!list_empty(&conn->requeue)) {
1586                 /*
1587                  * we always do fastlogout - conn stop code will clean up.
1588                  */
1589                 if (conn->session->state == ISCSI_STATE_LOGGING_OUT)
1590                         break;
1591
1592                 task = list_entry(conn->requeue.next, struct iscsi_task,
1593                                   running);
1594                 if (iscsi_check_tmf_restrictions(task, ISCSI_OP_SCSI_DATA_OUT))
1595                         break;
1596
1597                 conn->task = task;
1598                 list_del_init(&conn->task->running);
1599                 conn->task->state = ISCSI_TASK_RUNNING;
1600                 spin_unlock_bh(&conn->taskqueuelock);
1601                 rc = iscsi_xmit_task(conn);
1602                 if (rc)
1603                         goto done;
1604                 spin_lock_bh(&conn->taskqueuelock);
1605                 if (!list_empty(&conn->mgmtqueue))
1606                         goto check_mgmt;
1607         }
1608         spin_unlock_bh(&conn->taskqueuelock);
1609         spin_unlock_bh(&conn->session->frwd_lock);
1610         return -ENODATA;
1611
1612 done:
1613         spin_unlock_bh(&conn->session->frwd_lock);
1614         return rc;
1615 }
1616
1617 static void iscsi_xmitworker(struct work_struct *work)
1618 {
1619         struct iscsi_conn *conn =
1620                 container_of(work, struct iscsi_conn, xmitwork);
1621         int rc;
1622         /*
1623          * serialize Xmit worker on a per-connection basis.
1624          */
1625         do {
1626                 rc = iscsi_data_xmit(conn);
1627         } while (rc >= 0 || rc == -EAGAIN);
1628 }
1629
1630 static inline struct iscsi_task *iscsi_alloc_task(struct iscsi_conn *conn,
1631                                                   struct scsi_cmnd *sc)
1632 {
1633         struct iscsi_task *task;
1634
1635         if (!kfifo_out(&conn->session->cmdpool.queue,
1636                          (void *) &task, sizeof(void *)))
1637                 return NULL;
1638
1639         sc->SCp.phase = conn->session->age;
1640         sc->SCp.ptr = (char *) task;
1641
1642         refcount_set(&task->refcount, 1);
1643         task->state = ISCSI_TASK_PENDING;
1644         task->conn = conn;
1645         task->sc = sc;
1646         task->have_checked_conn = false;
1647         task->last_timeout = jiffies;
1648         task->last_xfer = jiffies;
1649         task->protected = false;
1650         INIT_LIST_HEAD(&task->running);
1651         return task;
1652 }
1653
1654 enum {
1655         FAILURE_BAD_HOST = 1,
1656         FAILURE_SESSION_FAILED,
1657         FAILURE_SESSION_FREED,
1658         FAILURE_WINDOW_CLOSED,
1659         FAILURE_OOM,
1660         FAILURE_SESSION_TERMINATE,
1661         FAILURE_SESSION_IN_RECOVERY,
1662         FAILURE_SESSION_RECOVERY_TIMEOUT,
1663         FAILURE_SESSION_LOGGING_OUT,
1664         FAILURE_SESSION_NOT_READY,
1665 };
1666
1667 int iscsi_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *sc)
1668 {
1669         struct iscsi_cls_session *cls_session;
1670         struct iscsi_host *ihost;
1671         int reason = 0;
1672         struct iscsi_session *session;
1673         struct iscsi_conn *conn;
1674         struct iscsi_task *task = NULL;
1675
1676         sc->result = 0;
1677         sc->SCp.ptr = NULL;
1678
1679         ihost = shost_priv(host);
1680
1681         cls_session = starget_to_session(scsi_target(sc->device));
1682         session = cls_session->dd_data;
1683         spin_lock_bh(&session->frwd_lock);
1684
1685         reason = iscsi_session_chkready(cls_session);
1686         if (reason) {
1687                 sc->result = reason;
1688                 goto fault;
1689         }
1690
1691         if (session->state != ISCSI_STATE_LOGGED_IN) {
1692                 /*
1693                  * to handle the race between when we set the recovery state
1694                  * and block the session we requeue here (commands could
1695                  * be entering our queuecommand while a block is starting
1696                  * up because the block code is not locked)
1697                  */
1698                 switch (session->state) {
1699                 case ISCSI_STATE_FAILED:
1700                         /*
1701                          * cmds should fail during shutdown, if the session
1702                          * state is bad, allowing completion to happen
1703                          */
1704                         if (unlikely(system_state != SYSTEM_RUNNING)) {
1705                                 reason = FAILURE_SESSION_FAILED;
1706                                 sc->result = DID_NO_CONNECT << 16;
1707                                 break;
1708                         }
1709                         /* fall through */
1710                 case ISCSI_STATE_IN_RECOVERY:
1711                         reason = FAILURE_SESSION_IN_RECOVERY;
1712                         sc->result = DID_IMM_RETRY << 16;
1713                         break;
1714                 case ISCSI_STATE_LOGGING_OUT:
1715                         reason = FAILURE_SESSION_LOGGING_OUT;
1716                         sc->result = DID_IMM_RETRY << 16;
1717                         break;
1718                 case ISCSI_STATE_RECOVERY_FAILED:
1719                         reason = FAILURE_SESSION_RECOVERY_TIMEOUT;
1720                         sc->result = DID_TRANSPORT_FAILFAST << 16;
1721                         break;
1722                 case ISCSI_STATE_TERMINATE:
1723                         reason = FAILURE_SESSION_TERMINATE;
1724                         sc->result = DID_NO_CONNECT << 16;
1725                         break;
1726                 default:
1727                         reason = FAILURE_SESSION_FREED;
1728                         sc->result = DID_NO_CONNECT << 16;
1729                 }
1730                 goto fault;
1731         }
1732
1733         conn = session->leadconn;
1734         if (!conn) {
1735                 reason = FAILURE_SESSION_FREED;
1736                 sc->result = DID_NO_CONNECT << 16;
1737                 goto fault;
1738         }
1739
1740         if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx)) {
1741                 reason = FAILURE_SESSION_IN_RECOVERY;
1742                 sc->result = DID_REQUEUE << 16;
1743                 goto fault;
1744         }
1745
1746         if (iscsi_check_cmdsn_window_closed(conn)) {
1747                 reason = FAILURE_WINDOW_CLOSED;
1748                 goto reject;
1749         }
1750
1751         task = iscsi_alloc_task(conn, sc);
1752         if (!task) {
1753                 reason = FAILURE_OOM;
1754                 goto reject;
1755         }
1756
1757         if (!ihost->workq) {
1758                 reason = iscsi_prep_scsi_cmd_pdu(task);
1759                 if (reason) {
1760                         if (reason == -ENOMEM ||  reason == -EACCES) {
1761                                 reason = FAILURE_OOM;
1762                                 goto prepd_reject;
1763                         } else {
1764                                 sc->result = DID_ABORT << 16;
1765                                 goto prepd_fault;
1766                         }
1767                 }
1768                 if (session->tt->xmit_task(task)) {
1769                         session->cmdsn--;
1770                         reason = FAILURE_SESSION_NOT_READY;
1771                         goto prepd_reject;
1772                 }
1773         } else {
1774                 spin_lock_bh(&conn->taskqueuelock);
1775                 list_add_tail(&task->running, &conn->cmdqueue);
1776                 spin_unlock_bh(&conn->taskqueuelock);
1777                 iscsi_conn_queue_work(conn);
1778         }
1779
1780         session->queued_cmdsn++;
1781         spin_unlock_bh(&session->frwd_lock);
1782         return 0;
1783
1784 prepd_reject:
1785         iscsi_complete_task(task, ISCSI_TASK_REQUEUE_SCSIQ);
1786 reject:
1787         spin_unlock_bh(&session->frwd_lock);
1788         ISCSI_DBG_SESSION(session, "cmd 0x%x rejected (%d)\n",
1789                           sc->cmnd[0], reason);
1790         return SCSI_MLQUEUE_TARGET_BUSY;
1791
1792 prepd_fault:
1793         iscsi_complete_task(task, ISCSI_TASK_REQUEUE_SCSIQ);
1794 fault:
1795         spin_unlock_bh(&session->frwd_lock);
1796         ISCSI_DBG_SESSION(session, "iscsi: cmd 0x%x is not queued (%d)\n",
1797                           sc->cmnd[0], reason);
1798         if (!scsi_bidi_cmnd(sc))
1799                 scsi_set_resid(sc, scsi_bufflen(sc));
1800         else {
1801                 scsi_out(sc)->resid = scsi_out(sc)->length;
1802                 scsi_in(sc)->resid = scsi_in(sc)->length;
1803         }
1804         sc->scsi_done(sc);
1805         return 0;
1806 }
1807 EXPORT_SYMBOL_GPL(iscsi_queuecommand);
1808
1809 int iscsi_target_alloc(struct scsi_target *starget)
1810 {
1811         struct iscsi_cls_session *cls_session = starget_to_session(starget);
1812         struct iscsi_session *session = cls_session->dd_data;
1813
1814         starget->can_queue = session->scsi_cmds_max;
1815         return 0;
1816 }
1817 EXPORT_SYMBOL_GPL(iscsi_target_alloc);
1818
1819 static void iscsi_tmf_timedout(struct timer_list *t)
1820 {
1821         struct iscsi_session *session = from_timer(session, t, tmf_timer);
1822
1823         spin_lock(&session->frwd_lock);
1824         if (session->tmf_state == TMF_QUEUED) {
1825                 session->tmf_state = TMF_TIMEDOUT;
1826                 ISCSI_DBG_EH(session, "tmf timedout\n");
1827                 /* unblock eh_abort() */
1828                 wake_up(&session->ehwait);
1829         }
1830         spin_unlock(&session->frwd_lock);
1831 }
1832
1833 static int iscsi_exec_task_mgmt_fn(struct iscsi_conn *conn,
1834                                    struct iscsi_tm *hdr, int age,
1835                                    int timeout)
1836         __must_hold(&session->frwd_lock)
1837 {
1838         struct iscsi_session *session = conn->session;
1839         struct iscsi_task *task;
1840
1841         task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)hdr,
1842                                       NULL, 0);
1843         if (!task) {
1844                 spin_unlock_bh(&session->frwd_lock);
1845                 iscsi_conn_printk(KERN_ERR, conn, "Could not send TMF.\n");
1846                 iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED);
1847                 spin_lock_bh(&session->frwd_lock);
1848                 return -EPERM;
1849         }
1850         conn->tmfcmd_pdus_cnt++;
1851         session->tmf_timer.expires = timeout * HZ + jiffies;
1852         add_timer(&session->tmf_timer);
1853         ISCSI_DBG_EH(session, "tmf set timeout\n");
1854
1855         spin_unlock_bh(&session->frwd_lock);
1856         mutex_unlock(&session->eh_mutex);
1857
1858         /*
1859          * block eh thread until:
1860          *
1861          * 1) tmf response
1862          * 2) tmf timeout
1863          * 3) session is terminated or restarted or userspace has
1864          * given up on recovery
1865          */
1866         wait_event_interruptible(session->ehwait, age != session->age ||
1867                                  session->state != ISCSI_STATE_LOGGED_IN ||
1868                                  session->tmf_state != TMF_QUEUED);
1869         if (signal_pending(current))
1870                 flush_signals(current);
1871         del_timer_sync(&session->tmf_timer);
1872
1873         mutex_lock(&session->eh_mutex);
1874         spin_lock_bh(&session->frwd_lock);
1875         /* if the session drops it will clean up the task */
1876         if (age != session->age ||
1877             session->state != ISCSI_STATE_LOGGED_IN)
1878                 return -ENOTCONN;
1879         return 0;
1880 }
1881
1882 /*
1883  * Fail commands. session lock held and recv side suspended and xmit
1884  * thread flushed
1885  */
1886 static void fail_scsi_tasks(struct iscsi_conn *conn, u64 lun, int error)
1887 {
1888         struct iscsi_task *task;
1889         int i;
1890
1891         for (i = 0; i < conn->session->cmds_max; i++) {
1892                 task = conn->session->cmds[i];
1893                 if (!task->sc || task->state == ISCSI_TASK_FREE)
1894                         continue;
1895
1896                 if (lun != -1 && lun != task->sc->device->lun)
1897                         continue;
1898
1899                 ISCSI_DBG_SESSION(conn->session,
1900                                   "failing sc %p itt 0x%x state %d\n",
1901                                   task->sc, task->itt, task->state);
1902                 fail_scsi_task(task, error);
1903         }
1904 }
1905
1906 /**
1907  * iscsi_suspend_queue - suspend iscsi_queuecommand
1908  * @conn: iscsi conn to stop queueing IO on
1909  *
1910  * This grabs the session frwd_lock to make sure no one is in
1911  * xmit_task/queuecommand, and then sets suspend to prevent
1912  * new commands from being queued. This only needs to be called
1913  * by offload drivers that need to sync a path like ep disconnect
1914  * with the iscsi_queuecommand/xmit_task. To start IO again libiscsi
1915  * will call iscsi_start_tx and iscsi_unblock_session when in FFP.
1916  */
1917 void iscsi_suspend_queue(struct iscsi_conn *conn)
1918 {
1919         spin_lock_bh(&conn->session->frwd_lock);
1920         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1921         spin_unlock_bh(&conn->session->frwd_lock);
1922 }
1923 EXPORT_SYMBOL_GPL(iscsi_suspend_queue);
1924
1925 /**
1926  * iscsi_suspend_tx - suspend iscsi_data_xmit
1927  * @conn: iscsi conn tp stop processing IO on.
1928  *
1929  * This function sets the suspend bit to prevent iscsi_data_xmit
1930  * from sending new IO, and if work is queued on the xmit thread
1931  * it will wait for it to be completed.
1932  */
1933 void iscsi_suspend_tx(struct iscsi_conn *conn)
1934 {
1935         struct Scsi_Host *shost = conn->session->host;
1936         struct iscsi_host *ihost = shost_priv(shost);
1937
1938         set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1939         if (ihost->workq)
1940                 flush_workqueue(ihost->workq);
1941 }
1942 EXPORT_SYMBOL_GPL(iscsi_suspend_tx);
1943
1944 static void iscsi_start_tx(struct iscsi_conn *conn)
1945 {
1946         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
1947         iscsi_conn_queue_work(conn);
1948 }
1949
1950 /*
1951  * We want to make sure a ping is in flight. It has timed out.
1952  * And we are not busy processing a pdu that is making
1953  * progress but got started before the ping and is taking a while
1954  * to complete so the ping is just stuck behind it in a queue.
1955  */
1956 static int iscsi_has_ping_timed_out(struct iscsi_conn *conn)
1957 {
1958         if (READ_ONCE(conn->ping_task) &&
1959             time_before_eq(conn->last_recv + (conn->recv_timeout * HZ) +
1960                            (conn->ping_timeout * HZ), jiffies))
1961                 return 1;
1962         else
1963                 return 0;
1964 }
1965
1966 enum blk_eh_timer_return iscsi_eh_cmd_timed_out(struct scsi_cmnd *sc)
1967 {
1968         enum blk_eh_timer_return rc = BLK_EH_DONE;
1969         struct iscsi_task *task = NULL, *running_task;
1970         struct iscsi_cls_session *cls_session;
1971         struct iscsi_session *session;
1972         struct iscsi_conn *conn;
1973         int i;
1974
1975         cls_session = starget_to_session(scsi_target(sc->device));
1976         session = cls_session->dd_data;
1977
1978         ISCSI_DBG_EH(session, "scsi cmd %p timedout\n", sc);
1979
1980         spin_lock_bh(&session->frwd_lock);
1981         task = (struct iscsi_task *)sc->SCp.ptr;
1982         if (!task) {
1983                 /*
1984                  * Raced with completion. Blk layer has taken ownership
1985                  * so let timeout code complete it now.
1986                  */
1987                 rc = BLK_EH_DONE;
1988                 goto done;
1989         }
1990
1991         if (session->state != ISCSI_STATE_LOGGED_IN) {
1992                 /*
1993                  * During shutdown, if session is prematurely disconnected,
1994                  * recovery won't happen and there will be hung cmds. Not
1995                  * handling cmds would trigger EH, also bad in this case.
1996                  * Instead, handle cmd, allow completion to happen and let
1997                  * upper layer to deal with the result.
1998                  */
1999                 if (unlikely(system_state != SYSTEM_RUNNING)) {
2000                         sc->result = DID_NO_CONNECT << 16;
2001                         ISCSI_DBG_EH(session, "sc on shutdown, handled\n");
2002                         rc = BLK_EH_DONE;
2003                         goto done;
2004                 }
2005                 /*
2006                  * We are probably in the middle of iscsi recovery so let
2007                  * that complete and handle the error.
2008                  */
2009                 rc = BLK_EH_RESET_TIMER;
2010                 goto done;
2011         }
2012
2013         conn = session->leadconn;
2014         if (!conn) {
2015                 /* In the middle of shuting down */
2016                 rc = BLK_EH_RESET_TIMER;
2017                 goto done;
2018         }
2019
2020         /*
2021          * If we have sent (at least queued to the network layer) a pdu or
2022          * recvd one for the task since the last timeout ask for
2023          * more time. If on the next timeout we have not made progress
2024          * we can check if it is the task or connection when we send the
2025          * nop as a ping.
2026          */
2027         if (time_after(task->last_xfer, task->last_timeout)) {
2028                 ISCSI_DBG_EH(session, "Command making progress. Asking "
2029                              "scsi-ml for more time to complete. "
2030                              "Last data xfer at %lu. Last timeout was at "
2031                              "%lu\n.", task->last_xfer, task->last_timeout);
2032                 task->have_checked_conn = false;
2033                 rc = BLK_EH_RESET_TIMER;
2034                 goto done;
2035         }
2036
2037         if (!conn->recv_timeout && !conn->ping_timeout)
2038                 goto done;
2039         /*
2040          * if the ping timedout then we are in the middle of cleaning up
2041          * and can let the iscsi eh handle it
2042          */
2043         if (iscsi_has_ping_timed_out(conn)) {
2044                 rc = BLK_EH_RESET_TIMER;
2045                 goto done;
2046         }
2047
2048         for (i = 0; i < conn->session->cmds_max; i++) {
2049                 running_task = conn->session->cmds[i];
2050                 if (!running_task->sc || running_task == task ||
2051                      running_task->state != ISCSI_TASK_RUNNING)
2052                         continue;
2053
2054                 /*
2055                  * Only check if cmds started before this one have made
2056                  * progress, or this could never fail
2057                  */
2058                 if (time_after(running_task->sc->jiffies_at_alloc,
2059                                task->sc->jiffies_at_alloc))
2060                         continue;
2061
2062                 if (time_after(running_task->last_xfer, task->last_timeout)) {
2063                         /*
2064                          * This task has not made progress, but a task
2065                          * started before us has transferred data since
2066                          * we started/last-checked. We could be queueing
2067                          * too many tasks or the LU is bad.
2068                          *
2069                          * If the device is bad the cmds ahead of us on
2070                          * other devs will complete, and this loop will
2071                          * eventually fail starting the scsi eh.
2072                          */
2073                         ISCSI_DBG_EH(session, "Command has not made progress "
2074                                      "but commands ahead of it have. "
2075                                      "Asking scsi-ml for more time to "
2076                                      "complete. Our last xfer vs running task "
2077                                      "last xfer %lu/%lu. Last check %lu.\n",
2078                                      task->last_xfer, running_task->last_xfer,
2079                                      task->last_timeout);
2080                         rc = BLK_EH_RESET_TIMER;
2081                         goto done;
2082                 }
2083         }
2084
2085         /* Assumes nop timeout is shorter than scsi cmd timeout */
2086         if (task->have_checked_conn)
2087                 goto done;
2088
2089         /*
2090          * Checking the transport already or nop from a cmd timeout still
2091          * running
2092          */
2093         if (READ_ONCE(conn->ping_task)) {
2094                 task->have_checked_conn = true;
2095                 rc = BLK_EH_RESET_TIMER;
2096                 goto done;
2097         }
2098
2099         /* Make sure there is a transport check done */
2100         iscsi_send_nopout(conn, NULL);
2101         task->have_checked_conn = true;
2102         rc = BLK_EH_RESET_TIMER;
2103
2104 done:
2105         if (task)
2106                 task->last_timeout = jiffies;
2107         spin_unlock_bh(&session->frwd_lock);
2108         ISCSI_DBG_EH(session, "return %s\n", rc == BLK_EH_RESET_TIMER ?
2109                      "timer reset" : "shutdown or nh");
2110         return rc;
2111 }
2112 EXPORT_SYMBOL_GPL(iscsi_eh_cmd_timed_out);
2113
2114 static void iscsi_check_transport_timeouts(struct timer_list *t)
2115 {
2116         struct iscsi_conn *conn = from_timer(conn, t, transport_timer);
2117         struct iscsi_session *session = conn->session;
2118         unsigned long recv_timeout, next_timeout = 0, last_recv;
2119
2120         spin_lock(&session->frwd_lock);
2121         if (session->state != ISCSI_STATE_LOGGED_IN)
2122                 goto done;
2123
2124         recv_timeout = conn->recv_timeout;
2125         if (!recv_timeout)
2126                 goto done;
2127
2128         recv_timeout *= HZ;
2129         last_recv = conn->last_recv;
2130
2131         if (iscsi_has_ping_timed_out(conn)) {
2132                 iscsi_conn_printk(KERN_ERR, conn, "ping timeout of %d secs "
2133                                   "expired, recv timeout %d, last rx %lu, "
2134                                   "last ping %lu, now %lu\n",
2135                                   conn->ping_timeout, conn->recv_timeout,
2136                                   last_recv, conn->last_ping, jiffies);
2137                 spin_unlock(&session->frwd_lock);
2138                 iscsi_conn_failure(conn, ISCSI_ERR_NOP_TIMEDOUT);
2139                 return;
2140         }
2141
2142         if (time_before_eq(last_recv + recv_timeout, jiffies)) {
2143                 /* send a ping to try to provoke some traffic */
2144                 ISCSI_DBG_CONN(conn, "Sending nopout as ping\n");
2145                 if (iscsi_send_nopout(conn, NULL))
2146                         next_timeout = jiffies + (1 * HZ);
2147                 else
2148                         next_timeout = conn->last_ping + (conn->ping_timeout * HZ);
2149         } else
2150                 next_timeout = last_recv + recv_timeout;
2151
2152         ISCSI_DBG_CONN(conn, "Setting next tmo %lu\n", next_timeout);
2153         mod_timer(&conn->transport_timer, next_timeout);
2154 done:
2155         spin_unlock(&session->frwd_lock);
2156 }
2157
2158 static void iscsi_prep_abort_task_pdu(struct iscsi_task *task,
2159                                       struct iscsi_tm *hdr)
2160 {
2161         memset(hdr, 0, sizeof(*hdr));
2162         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
2163         hdr->flags = ISCSI_TM_FUNC_ABORT_TASK & ISCSI_FLAG_TM_FUNC_MASK;
2164         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
2165         hdr->lun = task->lun;
2166         hdr->rtt = task->hdr_itt;
2167         hdr->refcmdsn = task->cmdsn;
2168 }
2169
2170 int iscsi_eh_abort(struct scsi_cmnd *sc)
2171 {
2172         struct iscsi_cls_session *cls_session;
2173         struct iscsi_session *session;
2174         struct iscsi_conn *conn;
2175         struct iscsi_task *task;
2176         struct iscsi_tm *hdr;
2177         int age;
2178
2179         cls_session = starget_to_session(scsi_target(sc->device));
2180         session = cls_session->dd_data;
2181
2182         ISCSI_DBG_EH(session, "aborting sc %p\n", sc);
2183
2184         mutex_lock(&session->eh_mutex);
2185         spin_lock_bh(&session->frwd_lock);
2186         /*
2187          * if session was ISCSI_STATE_IN_RECOVERY then we may not have
2188          * got the command.
2189          */
2190         if (!sc->SCp.ptr) {
2191                 ISCSI_DBG_EH(session, "sc never reached iscsi layer or "
2192                                       "it completed.\n");
2193                 spin_unlock_bh(&session->frwd_lock);
2194                 mutex_unlock(&session->eh_mutex);
2195                 return SUCCESS;
2196         }
2197
2198         /*
2199          * If we are not logged in or we have started a new session
2200          * then let the host reset code handle this
2201          */
2202         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN ||
2203             sc->SCp.phase != session->age) {
2204                 spin_unlock_bh(&session->frwd_lock);
2205                 mutex_unlock(&session->eh_mutex);
2206                 ISCSI_DBG_EH(session, "failing abort due to dropped "
2207                                   "session.\n");
2208                 return FAILED;
2209         }
2210
2211         conn = session->leadconn;
2212         conn->eh_abort_cnt++;
2213         age = session->age;
2214
2215         task = (struct iscsi_task *)sc->SCp.ptr;
2216         ISCSI_DBG_EH(session, "aborting [sc %p itt 0x%x]\n",
2217                      sc, task->itt);
2218
2219         /* task completed before time out */
2220         if (!task->sc) {
2221                 ISCSI_DBG_EH(session, "sc completed while abort in progress\n");
2222                 goto success;
2223         }
2224
2225         if (task->state == ISCSI_TASK_PENDING) {
2226                 fail_scsi_task(task, DID_ABORT);
2227                 goto success;
2228         }
2229
2230         /* only have one tmf outstanding at a time */
2231         if (session->tmf_state != TMF_INITIAL)
2232                 goto failed;
2233         session->tmf_state = TMF_QUEUED;
2234
2235         hdr = &session->tmhdr;
2236         iscsi_prep_abort_task_pdu(task, hdr);
2237
2238         if (iscsi_exec_task_mgmt_fn(conn, hdr, age, session->abort_timeout))
2239                 goto failed;
2240
2241         switch (session->tmf_state) {
2242         case TMF_SUCCESS:
2243                 spin_unlock_bh(&session->frwd_lock);
2244                 /*
2245                  * stop tx side incase the target had sent a abort rsp but
2246                  * the initiator was still writing out data.
2247                  */
2248                 iscsi_suspend_tx(conn);
2249                 /*
2250                  * we do not stop the recv side because targets have been
2251                  * good and have never sent us a successful tmf response
2252                  * then sent more data for the cmd.
2253                  */
2254                 spin_lock_bh(&session->frwd_lock);
2255                 fail_scsi_task(task, DID_ABORT);
2256                 session->tmf_state = TMF_INITIAL;
2257                 memset(hdr, 0, sizeof(*hdr));
2258                 spin_unlock_bh(&session->frwd_lock);
2259                 iscsi_start_tx(conn);
2260                 goto success_unlocked;
2261         case TMF_TIMEDOUT:
2262                 spin_unlock_bh(&session->frwd_lock);
2263                 iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST);
2264                 goto failed_unlocked;
2265         case TMF_NOT_FOUND:
2266                 if (!sc->SCp.ptr) {
2267                         session->tmf_state = TMF_INITIAL;
2268                         memset(hdr, 0, sizeof(*hdr));
2269                         /* task completed before tmf abort response */
2270                         ISCSI_DBG_EH(session, "sc completed while abort in "
2271                                               "progress\n");
2272                         goto success;
2273                 }
2274                 /* fall through */
2275         default:
2276                 session->tmf_state = TMF_INITIAL;
2277                 goto failed;
2278         }
2279
2280 success:
2281         spin_unlock_bh(&session->frwd_lock);
2282 success_unlocked:
2283         ISCSI_DBG_EH(session, "abort success [sc %p itt 0x%x]\n",
2284                      sc, task->itt);
2285         mutex_unlock(&session->eh_mutex);
2286         return SUCCESS;
2287
2288 failed:
2289         spin_unlock_bh(&session->frwd_lock);
2290 failed_unlocked:
2291         ISCSI_DBG_EH(session, "abort failed [sc %p itt 0x%x]\n", sc,
2292                      task ? task->itt : 0);
2293         mutex_unlock(&session->eh_mutex);
2294         return FAILED;
2295 }
2296 EXPORT_SYMBOL_GPL(iscsi_eh_abort);
2297
2298 static void iscsi_prep_lun_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr)
2299 {
2300         memset(hdr, 0, sizeof(*hdr));
2301         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
2302         hdr->flags = ISCSI_TM_FUNC_LOGICAL_UNIT_RESET & ISCSI_FLAG_TM_FUNC_MASK;
2303         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
2304         int_to_scsilun(sc->device->lun, &hdr->lun);
2305         hdr->rtt = RESERVED_ITT;
2306 }
2307
2308 int iscsi_eh_device_reset(struct scsi_cmnd *sc)
2309 {
2310         struct iscsi_cls_session *cls_session;
2311         struct iscsi_session *session;
2312         struct iscsi_conn *conn;
2313         struct iscsi_tm *hdr;
2314         int rc = FAILED;
2315
2316         cls_session = starget_to_session(scsi_target(sc->device));
2317         session = cls_session->dd_data;
2318
2319         ISCSI_DBG_EH(session, "LU Reset [sc %p lun %llu]\n", sc,
2320                      sc->device->lun);
2321
2322         mutex_lock(&session->eh_mutex);
2323         spin_lock_bh(&session->frwd_lock);
2324         /*
2325          * Just check if we are not logged in. We cannot check for
2326          * the phase because the reset could come from a ioctl.
2327          */
2328         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN)
2329                 goto unlock;
2330         conn = session->leadconn;
2331
2332         /* only have one tmf outstanding at a time */
2333         if (session->tmf_state != TMF_INITIAL)
2334                 goto unlock;
2335         session->tmf_state = TMF_QUEUED;
2336
2337         hdr = &session->tmhdr;
2338         iscsi_prep_lun_reset_pdu(sc, hdr);
2339
2340         if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age,
2341                                     session->lu_reset_timeout)) {
2342                 rc = FAILED;
2343                 goto unlock;
2344         }
2345
2346         switch (session->tmf_state) {
2347         case TMF_SUCCESS:
2348                 break;
2349         case TMF_TIMEDOUT:
2350                 spin_unlock_bh(&session->frwd_lock);
2351                 iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST);
2352                 goto done;
2353         default:
2354                 session->tmf_state = TMF_INITIAL;
2355                 goto unlock;
2356         }
2357
2358         rc = SUCCESS;
2359         spin_unlock_bh(&session->frwd_lock);
2360
2361         iscsi_suspend_tx(conn);
2362
2363         spin_lock_bh(&session->frwd_lock);
2364         memset(hdr, 0, sizeof(*hdr));
2365         fail_scsi_tasks(conn, sc->device->lun, DID_ERROR);
2366         session->tmf_state = TMF_INITIAL;
2367         spin_unlock_bh(&session->frwd_lock);
2368
2369         iscsi_start_tx(conn);
2370         goto done;
2371
2372 unlock:
2373         spin_unlock_bh(&session->frwd_lock);
2374 done:
2375         ISCSI_DBG_EH(session, "dev reset result = %s\n",
2376                      rc == SUCCESS ? "SUCCESS" : "FAILED");
2377         mutex_unlock(&session->eh_mutex);
2378         return rc;
2379 }
2380 EXPORT_SYMBOL_GPL(iscsi_eh_device_reset);
2381
2382 void iscsi_session_recovery_timedout(struct iscsi_cls_session *cls_session)
2383 {
2384         struct iscsi_session *session = cls_session->dd_data;
2385
2386         spin_lock_bh(&session->frwd_lock);
2387         if (session->state != ISCSI_STATE_LOGGED_IN) {
2388                 session->state = ISCSI_STATE_RECOVERY_FAILED;
2389                 wake_up(&session->ehwait);
2390         }
2391         spin_unlock_bh(&session->frwd_lock);
2392 }
2393 EXPORT_SYMBOL_GPL(iscsi_session_recovery_timedout);
2394
2395 /**
2396  * iscsi_eh_session_reset - drop session and attempt relogin
2397  * @sc: scsi command
2398  *
2399  * This function will wait for a relogin, session termination from
2400  * userspace, or a recovery/replacement timeout.
2401  */
2402 int iscsi_eh_session_reset(struct scsi_cmnd *sc)
2403 {
2404         struct iscsi_cls_session *cls_session;
2405         struct iscsi_session *session;
2406         struct iscsi_conn *conn;
2407
2408         cls_session = starget_to_session(scsi_target(sc->device));
2409         session = cls_session->dd_data;
2410         conn = session->leadconn;
2411
2412         mutex_lock(&session->eh_mutex);
2413         spin_lock_bh(&session->frwd_lock);
2414         if (session->state == ISCSI_STATE_TERMINATE) {
2415 failed:
2416                 ISCSI_DBG_EH(session,
2417                              "failing session reset: Could not log back into "
2418                              "%s [age %d]\n", session->targetname,
2419                              session->age);
2420                 spin_unlock_bh(&session->frwd_lock);
2421                 mutex_unlock(&session->eh_mutex);
2422                 return FAILED;
2423         }
2424
2425         spin_unlock_bh(&session->frwd_lock);
2426         mutex_unlock(&session->eh_mutex);
2427         /*
2428          * we drop the lock here but the leadconn cannot be destoyed while
2429          * we are in the scsi eh
2430          */
2431         iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST);
2432
2433         ISCSI_DBG_EH(session, "wait for relogin\n");
2434         wait_event_interruptible(session->ehwait,
2435                                  session->state == ISCSI_STATE_TERMINATE ||
2436                                  session->state == ISCSI_STATE_LOGGED_IN ||
2437                                  session->state == ISCSI_STATE_RECOVERY_FAILED);
2438         if (signal_pending(current))
2439                 flush_signals(current);
2440
2441         mutex_lock(&session->eh_mutex);
2442         spin_lock_bh(&session->frwd_lock);
2443         if (session->state == ISCSI_STATE_LOGGED_IN) {
2444                 ISCSI_DBG_EH(session,
2445                              "session reset succeeded for %s,%s\n",
2446                              session->targetname, conn->persistent_address);
2447         } else
2448                 goto failed;
2449         spin_unlock_bh(&session->frwd_lock);
2450         mutex_unlock(&session->eh_mutex);
2451         return SUCCESS;
2452 }
2453 EXPORT_SYMBOL_GPL(iscsi_eh_session_reset);
2454
2455 static void iscsi_prep_tgt_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr)
2456 {
2457         memset(hdr, 0, sizeof(*hdr));
2458         hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE;
2459         hdr->flags = ISCSI_TM_FUNC_TARGET_WARM_RESET & ISCSI_FLAG_TM_FUNC_MASK;
2460         hdr->flags |= ISCSI_FLAG_CMD_FINAL;
2461         hdr->rtt = RESERVED_ITT;
2462 }
2463
2464 /**
2465  * iscsi_eh_target_reset - reset target
2466  * @sc: scsi command
2467  *
2468  * This will attempt to send a warm target reset.
2469  */
2470 static int iscsi_eh_target_reset(struct scsi_cmnd *sc)
2471 {
2472         struct iscsi_cls_session *cls_session;
2473         struct iscsi_session *session;
2474         struct iscsi_conn *conn;
2475         struct iscsi_tm *hdr;
2476         int rc = FAILED;
2477
2478         cls_session = starget_to_session(scsi_target(sc->device));
2479         session = cls_session->dd_data;
2480
2481         ISCSI_DBG_EH(session, "tgt Reset [sc %p tgt %s]\n", sc,
2482                      session->targetname);
2483
2484         mutex_lock(&session->eh_mutex);
2485         spin_lock_bh(&session->frwd_lock);
2486         /*
2487          * Just check if we are not logged in. We cannot check for
2488          * the phase because the reset could come from a ioctl.
2489          */
2490         if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN)
2491                 goto unlock;
2492         conn = session->leadconn;
2493
2494         /* only have one tmf outstanding at a time */
2495         if (session->tmf_state != TMF_INITIAL)
2496                 goto unlock;
2497         session->tmf_state = TMF_QUEUED;
2498
2499         hdr = &session->tmhdr;
2500         iscsi_prep_tgt_reset_pdu(sc, hdr);
2501
2502         if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age,
2503                                     session->tgt_reset_timeout)) {
2504                 rc = FAILED;
2505                 goto unlock;
2506         }
2507
2508         switch (session->tmf_state) {
2509         case TMF_SUCCESS:
2510                 break;
2511         case TMF_TIMEDOUT:
2512                 spin_unlock_bh(&session->frwd_lock);
2513                 iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST);
2514                 goto done;
2515         default:
2516                 session->tmf_state = TMF_INITIAL;
2517                 goto unlock;
2518         }
2519
2520         rc = SUCCESS;
2521         spin_unlock_bh(&session->frwd_lock);
2522
2523         iscsi_suspend_tx(conn);
2524
2525         spin_lock_bh(&session->frwd_lock);
2526         memset(hdr, 0, sizeof(*hdr));
2527         fail_scsi_tasks(conn, -1, DID_ERROR);
2528         session->tmf_state = TMF_INITIAL;
2529         spin_unlock_bh(&session->frwd_lock);
2530
2531         iscsi_start_tx(conn);
2532         goto done;
2533
2534 unlock:
2535         spin_unlock_bh(&session->frwd_lock);
2536 done:
2537         ISCSI_DBG_EH(session, "tgt %s reset result = %s\n", session->targetname,
2538                      rc == SUCCESS ? "SUCCESS" : "FAILED");
2539         mutex_unlock(&session->eh_mutex);
2540         return rc;
2541 }
2542
2543 /**
2544  * iscsi_eh_recover_target - reset target and possibly the session
2545  * @sc: scsi command
2546  *
2547  * This will attempt to send a warm target reset. If that fails,
2548  * we will escalate to ERL0 session recovery.
2549  */
2550 int iscsi_eh_recover_target(struct scsi_cmnd *sc)
2551 {
2552         int rc;
2553
2554         rc = iscsi_eh_target_reset(sc);
2555         if (rc == FAILED)
2556                 rc = iscsi_eh_session_reset(sc);
2557         return rc;
2558 }
2559 EXPORT_SYMBOL_GPL(iscsi_eh_recover_target);
2560
2561 /*
2562  * Pre-allocate a pool of @max items of @item_size. By default, the pool
2563  * should be accessed via kfifo_{get,put} on q->queue.
2564  * Optionally, the caller can obtain the array of object pointers
2565  * by passing in a non-NULL @items pointer
2566  */
2567 int
2568 iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size)
2569 {
2570         int i, num_arrays = 1;
2571
2572         memset(q, 0, sizeof(*q));
2573
2574         q->max = max;
2575
2576         /* If the user passed an items pointer, he wants a copy of
2577          * the array. */
2578         if (items)
2579                 num_arrays++;
2580         q->pool = kvcalloc(num_arrays * max, sizeof(void *), GFP_KERNEL);
2581         if (q->pool == NULL)
2582                 return -ENOMEM;
2583
2584         kfifo_init(&q->queue, (void*)q->pool, max * sizeof(void*));
2585
2586         for (i = 0; i < max; i++) {
2587                 q->pool[i] = kzalloc(item_size, GFP_KERNEL);
2588                 if (q->pool[i] == NULL) {
2589                         q->max = i;
2590                         goto enomem;
2591                 }
2592                 kfifo_in(&q->queue, (void*)&q->pool[i], sizeof(void*));
2593         }
2594
2595         if (items) {
2596                 *items = q->pool + max;
2597                 memcpy(*items, q->pool, max * sizeof(void *));
2598         }
2599
2600         return 0;
2601
2602 enomem:
2603         iscsi_pool_free(q);
2604         return -ENOMEM;
2605 }
2606 EXPORT_SYMBOL_GPL(iscsi_pool_init);
2607
2608 void iscsi_pool_free(struct iscsi_pool *q)
2609 {
2610         int i;
2611
2612         for (i = 0; i < q->max; i++)
2613                 kfree(q->pool[i]);
2614         kvfree(q->pool);
2615 }
2616 EXPORT_SYMBOL_GPL(iscsi_pool_free);
2617
2618 /**
2619  * iscsi_host_add - add host to system
2620  * @shost: scsi host
2621  * @pdev: parent device
2622  *
2623  * This should be called by partial offload and software iscsi drivers
2624  * to add a host to the system.
2625  */
2626 int iscsi_host_add(struct Scsi_Host *shost, struct device *pdev)
2627 {
2628         if (!shost->can_queue)
2629                 shost->can_queue = ISCSI_DEF_XMIT_CMDS_MAX;
2630
2631         if (!shost->cmd_per_lun)
2632                 shost->cmd_per_lun = ISCSI_DEF_CMD_PER_LUN;
2633
2634         return scsi_add_host(shost, pdev);
2635 }
2636 EXPORT_SYMBOL_GPL(iscsi_host_add);
2637
2638 /**
2639  * iscsi_host_alloc - allocate a host and driver data
2640  * @sht: scsi host template
2641  * @dd_data_size: driver host data size
2642  * @xmit_can_sleep: bool indicating if LLD will queue IO from a work queue
2643  *
2644  * This should be called by partial offload and software iscsi drivers.
2645  * To access the driver specific memory use the iscsi_host_priv() macro.
2646  */
2647 struct Scsi_Host *iscsi_host_alloc(struct scsi_host_template *sht,
2648                                    int dd_data_size, bool xmit_can_sleep)
2649 {
2650         struct Scsi_Host *shost;
2651         struct iscsi_host *ihost;
2652
2653         shost = scsi_host_alloc(sht, sizeof(struct iscsi_host) + dd_data_size);
2654         if (!shost)
2655                 return NULL;
2656         ihost = shost_priv(shost);
2657
2658         if (xmit_can_sleep) {
2659                 snprintf(ihost->workq_name, sizeof(ihost->workq_name),
2660                         "iscsi_q_%d", shost->host_no);
2661                 ihost->workq = create_singlethread_workqueue(ihost->workq_name);
2662                 if (!ihost->workq)
2663                         goto free_host;
2664         }
2665
2666         spin_lock_init(&ihost->lock);
2667         ihost->state = ISCSI_HOST_SETUP;
2668         ihost->num_sessions = 0;
2669         init_waitqueue_head(&ihost->session_removal_wq);
2670         return shost;
2671
2672 free_host:
2673         scsi_host_put(shost);
2674         return NULL;
2675 }
2676 EXPORT_SYMBOL_GPL(iscsi_host_alloc);
2677
2678 static void iscsi_notify_host_removed(struct iscsi_cls_session *cls_session)
2679 {
2680         iscsi_session_failure(cls_session->dd_data, ISCSI_ERR_INVALID_HOST);
2681 }
2682
2683 /**
2684  * iscsi_host_remove - remove host and sessions
2685  * @shost: scsi host
2686  *
2687  * If there are any sessions left, this will initiate the removal and wait
2688  * for the completion.
2689  */
2690 void iscsi_host_remove(struct Scsi_Host *shost)
2691 {
2692         struct iscsi_host *ihost = shost_priv(shost);
2693         unsigned long flags;
2694
2695         spin_lock_irqsave(&ihost->lock, flags);
2696         ihost->state = ISCSI_HOST_REMOVED;
2697         spin_unlock_irqrestore(&ihost->lock, flags);
2698
2699         iscsi_host_for_each_session(shost, iscsi_notify_host_removed);
2700         wait_event_interruptible(ihost->session_removal_wq,
2701                                  ihost->num_sessions == 0);
2702         if (signal_pending(current))
2703                 flush_signals(current);
2704
2705         scsi_remove_host(shost);
2706         if (ihost->workq)
2707                 destroy_workqueue(ihost->workq);
2708 }
2709 EXPORT_SYMBOL_GPL(iscsi_host_remove);
2710
2711 void iscsi_host_free(struct Scsi_Host *shost)
2712 {
2713         struct iscsi_host *ihost = shost_priv(shost);
2714
2715         kfree(ihost->netdev);
2716         kfree(ihost->hwaddress);
2717         kfree(ihost->initiatorname);
2718         scsi_host_put(shost);
2719 }
2720 EXPORT_SYMBOL_GPL(iscsi_host_free);
2721
2722 static void iscsi_host_dec_session_cnt(struct Scsi_Host *shost)
2723 {
2724         struct iscsi_host *ihost = shost_priv(shost);
2725         unsigned long flags;
2726
2727         shost = scsi_host_get(shost);
2728         if (!shost) {
2729                 printk(KERN_ERR "Invalid state. Cannot notify host removal "
2730                       "of session teardown event because host already "
2731                       "removed.\n");
2732                 return;
2733         }
2734
2735         spin_lock_irqsave(&ihost->lock, flags);
2736         ihost->num_sessions--;
2737         if (ihost->num_sessions == 0)
2738                 wake_up(&ihost->session_removal_wq);
2739         spin_unlock_irqrestore(&ihost->lock, flags);
2740         scsi_host_put(shost);
2741 }
2742
2743 /**
2744  * iscsi_session_setup - create iscsi cls session and host and session
2745  * @iscsit: iscsi transport template
2746  * @shost: scsi host
2747  * @cmds_max: session can queue
2748  * @dd_size: private driver data size, added to session allocation size
2749  * @cmd_task_size: LLD task private data size
2750  * @initial_cmdsn: initial CmdSN
2751  * @id: target ID to add to this session
2752  *
2753  * This can be used by software iscsi_transports that allocate
2754  * a session per scsi host.
2755  *
2756  * Callers should set cmds_max to the largest total numer (mgmt + scsi) of
2757  * tasks they support. The iscsi layer reserves ISCSI_MGMT_CMDS_MAX tasks
2758  * for nop handling and login/logout requests.
2759  */
2760 struct iscsi_cls_session *
2761 iscsi_session_setup(struct iscsi_transport *iscsit, struct Scsi_Host *shost,
2762                     uint16_t cmds_max, int dd_size, int cmd_task_size,
2763                     uint32_t initial_cmdsn, unsigned int id)
2764 {
2765         struct iscsi_host *ihost = shost_priv(shost);
2766         struct iscsi_session *session;
2767         struct iscsi_cls_session *cls_session;
2768         int cmd_i, scsi_cmds, total_cmds = cmds_max;
2769         unsigned long flags;
2770
2771         spin_lock_irqsave(&ihost->lock, flags);
2772         if (ihost->state == ISCSI_HOST_REMOVED) {
2773                 spin_unlock_irqrestore(&ihost->lock, flags);
2774                 return NULL;
2775         }
2776         ihost->num_sessions++;
2777         spin_unlock_irqrestore(&ihost->lock, flags);
2778
2779         if (!total_cmds)
2780                 total_cmds = ISCSI_DEF_XMIT_CMDS_MAX;
2781         /*
2782          * The iscsi layer needs some tasks for nop handling and tmfs,
2783          * so the cmds_max must at least be greater than ISCSI_MGMT_CMDS_MAX
2784          * + 1 command for scsi IO.
2785          */
2786         if (total_cmds < ISCSI_TOTAL_CMDS_MIN) {
2787                 printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2788                        "must be a power of two that is at least %d.\n",
2789                        total_cmds, ISCSI_TOTAL_CMDS_MIN);
2790                 goto dec_session_count;
2791         }
2792
2793         if (total_cmds > ISCSI_TOTAL_CMDS_MAX) {
2794                 printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2795                        "must be a power of 2 less than or equal to %d.\n",
2796                        cmds_max, ISCSI_TOTAL_CMDS_MAX);
2797                 total_cmds = ISCSI_TOTAL_CMDS_MAX;
2798         }
2799
2800         if (!is_power_of_2(total_cmds)) {
2801                 printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue "
2802                        "must be a power of 2.\n", total_cmds);
2803                 total_cmds = rounddown_pow_of_two(total_cmds);
2804                 if (total_cmds < ISCSI_TOTAL_CMDS_MIN)
2805                         return NULL;
2806                 printk(KERN_INFO "iscsi: Rounding can_queue to %d.\n",
2807                        total_cmds);
2808         }
2809         scsi_cmds = total_cmds - ISCSI_MGMT_CMDS_MAX;
2810
2811         cls_session = iscsi_alloc_session(shost, iscsit,
2812                                           sizeof(struct iscsi_session) +
2813                                           dd_size);
2814         if (!cls_session)
2815                 goto dec_session_count;
2816         session = cls_session->dd_data;
2817         session->cls_session = cls_session;
2818         session->host = shost;
2819         session->state = ISCSI_STATE_FREE;
2820         session->fast_abort = 1;
2821         session->tgt_reset_timeout = 30;
2822         session->lu_reset_timeout = 15;
2823         session->abort_timeout = 10;
2824         session->scsi_cmds_max = scsi_cmds;
2825         session->cmds_max = total_cmds;
2826         session->queued_cmdsn = session->cmdsn = initial_cmdsn;
2827         session->exp_cmdsn = initial_cmdsn + 1;
2828         session->max_cmdsn = initial_cmdsn + 1;
2829         session->max_r2t = 1;
2830         session->tt = iscsit;
2831         session->dd_data = cls_session->dd_data + sizeof(*session);
2832
2833         session->tmf_state = TMF_INITIAL;
2834         timer_setup(&session->tmf_timer, iscsi_tmf_timedout, 0);
2835         mutex_init(&session->eh_mutex);
2836
2837         spin_lock_init(&session->frwd_lock);
2838         spin_lock_init(&session->back_lock);
2839
2840         /* initialize SCSI PDU commands pool */
2841         if (iscsi_pool_init(&session->cmdpool, session->cmds_max,
2842                             (void***)&session->cmds,
2843                             cmd_task_size + sizeof(struct iscsi_task)))
2844                 goto cmdpool_alloc_fail;
2845
2846         /* pre-format cmds pool with ITT */
2847         for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) {
2848                 struct iscsi_task *task = session->cmds[cmd_i];
2849
2850                 if (cmd_task_size)
2851                         task->dd_data = &task[1];
2852                 task->itt = cmd_i;
2853                 task->state = ISCSI_TASK_FREE;
2854                 INIT_LIST_HEAD(&task->running);
2855         }
2856
2857         if (!try_module_get(iscsit->owner))
2858                 goto module_get_fail;
2859
2860         if (iscsi_add_session(cls_session, id))
2861                 goto cls_session_fail;
2862
2863         return cls_session;
2864
2865 cls_session_fail:
2866         module_put(iscsit->owner);
2867 module_get_fail:
2868         iscsi_pool_free(&session->cmdpool);
2869 cmdpool_alloc_fail:
2870         iscsi_free_session(cls_session);
2871 dec_session_count:
2872         iscsi_host_dec_session_cnt(shost);
2873         return NULL;
2874 }
2875 EXPORT_SYMBOL_GPL(iscsi_session_setup);
2876
2877 /**
2878  * iscsi_session_teardown - destroy session, host, and cls_session
2879  * @cls_session: iscsi session
2880  */
2881 void iscsi_session_teardown(struct iscsi_cls_session *cls_session)
2882 {
2883         struct iscsi_session *session = cls_session->dd_data;
2884         struct module *owner = cls_session->transport->owner;
2885         struct Scsi_Host *shost = session->host;
2886
2887         iscsi_pool_free(&session->cmdpool);
2888
2889         iscsi_remove_session(cls_session);
2890
2891         kfree(session->password);
2892         kfree(session->password_in);
2893         kfree(session->username);
2894         kfree(session->username_in);
2895         kfree(session->targetname);
2896         kfree(session->targetalias);
2897         kfree(session->initiatorname);
2898         kfree(session->boot_root);
2899         kfree(session->boot_nic);
2900         kfree(session->boot_target);
2901         kfree(session->ifacename);
2902         kfree(session->portal_type);
2903         kfree(session->discovery_parent_type);
2904
2905         iscsi_free_session(cls_session);
2906
2907         iscsi_host_dec_session_cnt(shost);
2908         module_put(owner);
2909 }
2910 EXPORT_SYMBOL_GPL(iscsi_session_teardown);
2911
2912 /**
2913  * iscsi_conn_setup - create iscsi_cls_conn and iscsi_conn
2914  * @cls_session: iscsi_cls_session
2915  * @dd_size: private driver data size
2916  * @conn_idx: cid
2917  */
2918 struct iscsi_cls_conn *
2919 iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size,
2920                  uint32_t conn_idx)
2921 {
2922         struct iscsi_session *session = cls_session->dd_data;
2923         struct iscsi_conn *conn;
2924         struct iscsi_cls_conn *cls_conn;
2925         char *data;
2926
2927         cls_conn = iscsi_create_conn(cls_session, sizeof(*conn) + dd_size,
2928                                      conn_idx);
2929         if (!cls_conn)
2930                 return NULL;
2931         conn = cls_conn->dd_data;
2932         memset(conn, 0, sizeof(*conn) + dd_size);
2933
2934         conn->dd_data = cls_conn->dd_data + sizeof(*conn);
2935         conn->session = session;
2936         conn->cls_conn = cls_conn;
2937         conn->c_stage = ISCSI_CONN_INITIAL_STAGE;
2938         conn->id = conn_idx;
2939         conn->exp_statsn = 0;
2940
2941         timer_setup(&conn->transport_timer, iscsi_check_transport_timeouts, 0);
2942
2943         INIT_LIST_HEAD(&conn->mgmtqueue);
2944         INIT_LIST_HEAD(&conn->cmdqueue);
2945         INIT_LIST_HEAD(&conn->requeue);
2946         spin_lock_init(&conn->taskqueuelock);
2947         INIT_WORK(&conn->xmitwork, iscsi_xmitworker);
2948
2949         /* allocate login_task used for the login/text sequences */
2950         spin_lock_bh(&session->frwd_lock);
2951         if (!kfifo_out(&session->cmdpool.queue,
2952                          (void*)&conn->login_task,
2953                          sizeof(void*))) {
2954                 spin_unlock_bh(&session->frwd_lock);
2955                 goto login_task_alloc_fail;
2956         }
2957         spin_unlock_bh(&session->frwd_lock);
2958
2959         data = (char *) __get_free_pages(GFP_KERNEL,
2960                                          get_order(ISCSI_DEF_MAX_RECV_SEG_LEN));
2961         if (!data)
2962                 goto login_task_data_alloc_fail;
2963         conn->login_task->data = conn->data = data;
2964
2965         init_waitqueue_head(&session->ehwait);
2966
2967         return cls_conn;
2968
2969 login_task_data_alloc_fail:
2970         kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task,
2971                     sizeof(void*));
2972 login_task_alloc_fail:
2973         iscsi_destroy_conn(cls_conn);
2974         return NULL;
2975 }
2976 EXPORT_SYMBOL_GPL(iscsi_conn_setup);
2977
2978 /**
2979  * iscsi_conn_teardown - teardown iscsi connection
2980  * @cls_conn: iscsi class connection
2981  *
2982  * TODO: we may need to make this into a two step process
2983  * like scsi-mls remove + put host
2984  */
2985 void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn)
2986 {
2987         struct iscsi_conn *conn = cls_conn->dd_data;
2988         struct iscsi_session *session = conn->session;
2989         char *tmp_persistent_address = conn->persistent_address;
2990         char *tmp_local_ipaddr = conn->local_ipaddr;
2991
2992         del_timer_sync(&conn->transport_timer);
2993
2994         mutex_lock(&session->eh_mutex);
2995         spin_lock_bh(&session->frwd_lock);
2996         conn->c_stage = ISCSI_CONN_CLEANUP_WAIT;
2997         if (session->leadconn == conn) {
2998                 /*
2999                  * leading connection? then give up on recovery.
3000                  */
3001                 session->state = ISCSI_STATE_TERMINATE;
3002                 wake_up(&session->ehwait);
3003         }
3004         spin_unlock_bh(&session->frwd_lock);
3005
3006         /* flush queued up work because we free the connection below */
3007         iscsi_suspend_tx(conn);
3008
3009         spin_lock_bh(&session->frwd_lock);
3010         free_pages((unsigned long) conn->data,
3011                    get_order(ISCSI_DEF_MAX_RECV_SEG_LEN));
3012         /* regular RX path uses back_lock */
3013         spin_lock_bh(&session->back_lock);
3014         kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task,
3015                     sizeof(void*));
3016         spin_unlock_bh(&session->back_lock);
3017         if (session->leadconn == conn)
3018                 session->leadconn = NULL;
3019         spin_unlock_bh(&session->frwd_lock);
3020         mutex_unlock(&session->eh_mutex);
3021
3022         iscsi_destroy_conn(cls_conn);
3023         kfree(tmp_persistent_address);
3024         kfree(tmp_local_ipaddr);
3025 }
3026 EXPORT_SYMBOL_GPL(iscsi_conn_teardown);
3027
3028 int iscsi_conn_start(struct iscsi_cls_conn *cls_conn)
3029 {
3030         struct iscsi_conn *conn = cls_conn->dd_data;
3031         struct iscsi_session *session = conn->session;
3032
3033         if (!session) {
3034                 iscsi_conn_printk(KERN_ERR, conn,
3035                                   "can't start unbound connection\n");
3036                 return -EPERM;
3037         }
3038
3039         if ((session->imm_data_en || !session->initial_r2t_en) &&
3040              session->first_burst > session->max_burst) {
3041                 iscsi_conn_printk(KERN_INFO, conn, "invalid burst lengths: "
3042                                   "first_burst %d max_burst %d\n",
3043                                   session->first_burst, session->max_burst);
3044                 return -EINVAL;
3045         }
3046
3047         if (conn->ping_timeout && !conn->recv_timeout) {
3048                 iscsi_conn_printk(KERN_ERR, conn, "invalid recv timeout of "
3049                                   "zero. Using 5 seconds\n.");
3050                 conn->recv_timeout = 5;
3051         }
3052
3053         if (conn->recv_timeout && !conn->ping_timeout) {
3054                 iscsi_conn_printk(KERN_ERR, conn, "invalid ping timeout of "
3055                                   "zero. Using 5 seconds.\n");
3056                 conn->ping_timeout = 5;
3057         }
3058
3059         spin_lock_bh(&session->frwd_lock);
3060         conn->c_stage = ISCSI_CONN_STARTED;
3061         session->state = ISCSI_STATE_LOGGED_IN;
3062         session->queued_cmdsn = session->cmdsn;
3063
3064         conn->last_recv = jiffies;
3065         conn->last_ping = jiffies;
3066         if (conn->recv_timeout && conn->ping_timeout)
3067                 mod_timer(&conn->transport_timer,
3068                           jiffies + (conn->recv_timeout * HZ));
3069
3070         switch(conn->stop_stage) {
3071         case STOP_CONN_RECOVER:
3072                 /*
3073                  * unblock eh_abort() if it is blocked. re-try all
3074                  * commands after successful recovery
3075                  */
3076                 conn->stop_stage = 0;
3077                 session->tmf_state = TMF_INITIAL;
3078                 session->age++;
3079                 if (session->age == 16)
3080                         session->age = 0;
3081                 break;
3082         case STOP_CONN_TERM:
3083                 conn->stop_stage = 0;
3084                 break;
3085         default:
3086                 break;
3087         }
3088         spin_unlock_bh(&session->frwd_lock);
3089
3090         iscsi_unblock_session(session->cls_session);
3091         wake_up(&session->ehwait);
3092         return 0;
3093 }
3094 EXPORT_SYMBOL_GPL(iscsi_conn_start);
3095
3096 static void
3097 fail_mgmt_tasks(struct iscsi_session *session, struct iscsi_conn *conn)
3098 {
3099         struct iscsi_task *task;
3100         int i, state;
3101
3102         for (i = 0; i < conn->session->cmds_max; i++) {
3103                 task = conn->session->cmds[i];
3104                 if (task->sc)
3105                         continue;
3106
3107                 if (task->state == ISCSI_TASK_FREE)
3108                         continue;
3109
3110                 ISCSI_DBG_SESSION(conn->session,
3111                                   "failing mgmt itt 0x%x state %d\n",
3112                                   task->itt, task->state);
3113                 state = ISCSI_TASK_ABRT_SESS_RECOV;
3114                 if (task->state == ISCSI_TASK_PENDING)
3115                         state = ISCSI_TASK_COMPLETED;
3116                 iscsi_complete_task(task, state);
3117
3118         }
3119 }
3120
3121 static void iscsi_start_session_recovery(struct iscsi_session *session,
3122                                          struct iscsi_conn *conn, int flag)
3123 {
3124         int old_stop_stage;
3125
3126         mutex_lock(&session->eh_mutex);
3127         spin_lock_bh(&session->frwd_lock);
3128         if (conn->stop_stage == STOP_CONN_TERM) {
3129                 spin_unlock_bh(&session->frwd_lock);
3130                 mutex_unlock(&session->eh_mutex);
3131                 return;
3132         }
3133
3134         /*
3135          * When this is called for the in_login state, we only want to clean
3136          * up the login task and connection. We do not need to block and set
3137          * the recovery state again
3138          */
3139         if (flag == STOP_CONN_TERM)
3140                 session->state = ISCSI_STATE_TERMINATE;
3141         else if (conn->stop_stage != STOP_CONN_RECOVER)
3142                 session->state = ISCSI_STATE_IN_RECOVERY;
3143
3144         old_stop_stage = conn->stop_stage;
3145         conn->stop_stage = flag;
3146         spin_unlock_bh(&session->frwd_lock);
3147
3148         del_timer_sync(&conn->transport_timer);
3149         iscsi_suspend_tx(conn);
3150
3151         spin_lock_bh(&session->frwd_lock);
3152         conn->c_stage = ISCSI_CONN_STOPPED;
3153         spin_unlock_bh(&session->frwd_lock);
3154
3155         /*
3156          * for connection level recovery we should not calculate
3157          * header digest. conn->hdr_size used for optimization
3158          * in hdr_extract() and will be re-negotiated at
3159          * set_param() time.
3160          */
3161         if (flag == STOP_CONN_RECOVER) {
3162                 conn->hdrdgst_en = 0;
3163                 conn->datadgst_en = 0;
3164                 if (session->state == ISCSI_STATE_IN_RECOVERY &&
3165                     old_stop_stage != STOP_CONN_RECOVER) {
3166                         ISCSI_DBG_SESSION(session, "blocking session\n");
3167                         iscsi_block_session(session->cls_session);
3168                 }
3169         }
3170
3171         /*
3172          * flush queues.
3173          */
3174         spin_lock_bh(&session->frwd_lock);
3175         fail_scsi_tasks(conn, -1, DID_TRANSPORT_DISRUPTED);
3176         fail_mgmt_tasks(session, conn);
3177         memset(&session->tmhdr, 0, sizeof(session->tmhdr));
3178         spin_unlock_bh(&session->frwd_lock);
3179         mutex_unlock(&session->eh_mutex);
3180 }
3181
3182 void iscsi_conn_stop(struct iscsi_cls_conn *cls_conn, int flag)
3183 {
3184         struct iscsi_conn *conn = cls_conn->dd_data;
3185         struct iscsi_session *session = conn->session;
3186
3187         switch (flag) {
3188         case STOP_CONN_RECOVER:
3189         case STOP_CONN_TERM:
3190                 iscsi_start_session_recovery(session, conn, flag);
3191                 break;
3192         default:
3193                 iscsi_conn_printk(KERN_ERR, conn,
3194                                   "invalid stop flag %d\n", flag);
3195         }
3196 }
3197 EXPORT_SYMBOL_GPL(iscsi_conn_stop);
3198
3199 int iscsi_conn_bind(struct iscsi_cls_session *cls_session,
3200                     struct iscsi_cls_conn *cls_conn, int is_leading)
3201 {
3202         struct iscsi_session *session = cls_session->dd_data;
3203         struct iscsi_conn *conn = cls_conn->dd_data;
3204
3205         spin_lock_bh(&session->frwd_lock);
3206         if (is_leading)
3207                 session->leadconn = conn;
3208         spin_unlock_bh(&session->frwd_lock);
3209
3210         /*
3211          * Unblock xmitworker(), Login Phase will pass through.
3212          */
3213         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx);
3214         clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx);
3215         return 0;
3216 }
3217 EXPORT_SYMBOL_GPL(iscsi_conn_bind);
3218
3219 int iscsi_switch_str_param(char **param, char *new_val_buf)
3220 {
3221         char *new_val;
3222
3223         if (*param) {
3224                 if (!strcmp(*param, new_val_buf))
3225                         return 0;
3226         }
3227
3228         new_val = kstrdup(new_val_buf, GFP_NOIO);
3229         if (!new_val)
3230                 return -ENOMEM;
3231
3232         kfree(*param);
3233         *param = new_val;
3234         return 0;
3235 }
3236 EXPORT_SYMBOL_GPL(iscsi_switch_str_param);
3237
3238 int iscsi_set_param(struct iscsi_cls_conn *cls_conn,
3239                     enum iscsi_param param, char *buf, int buflen)
3240 {
3241         struct iscsi_conn *conn = cls_conn->dd_data;
3242         struct iscsi_session *session = conn->session;
3243         int val;
3244
3245         switch(param) {
3246         case ISCSI_PARAM_FAST_ABORT:
3247                 sscanf(buf, "%d", &session->fast_abort);
3248                 break;
3249         case ISCSI_PARAM_ABORT_TMO:
3250                 sscanf(buf, "%d", &session->abort_timeout);
3251                 break;
3252         case ISCSI_PARAM_LU_RESET_TMO:
3253                 sscanf(buf, "%d", &session->lu_reset_timeout);
3254                 break;
3255         case ISCSI_PARAM_TGT_RESET_TMO:
3256                 sscanf(buf, "%d", &session->tgt_reset_timeout);
3257                 break;
3258         case ISCSI_PARAM_PING_TMO:
3259                 sscanf(buf, "%d", &conn->ping_timeout);
3260                 break;
3261         case ISCSI_PARAM_RECV_TMO:
3262                 sscanf(buf, "%d", &conn->recv_timeout);
3263                 break;
3264         case ISCSI_PARAM_MAX_RECV_DLENGTH:
3265                 sscanf(buf, "%d", &conn->max_recv_dlength);
3266                 break;
3267         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
3268                 sscanf(buf, "%d", &conn->max_xmit_dlength);
3269                 break;
3270         case ISCSI_PARAM_HDRDGST_EN:
3271                 sscanf(buf, "%d", &conn->hdrdgst_en);
3272                 break;
3273         case ISCSI_PARAM_DATADGST_EN:
3274                 sscanf(buf, "%d", &conn->datadgst_en);
3275                 break;
3276         case ISCSI_PARAM_INITIAL_R2T_EN:
3277                 sscanf(buf, "%d", &session->initial_r2t_en);
3278                 break;
3279         case ISCSI_PARAM_MAX_R2T:
3280                 sscanf(buf, "%hu", &session->max_r2t);
3281                 break;
3282         case ISCSI_PARAM_IMM_DATA_EN:
3283                 sscanf(buf, "%d", &session->imm_data_en);
3284                 break;
3285         case ISCSI_PARAM_FIRST_BURST:
3286                 sscanf(buf, "%d", &session->first_burst);
3287                 break;
3288         case ISCSI_PARAM_MAX_BURST:
3289                 sscanf(buf, "%d", &session->max_burst);
3290                 break;
3291         case ISCSI_PARAM_PDU_INORDER_EN:
3292                 sscanf(buf, "%d", &session->pdu_inorder_en);
3293                 break;
3294         case ISCSI_PARAM_DATASEQ_INORDER_EN:
3295                 sscanf(buf, "%d", &session->dataseq_inorder_en);
3296                 break;
3297         case ISCSI_PARAM_ERL:
3298                 sscanf(buf, "%d", &session->erl);
3299                 break;
3300         case ISCSI_PARAM_EXP_STATSN:
3301                 sscanf(buf, "%u", &conn->exp_statsn);
3302                 break;
3303         case ISCSI_PARAM_USERNAME:
3304                 return iscsi_switch_str_param(&session->username, buf);
3305         case ISCSI_PARAM_USERNAME_IN:
3306                 return iscsi_switch_str_param(&session->username_in, buf);
3307         case ISCSI_PARAM_PASSWORD:
3308                 return iscsi_switch_str_param(&session->password, buf);
3309         case ISCSI_PARAM_PASSWORD_IN:
3310                 return iscsi_switch_str_param(&session->password_in, buf);
3311         case ISCSI_PARAM_TARGET_NAME:
3312                 return iscsi_switch_str_param(&session->targetname, buf);
3313         case ISCSI_PARAM_TARGET_ALIAS:
3314                 return iscsi_switch_str_param(&session->targetalias, buf);
3315         case ISCSI_PARAM_TPGT:
3316                 sscanf(buf, "%d", &session->tpgt);
3317                 break;
3318         case ISCSI_PARAM_PERSISTENT_PORT:
3319                 sscanf(buf, "%d", &conn->persistent_port);
3320                 break;
3321         case ISCSI_PARAM_PERSISTENT_ADDRESS:
3322                 return iscsi_switch_str_param(&conn->persistent_address, buf);
3323         case ISCSI_PARAM_IFACE_NAME:
3324                 return iscsi_switch_str_param(&session->ifacename, buf);
3325         case ISCSI_PARAM_INITIATOR_NAME:
3326                 return iscsi_switch_str_param(&session->initiatorname, buf);
3327         case ISCSI_PARAM_BOOT_ROOT:
3328                 return iscsi_switch_str_param(&session->boot_root, buf);
3329         case ISCSI_PARAM_BOOT_NIC:
3330                 return iscsi_switch_str_param(&session->boot_nic, buf);
3331         case ISCSI_PARAM_BOOT_TARGET:
3332                 return iscsi_switch_str_param(&session->boot_target, buf);
3333         case ISCSI_PARAM_PORTAL_TYPE:
3334                 return iscsi_switch_str_param(&session->portal_type, buf);
3335         case ISCSI_PARAM_DISCOVERY_PARENT_TYPE:
3336                 return iscsi_switch_str_param(&session->discovery_parent_type,
3337                                               buf);
3338         case ISCSI_PARAM_DISCOVERY_SESS:
3339                 sscanf(buf, "%d", &val);
3340                 session->discovery_sess = !!val;
3341                 break;
3342         case ISCSI_PARAM_LOCAL_IPADDR:
3343                 return iscsi_switch_str_param(&conn->local_ipaddr, buf);
3344         default:
3345                 return -ENOSYS;
3346         }
3347
3348         return 0;
3349 }
3350 EXPORT_SYMBOL_GPL(iscsi_set_param);
3351
3352 int iscsi_session_get_param(struct iscsi_cls_session *cls_session,
3353                             enum iscsi_param param, char *buf)
3354 {
3355         struct iscsi_session *session = cls_session->dd_data;
3356         int len;
3357
3358         switch(param) {
3359         case ISCSI_PARAM_FAST_ABORT:
3360                 len = sysfs_emit(buf, "%d\n", session->fast_abort);
3361                 break;
3362         case ISCSI_PARAM_ABORT_TMO:
3363                 len = sysfs_emit(buf, "%d\n", session->abort_timeout);
3364                 break;
3365         case ISCSI_PARAM_LU_RESET_TMO:
3366                 len = sysfs_emit(buf, "%d\n", session->lu_reset_timeout);
3367                 break;
3368         case ISCSI_PARAM_TGT_RESET_TMO:
3369                 len = sysfs_emit(buf, "%d\n", session->tgt_reset_timeout);
3370                 break;
3371         case ISCSI_PARAM_INITIAL_R2T_EN:
3372                 len = sysfs_emit(buf, "%d\n", session->initial_r2t_en);
3373                 break;
3374         case ISCSI_PARAM_MAX_R2T:
3375                 len = sysfs_emit(buf, "%hu\n", session->max_r2t);
3376                 break;
3377         case ISCSI_PARAM_IMM_DATA_EN:
3378                 len = sysfs_emit(buf, "%d\n", session->imm_data_en);
3379                 break;
3380         case ISCSI_PARAM_FIRST_BURST:
3381                 len = sysfs_emit(buf, "%u\n", session->first_burst);
3382                 break;
3383         case ISCSI_PARAM_MAX_BURST:
3384                 len = sysfs_emit(buf, "%u\n", session->max_burst);
3385                 break;
3386         case ISCSI_PARAM_PDU_INORDER_EN:
3387                 len = sysfs_emit(buf, "%d\n", session->pdu_inorder_en);
3388                 break;
3389         case ISCSI_PARAM_DATASEQ_INORDER_EN:
3390                 len = sysfs_emit(buf, "%d\n", session->dataseq_inorder_en);
3391                 break;
3392         case ISCSI_PARAM_DEF_TASKMGMT_TMO:
3393                 len = sysfs_emit(buf, "%d\n", session->def_taskmgmt_tmo);
3394                 break;
3395         case ISCSI_PARAM_ERL:
3396                 len = sysfs_emit(buf, "%d\n", session->erl);
3397                 break;
3398         case ISCSI_PARAM_TARGET_NAME:
3399                 len = sysfs_emit(buf, "%s\n", session->targetname);
3400                 break;
3401         case ISCSI_PARAM_TARGET_ALIAS:
3402                 len = sysfs_emit(buf, "%s\n", session->targetalias);
3403                 break;
3404         case ISCSI_PARAM_TPGT:
3405                 len = sysfs_emit(buf, "%d\n", session->tpgt);
3406                 break;
3407         case ISCSI_PARAM_USERNAME:
3408                 len = sysfs_emit(buf, "%s\n", session->username);
3409                 break;
3410         case ISCSI_PARAM_USERNAME_IN:
3411                 len = sysfs_emit(buf, "%s\n", session->username_in);
3412                 break;
3413         case ISCSI_PARAM_PASSWORD:
3414                 len = sysfs_emit(buf, "%s\n", session->password);
3415                 break;
3416         case ISCSI_PARAM_PASSWORD_IN:
3417                 len = sysfs_emit(buf, "%s\n", session->password_in);
3418                 break;
3419         case ISCSI_PARAM_IFACE_NAME:
3420                 len = sysfs_emit(buf, "%s\n", session->ifacename);
3421                 break;
3422         case ISCSI_PARAM_INITIATOR_NAME:
3423                 len = sysfs_emit(buf, "%s\n", session->initiatorname);
3424                 break;
3425         case ISCSI_PARAM_BOOT_ROOT:
3426                 len = sysfs_emit(buf, "%s\n", session->boot_root);
3427                 break;
3428         case ISCSI_PARAM_BOOT_NIC:
3429                 len = sysfs_emit(buf, "%s\n", session->boot_nic);
3430                 break;
3431         case ISCSI_PARAM_BOOT_TARGET:
3432                 len = sysfs_emit(buf, "%s\n", session->boot_target);
3433                 break;
3434         case ISCSI_PARAM_AUTO_SND_TGT_DISABLE:
3435                 len = sysfs_emit(buf, "%u\n", session->auto_snd_tgt_disable);
3436                 break;
3437         case ISCSI_PARAM_DISCOVERY_SESS:
3438                 len = sysfs_emit(buf, "%u\n", session->discovery_sess);
3439                 break;
3440         case ISCSI_PARAM_PORTAL_TYPE:
3441                 len = sysfs_emit(buf, "%s\n", session->portal_type);
3442                 break;
3443         case ISCSI_PARAM_CHAP_AUTH_EN:
3444                 len = sysfs_emit(buf, "%u\n", session->chap_auth_en);
3445                 break;
3446         case ISCSI_PARAM_DISCOVERY_LOGOUT_EN:
3447                 len = sysfs_emit(buf, "%u\n", session->discovery_logout_en);
3448                 break;
3449         case ISCSI_PARAM_BIDI_CHAP_EN:
3450                 len = sysfs_emit(buf, "%u\n", session->bidi_chap_en);
3451                 break;
3452         case ISCSI_PARAM_DISCOVERY_AUTH_OPTIONAL:
3453                 len = sysfs_emit(buf, "%u\n", session->discovery_auth_optional);
3454                 break;
3455         case ISCSI_PARAM_DEF_TIME2WAIT:
3456                 len = sysfs_emit(buf, "%d\n", session->time2wait);
3457                 break;
3458         case ISCSI_PARAM_DEF_TIME2RETAIN:
3459                 len = sysfs_emit(buf, "%d\n", session->time2retain);
3460                 break;
3461         case ISCSI_PARAM_TSID:
3462                 len = sysfs_emit(buf, "%u\n", session->tsid);
3463                 break;
3464         case ISCSI_PARAM_ISID:
3465                 len = sysfs_emit(buf, "%02x%02x%02x%02x%02x%02x\n",
3466                               session->isid[0], session->isid[1],
3467                               session->isid[2], session->isid[3],
3468                               session->isid[4], session->isid[5]);
3469                 break;
3470         case ISCSI_PARAM_DISCOVERY_PARENT_IDX:
3471                 len = sysfs_emit(buf, "%u\n", session->discovery_parent_idx);
3472                 break;
3473         case ISCSI_PARAM_DISCOVERY_PARENT_TYPE:
3474                 if (session->discovery_parent_type)
3475                         len = sysfs_emit(buf, "%s\n",
3476                                       session->discovery_parent_type);
3477                 else
3478                         len = sysfs_emit(buf, "\n");
3479                 break;
3480         default:
3481                 return -ENOSYS;
3482         }
3483
3484         return len;
3485 }
3486 EXPORT_SYMBOL_GPL(iscsi_session_get_param);
3487
3488 int iscsi_conn_get_addr_param(struct sockaddr_storage *addr,
3489                               enum iscsi_param param, char *buf)
3490 {
3491         struct sockaddr_in6 *sin6 = NULL;
3492         struct sockaddr_in *sin = NULL;
3493         int len;
3494
3495         switch (addr->ss_family) {
3496         case AF_INET:
3497                 sin = (struct sockaddr_in *)addr;
3498                 break;
3499         case AF_INET6:
3500                 sin6 = (struct sockaddr_in6 *)addr;
3501                 break;
3502         default:
3503                 return -EINVAL;
3504         }
3505
3506         switch (param) {
3507         case ISCSI_PARAM_CONN_ADDRESS:
3508         case ISCSI_HOST_PARAM_IPADDRESS:
3509                 if (sin)
3510                         len = sysfs_emit(buf, "%pI4\n", &sin->sin_addr.s_addr);
3511                 else
3512                         len = sysfs_emit(buf, "%pI6\n", &sin6->sin6_addr);
3513                 break;
3514         case ISCSI_PARAM_CONN_PORT:
3515         case ISCSI_PARAM_LOCAL_PORT:
3516                 if (sin)
3517                         len = sysfs_emit(buf, "%hu\n", be16_to_cpu(sin->sin_port));
3518                 else
3519                         len = sysfs_emit(buf, "%hu\n",
3520                                       be16_to_cpu(sin6->sin6_port));
3521                 break;
3522         default:
3523                 return -EINVAL;
3524         }
3525
3526         return len;
3527 }
3528 EXPORT_SYMBOL_GPL(iscsi_conn_get_addr_param);
3529
3530 int iscsi_conn_get_param(struct iscsi_cls_conn *cls_conn,
3531                          enum iscsi_param param, char *buf)
3532 {
3533         struct iscsi_conn *conn = cls_conn->dd_data;
3534         int len;
3535
3536         switch(param) {
3537         case ISCSI_PARAM_PING_TMO:
3538                 len = sysfs_emit(buf, "%u\n", conn->ping_timeout);
3539                 break;
3540         case ISCSI_PARAM_RECV_TMO:
3541                 len = sysfs_emit(buf, "%u\n", conn->recv_timeout);
3542                 break;
3543         case ISCSI_PARAM_MAX_RECV_DLENGTH:
3544                 len = sysfs_emit(buf, "%u\n", conn->max_recv_dlength);
3545                 break;
3546         case ISCSI_PARAM_MAX_XMIT_DLENGTH:
3547                 len = sysfs_emit(buf, "%u\n", conn->max_xmit_dlength);
3548                 break;
3549         case ISCSI_PARAM_HDRDGST_EN:
3550                 len = sysfs_emit(buf, "%d\n", conn->hdrdgst_en);
3551                 break;
3552         case ISCSI_PARAM_DATADGST_EN:
3553                 len = sysfs_emit(buf, "%d\n", conn->datadgst_en);
3554                 break;
3555         case ISCSI_PARAM_IFMARKER_EN:
3556                 len = sysfs_emit(buf, "%d\n", conn->ifmarker_en);
3557                 break;
3558         case ISCSI_PARAM_OFMARKER_EN:
3559                 len = sysfs_emit(buf, "%d\n", conn->ofmarker_en);
3560                 break;
3561         case ISCSI_PARAM_EXP_STATSN:
3562                 len = sysfs_emit(buf, "%u\n", conn->exp_statsn);
3563                 break;
3564         case ISCSI_PARAM_PERSISTENT_PORT:
3565                 len = sysfs_emit(buf, "%d\n", conn->persistent_port);
3566                 break;
3567         case ISCSI_PARAM_PERSISTENT_ADDRESS:
3568                 len = sysfs_emit(buf, "%s\n", conn->persistent_address);
3569                 break;
3570         case ISCSI_PARAM_STATSN:
3571                 len = sysfs_emit(buf, "%u\n", conn->statsn);
3572                 break;
3573         case ISCSI_PARAM_MAX_SEGMENT_SIZE:
3574                 len = sysfs_emit(buf, "%u\n", conn->max_segment_size);
3575                 break;
3576         case ISCSI_PARAM_KEEPALIVE_TMO:
3577                 len = sysfs_emit(buf, "%u\n", conn->keepalive_tmo);
3578                 break;
3579         case ISCSI_PARAM_LOCAL_PORT:
3580                 len = sysfs_emit(buf, "%u\n", conn->local_port);
3581                 break;
3582         case ISCSI_PARAM_TCP_TIMESTAMP_STAT:
3583                 len = sysfs_emit(buf, "%u\n", conn->tcp_timestamp_stat);
3584                 break;
3585         case ISCSI_PARAM_TCP_NAGLE_DISABLE:
3586                 len = sysfs_emit(buf, "%u\n", conn->tcp_nagle_disable);
3587                 break;
3588         case ISCSI_PARAM_TCP_WSF_DISABLE:
3589                 len = sysfs_emit(buf, "%u\n", conn->tcp_wsf_disable);
3590                 break;
3591         case ISCSI_PARAM_TCP_TIMER_SCALE:
3592                 len = sysfs_emit(buf, "%u\n", conn->tcp_timer_scale);
3593                 break;
3594         case ISCSI_PARAM_TCP_TIMESTAMP_EN:
3595                 len = sysfs_emit(buf, "%u\n", conn->tcp_timestamp_en);
3596                 break;
3597         case ISCSI_PARAM_IP_FRAGMENT_DISABLE:
3598                 len = sysfs_emit(buf, "%u\n", conn->fragment_disable);
3599                 break;
3600         case ISCSI_PARAM_IPV4_TOS:
3601                 len = sysfs_emit(buf, "%u\n", conn->ipv4_tos);
3602                 break;
3603         case ISCSI_PARAM_IPV6_TC:
3604                 len = sysfs_emit(buf, "%u\n", conn->ipv6_traffic_class);
3605                 break;
3606         case ISCSI_PARAM_IPV6_FLOW_LABEL:
3607                 len = sysfs_emit(buf, "%u\n", conn->ipv6_flow_label);
3608                 break;
3609         case ISCSI_PARAM_IS_FW_ASSIGNED_IPV6:
3610                 len = sysfs_emit(buf, "%u\n", conn->is_fw_assigned_ipv6);
3611                 break;
3612         case ISCSI_PARAM_TCP_XMIT_WSF:
3613                 len = sysfs_emit(buf, "%u\n", conn->tcp_xmit_wsf);
3614                 break;
3615         case ISCSI_PARAM_TCP_RECV_WSF:
3616                 len = sysfs_emit(buf, "%u\n", conn->tcp_recv_wsf);
3617                 break;
3618         case ISCSI_PARAM_LOCAL_IPADDR:
3619                 len = sysfs_emit(buf, "%s\n", conn->local_ipaddr);
3620                 break;
3621         default:
3622                 return -ENOSYS;
3623         }
3624
3625         return len;
3626 }
3627 EXPORT_SYMBOL_GPL(iscsi_conn_get_param);
3628
3629 int iscsi_host_get_param(struct Scsi_Host *shost, enum iscsi_host_param param,
3630                          char *buf)
3631 {
3632         struct iscsi_host *ihost = shost_priv(shost);
3633         int len;
3634
3635         switch (param) {
3636         case ISCSI_HOST_PARAM_NETDEV_NAME:
3637                 len = sysfs_emit(buf, "%s\n", ihost->netdev);
3638                 break;
3639         case ISCSI_HOST_PARAM_HWADDRESS:
3640                 len = sysfs_emit(buf, "%s\n", ihost->hwaddress);
3641                 break;
3642         case ISCSI_HOST_PARAM_INITIATOR_NAME:
3643                 len = sysfs_emit(buf, "%s\n", ihost->initiatorname);
3644                 break;
3645         default:
3646                 return -ENOSYS;
3647         }
3648
3649         return len;
3650 }
3651 EXPORT_SYMBOL_GPL(iscsi_host_get_param);
3652
3653 int iscsi_host_set_param(struct Scsi_Host *shost, enum iscsi_host_param param,
3654                          char *buf, int buflen)
3655 {
3656         struct iscsi_host *ihost = shost_priv(shost);
3657
3658         switch (param) {
3659         case ISCSI_HOST_PARAM_NETDEV_NAME:
3660                 return iscsi_switch_str_param(&ihost->netdev, buf);
3661         case ISCSI_HOST_PARAM_HWADDRESS:
3662                 return iscsi_switch_str_param(&ihost->hwaddress, buf);
3663         case ISCSI_HOST_PARAM_INITIATOR_NAME:
3664                 return iscsi_switch_str_param(&ihost->initiatorname, buf);
3665         default:
3666                 return -ENOSYS;
3667         }
3668
3669         return 0;
3670 }
3671 EXPORT_SYMBOL_GPL(iscsi_host_set_param);
3672
3673 MODULE_AUTHOR("Mike Christie");
3674 MODULE_DESCRIPTION("iSCSI library functions");
3675 MODULE_LICENSE("GPL");