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