Added possibility to coexist if both target driver and dev handler need custom memory...
[mirror/scst/.git] / scst / src / dev_handlers / scst_user.c
1 /*
2  *  scst_user.c
3  *
4  *  Copyright (C) 2007 - 2008 Vladislav Bolkhovitin <vst@vlnb.net>
5  *  Copyright (C) 2007 - 2008 CMS Distribution Limited
6  *
7  *  SCSI virtual user space device handler
8  *
9  *  This program is free software; you can redistribute it and/or
10  *  modify it under the terms of the GNU General Public License
11  *  as published by the Free Software Foundation, version 2
12  *  of the License.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  *  GNU General Public License for more details.
18  */
19
20 #include <linux/kthread.h>
21 #include <linux/delay.h>
22 #include <linux/poll.h>
23
24 #define LOG_PREFIX              DEV_USER_NAME
25
26 #include "scst.h"
27 #include "scst_user.h"
28 #include "scst_dev_handler.h"
29
30 #if defined(CONFIG_HIGHMEM4G) || defined(CONFIG_HIGHMEM64G)
31 #warning "HIGHMEM kernel configurations are not supported by this module, \
32         because nowadays it doesn't worth the effort. Consider change \
33         VMSPLIT option or use 64-bit configuration instead. See README file \
34         for details."
35 #endif
36
37 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 18))
38 #define COMPLETION_INITIALIZER_ONSTACK(work) \
39         ({ init_completion(&work); work; })
40         
41 /*
42  * Lockdep needs to run a non-constant initializer for on-stack
43  * completions - so we use the _ONSTACK() variant for those that
44  * are on the kernel stack:
45  */
46 #ifdef CONFIG_LOCKDEP
47 # define DECLARE_COMPLETION_ONSTACK(work) \
48         struct completion work = COMPLETION_INITIALIZER_ONSTACK(work)
49 #else
50 # define DECLARE_COMPLETION_ONSTACK(work) DECLARE_COMPLETION(work)
51 #endif
52
53 #endif
54
55 #define DEV_USER_MAJOR                  237
56
57 #define DEV_USER_CMD_HASH_ORDER         6
58
59 #define DEV_USER_ATTACH_TIMEOUT         (5*HZ)
60
61 struct scst_user_dev {
62         struct rw_semaphore dev_rwsem;
63
64         struct scst_cmd_lists cmd_lists;
65
66         /* Protected by cmd_lists.cmd_list_lock */
67         struct list_head ready_cmd_list;
68
69         /* Protected by dev_rwsem or don't need any protection */
70         unsigned int blocking:1;
71         unsigned int cleanup_done:1;
72         unsigned int tst:3;
73         unsigned int queue_alg:4;
74         unsigned int tas:1;
75         unsigned int swp:1;
76         unsigned int has_own_order_mgmt:1;
77
78         int (*generic_parse)(struct scst_cmd *cmd,
79                 int (*get_block)(struct scst_cmd *cmd));
80
81         int block;
82         int def_block;
83
84         struct scst_mem_lim udev_mem_lim;
85         struct sgv_pool *pool;
86
87         uint8_t parse_type;
88         uint8_t on_free_cmd_type;
89         uint8_t memory_reuse_type;
90         uint8_t partial_transfers_type;
91         uint32_t partial_len;
92
93         struct scst_dev_type devtype;
94
95         /* Both protected by cmd_lists.cmd_list_lock */
96         unsigned int handle_counter;
97         struct list_head ucmd_hash[1 << DEV_USER_CMD_HASH_ORDER];
98
99         struct scst_device *sdev;
100
101         int virt_id;
102         struct list_head dev_list_entry;
103         char name[SCST_MAX_NAME];
104
105         struct list_head cleanup_list_entry;
106         /* ToDo: make it on-stack */
107         struct completion cleanup_cmpl;
108 };
109
110 /* Most fields are unprotected, since only one thread at time can access them */
111 struct scst_user_cmd {
112         struct scst_cmd *cmd;
113         struct scst_user_dev *dev;
114
115         atomic_t ucmd_ref;
116
117         unsigned int buff_cached:1;
118         unsigned int buf_dirty:1;
119         unsigned int background_exec:1;
120         unsigned int aborted:1;
121
122         struct scst_user_cmd *buf_ucmd;
123
124         int cur_data_page;
125         int num_data_pages;
126         int first_page_offset;
127         unsigned long ubuff;
128         struct page **data_pages;
129         struct sgv_pool_obj *sgv;
130
131         /*
132          * Special flags, which can be accessed asynchronously (hence "long").
133          * Protected by cmd_lists.cmd_list_lock.
134          */
135         unsigned long sent_to_user:1;
136         unsigned long jammed:1;
137         unsigned long this_state_unjammed:1;
138         unsigned long seen_by_user:1; /* here only as a small optimization */
139
140         unsigned int state;
141
142         struct list_head ready_cmd_list_entry;
143
144         unsigned int h;
145         struct list_head hash_list_entry;
146
147         struct scst_user_get_cmd user_cmd;
148
149         /* cmpl used only by ATTACH_SESS, mcmd used only by TM */
150         union {
151                 struct completion *cmpl;
152                 struct scst_mgmt_cmd *mcmd;
153         };
154         int result;
155 };
156
157 static struct scst_user_cmd *dev_user_alloc_ucmd(struct scst_user_dev *dev,
158         gfp_t gfp_mask);
159 static void dev_user_free_ucmd(struct scst_user_cmd *ucmd);
160
161 static int dev_user_parse(struct scst_cmd *cmd);
162 static int dev_user_exec(struct scst_cmd *cmd);
163 static void dev_user_on_free_cmd(struct scst_cmd *cmd);
164 static int dev_user_task_mgmt_fn(struct scst_mgmt_cmd *mcmd,
165         struct scst_tgt_dev *tgt_dev);
166
167 static int dev_user_disk_done(struct scst_cmd *cmd);
168 static int dev_user_tape_done(struct scst_cmd *cmd);
169
170 static struct page *dev_user_alloc_pages(struct scatterlist *sg,
171         gfp_t gfp_mask, void *priv);
172 static void dev_user_free_sg_entries(struct scatterlist *sg, int sg_count,
173                                      void *priv);
174
175 static void dev_user_add_to_ready(struct scst_user_cmd *ucmd);
176
177 static void dev_user_unjam_cmd(struct scst_user_cmd *ucmd, int busy,
178         unsigned long *flags);
179
180 static int dev_user_process_reply_on_free(struct scst_user_cmd *ucmd);
181 static int dev_user_process_reply_tm_exec(struct scst_user_cmd *ucmd,
182         int status);
183 static int dev_user_process_reply_sess(struct scst_user_cmd *ucmd, int status);
184 static int dev_user_register_dev(struct file *file,
185         const struct scst_user_dev_desc *dev_desc);
186 static int __dev_user_set_opt(struct scst_user_dev *dev,
187         const struct scst_user_opt *opt);
188 static int dev_user_set_opt(struct file *file, const struct scst_user_opt *opt);
189 static int dev_user_get_opt(struct file *file, void __user *arg);
190
191 static unsigned int dev_user_poll(struct file *filp, poll_table *wait);
192 static long dev_user_ioctl(struct file *file, unsigned int cmd,
193         unsigned long arg);
194 static int dev_user_release(struct inode *inode, struct file *file);
195
196 /** Data **/
197
198 static struct kmem_cache *user_cmd_cachep;
199 static struct kmem_cache *user_get_cmd_cachep;
200
201 static DEFINE_MUTEX(dev_priv_mutex);
202
203 static struct file_operations dev_user_fops = {
204         .poll           = dev_user_poll,
205         .unlocked_ioctl = dev_user_ioctl,
206 #ifdef CONFIG_COMPAT
207         .compat_ioctl   = dev_user_ioctl,
208 #endif
209         .release        = dev_user_release,
210 };
211
212 static struct class *dev_user_sysfs_class;
213
214 static DEFINE_SPINLOCK(dev_list_lock);
215 static LIST_HEAD(dev_list);
216
217 static DEFINE_SPINLOCK(cleanup_lock);
218 static LIST_HEAD(cleanup_list);
219 static DECLARE_WAIT_QUEUE_HEAD(cleanup_list_waitQ);
220 static struct task_struct *cleanup_thread;
221
222 /*
223  * Skip this command if result is not 0. Must be called under
224  * cmd_lists.cmd_list_lock and IRQ off.
225  */
226 static inline bool ucmd_get_check(struct scst_user_cmd *ucmd)
227 {
228         int r = atomic_inc_return(&ucmd->ucmd_ref);
229         int res;
230         if (unlikely(r == 1)) {
231                 TRACE_DBG("ucmd %p is being destroyed", ucmd);
232                 atomic_dec(&ucmd->ucmd_ref);
233                 res = true;
234                 /*
235                  * Necessary code is serialized by cmd_list_lock in
236                  * cmd_remove_hash()
237                  */
238         } else {
239                 TRACE_DBG("ucmd %p, new ref_cnt %d", ucmd,
240                         atomic_read(&ucmd->ucmd_ref));
241                 res = false;
242         }
243         return res;
244 }
245
246 static inline void __ucmd_get(struct scst_user_cmd *ucmd, bool barrier)
247 {
248         TRACE_DBG("ucmd %p, ucmd_ref %d", ucmd, atomic_read(&ucmd->ucmd_ref));
249         atomic_inc(&ucmd->ucmd_ref);
250         if (barrier)
251                 smp_mb__after_atomic_inc();
252 }
253
254 static inline void ucmd_get_ordered(struct scst_user_cmd *ucmd)
255 {
256         __ucmd_get(ucmd, true);
257 }
258
259 static inline void ucmd_get(struct scst_user_cmd *ucmd)
260 {
261         __ucmd_get(ucmd, false);
262 }
263
264 /* Must not be called under cmd_list_lock!! */
265 static inline void ucmd_put(struct scst_user_cmd *ucmd)
266 {
267         TRACE_DBG("ucmd %p, ucmd_ref %d", ucmd, atomic_read(&ucmd->ucmd_ref));
268
269         EXTRACHECKS_BUG_ON(atomic_read(&ucmd->ucmd_ref) == 0);
270
271         if (atomic_dec_and_test(&ucmd->ucmd_ref))
272                 dev_user_free_ucmd(ucmd);
273 }
274
275 static inline int calc_num_pg(unsigned long buf, int len)
276 {
277         len += buf & ~PAGE_MASK;
278         return (len >> PAGE_SHIFT) + ((len & ~PAGE_MASK) != 0);
279 }
280
281 static inline int is_need_offs_page(unsigned long buf, int len)
282 {
283         return ((buf & ~PAGE_MASK) != 0) &&
284                 ((buf & PAGE_MASK) != ((buf+len-1) & PAGE_MASK));
285 }
286
287 static void __dev_user_not_reg(void)
288 {
289         PRINT_ERROR("%s", "Device not registered");
290         return;
291 }
292
293 static inline int dev_user_check_reg(struct scst_user_dev *dev)
294 {
295         if (dev == NULL) {
296                 __dev_user_not_reg();
297                 return -EINVAL;
298         }
299         return 0;
300 }
301
302 static inline int scst_user_cmd_hashfn(int h)
303 {
304         return h & ((1 << DEV_USER_CMD_HASH_ORDER) - 1);
305 }
306
307 static inline struct scst_user_cmd *__ucmd_find_hash(struct scst_user_dev *dev,
308         unsigned int h)
309 {
310         struct list_head *head;
311         struct scst_user_cmd *ucmd;
312
313         head = &dev->ucmd_hash[scst_user_cmd_hashfn(h)];
314         list_for_each_entry(ucmd, head, hash_list_entry) {
315                 if (ucmd->h == h) {
316                         TRACE_DBG("Found ucmd %p", ucmd);
317                         return ucmd;
318                 }
319         }
320         return NULL;
321 }
322
323 static void cmd_insert_hash(struct scst_user_cmd *ucmd)
324 {
325         struct list_head *head;
326         struct scst_user_dev *dev = ucmd->dev;
327         struct scst_user_cmd *u;
328         unsigned long flags;
329
330         spin_lock_irqsave(&dev->cmd_lists.cmd_list_lock, flags);
331         do {
332                 ucmd->h = dev->handle_counter++;
333                 u = __ucmd_find_hash(dev, ucmd->h);
334         } while (u != NULL);
335         head = &dev->ucmd_hash[scst_user_cmd_hashfn(ucmd->h)];
336         list_add_tail(&ucmd->hash_list_entry, head);
337         spin_unlock_irqrestore(&dev->cmd_lists.cmd_list_lock, flags);
338
339         TRACE_DBG("Inserted ucmd %p, h=%d (dev %s)", ucmd, ucmd->h, dev->name);
340         return;
341 }
342
343 static inline void cmd_remove_hash(struct scst_user_cmd *ucmd)
344 {
345         unsigned long flags;
346
347         spin_lock_irqsave(&ucmd->dev->cmd_lists.cmd_list_lock, flags);
348         list_del(&ucmd->hash_list_entry);
349         spin_unlock_irqrestore(&ucmd->dev->cmd_lists.cmd_list_lock, flags);
350
351         TRACE_DBG("Removed ucmd %p, h=%d", ucmd, ucmd->h);
352         return;
353 }
354
355 static void dev_user_free_ucmd(struct scst_user_cmd *ucmd)
356 {
357         TRACE_ENTRY();
358
359         TRACE_MEM("Freeing ucmd %p", ucmd);
360
361         cmd_remove_hash(ucmd);
362         EXTRACHECKS_BUG_ON(ucmd->cmd != NULL);
363
364         kmem_cache_free(user_cmd_cachep, ucmd);
365
366         TRACE_EXIT();
367         return;
368 }
369
370 static struct page *dev_user_alloc_pages(struct scatterlist *sg,
371         gfp_t gfp_mask, void *priv)
372 {
373         struct scst_user_cmd *ucmd = (struct scst_user_cmd *)priv;
374         int offset = 0;
375
376         TRACE_ENTRY();
377
378         /* *sg supposed to be zeroed */
379
380         TRACE_MEM("ucmd %p, ubuff %lx, ucmd->cur_data_page %d", ucmd,
381                 ucmd->ubuff, ucmd->cur_data_page);
382
383         if (ucmd->cur_data_page == 0) {
384                 TRACE_MEM("ucmd->first_page_offset %d",
385                         ucmd->first_page_offset);
386                 offset = ucmd->first_page_offset;
387                 ucmd_get(ucmd);
388         }
389
390         if (ucmd->cur_data_page >= ucmd->num_data_pages)
391                 goto out;
392
393         sg_set_page(sg, ucmd->data_pages[ucmd->cur_data_page],
394                 PAGE_SIZE - offset, offset);
395         ucmd->cur_data_page++;
396
397         TRACE_MEM("page=%p, length=%d, offset=%d", sg_page(sg), sg->length,
398                 sg->offset);
399         TRACE_BUFFER("Page data", sg_virt(sg), sg->length);
400
401 out:
402         TRACE_EXIT();
403         return sg_page(sg);
404 }
405
406 static void dev_user_on_cached_mem_free(struct scst_user_cmd *ucmd)
407 {
408         TRACE_ENTRY();
409
410         TRACE_MEM("Preparing ON_CACHED_MEM_FREE (ucmd %p, h %d, ubuff %lx)",
411                 ucmd, ucmd->h, ucmd->ubuff);
412
413         ucmd->user_cmd.cmd_h = ucmd->h;
414         ucmd->user_cmd.subcode = SCST_USER_ON_CACHED_MEM_FREE;
415         ucmd->user_cmd.on_cached_mem_free.pbuf = ucmd->ubuff;
416
417         ucmd->state = UCMD_STATE_ON_CACHE_FREEING;
418
419         dev_user_add_to_ready(ucmd);
420
421         TRACE_EXIT();
422         return;
423 }
424
425 static void dev_user_unmap_buf(struct scst_user_cmd *ucmd)
426 {
427         int i;
428
429         TRACE_ENTRY();
430
431         TRACE_MEM("Unmapping data pages (ucmd %p, ubuff %lx, num %d)", ucmd,
432                 ucmd->ubuff, ucmd->num_data_pages);
433
434         for (i = 0; i < ucmd->num_data_pages; i++) {
435                 struct page *page = ucmd->data_pages[i];
436
437                 if (ucmd->buf_dirty)
438                         SetPageDirty(page);
439
440                 page_cache_release(page);
441         }
442
443         kfree(ucmd->data_pages);
444         ucmd->data_pages = NULL;
445
446         TRACE_EXIT();
447         return;
448 }
449
450 static void __dev_user_free_sg_entries(struct scst_user_cmd *ucmd)
451 {
452         TRACE_ENTRY();
453
454         sBUG_ON(ucmd->data_pages == NULL);
455
456         TRACE_MEM("Freeing data pages (ucmd=%p, ubuff=%lx, buff_cached=%d)",
457                 ucmd, ucmd->ubuff, ucmd->buff_cached);
458
459         dev_user_unmap_buf(ucmd);
460
461         if (ucmd->buff_cached)
462                 dev_user_on_cached_mem_free(ucmd);
463         else
464                 ucmd_put(ucmd);
465
466         TRACE_EXIT();
467         return;
468 }
469
470 static void dev_user_free_sg_entries(struct scatterlist *sg, int sg_count,
471         void *priv)
472 {
473         struct scst_user_cmd *ucmd = (struct scst_user_cmd *)priv;
474
475         TRACE_MEM("Freeing data pages (sg=%p, sg_count=%d, priv %p)", sg,
476                 sg_count, ucmd);
477
478         __dev_user_free_sg_entries(ucmd);
479
480         return;
481 }
482
483 static inline int is_buff_cached(struct scst_user_cmd *ucmd)
484 {
485         int mem_reuse_type = ucmd->dev->memory_reuse_type;
486
487         if ((mem_reuse_type == SCST_USER_MEM_REUSE_ALL) ||
488             ((ucmd->cmd->data_direction == SCST_DATA_READ) &&
489              (mem_reuse_type == SCST_USER_MEM_REUSE_READ)) ||
490             ((ucmd->cmd->data_direction == SCST_DATA_WRITE) &&
491              (mem_reuse_type == SCST_USER_MEM_REUSE_WRITE)))
492                 return 1;
493         else
494                 return 0;
495 }
496
497 /*
498  * Returns 0 for success, <0 for fatal failure, >0 - need pages.
499  * Unmaps the buffer, if needed in case of error
500  */
501 static int dev_user_alloc_sg(struct scst_user_cmd *ucmd, int cached_buff)
502 {
503         int res = 0;
504         struct scst_cmd *cmd = ucmd->cmd;
505         struct scst_user_dev *dev = ucmd->dev;
506         gfp_t gfp_mask;
507         int flags = 0;
508         int bufflen = cmd->bufflen;
509         int last_len = 0;
510
511         TRACE_ENTRY();
512
513         sBUG_ON(bufflen == 0);
514
515         gfp_mask = __GFP_NOWARN;
516         gfp_mask |= (scst_cmd_atomic(cmd) ? GFP_ATOMIC : GFP_KERNEL);
517
518         if (cached_buff) {
519                 flags |= SCST_POOL_RETURN_OBJ_ON_ALLOC_FAIL;
520                 if (ucmd->ubuff == 0)
521                         flags |= SCST_POOL_NO_ALLOC_ON_CACHE_MISS;
522         } else {
523                 TRACE_MEM("%s", "Not cached buff");
524                 flags |= SCST_POOL_ALLOC_NO_CACHED;
525                 if (ucmd->ubuff == 0) {
526                         res = 1;
527                         goto out;
528                 }
529                 bufflen += ucmd->first_page_offset;
530                 if (is_need_offs_page(ucmd->ubuff, cmd->bufflen))
531                         last_len = bufflen & ~PAGE_MASK;
532                 else
533                         last_len = cmd->bufflen & ~PAGE_MASK;
534                 if (last_len == 0)
535                         last_len = PAGE_SIZE;
536         }
537         ucmd->buff_cached = cached_buff;
538
539         cmd->sg = sgv_pool_alloc(dev->pool, bufflen, gfp_mask, flags,
540                         &cmd->sg_cnt, &ucmd->sgv, &dev->udev_mem_lim, ucmd);
541         if (cmd->sg != NULL) {
542                 struct scst_user_cmd *buf_ucmd =
543                         (struct scst_user_cmd *)sgv_get_priv(ucmd->sgv);
544
545                 TRACE_MEM("Buf ucmd %p", buf_ucmd);
546
547                 ucmd->ubuff = buf_ucmd->ubuff;
548                 ucmd->buf_ucmd = buf_ucmd;
549
550                 EXTRACHECKS_BUG_ON((ucmd->data_pages != NULL) &&
551                                    (ucmd != buf_ucmd));
552
553                 if (last_len != 0) {
554                         /* We don't use clustering, so the assignment is safe */
555                         cmd->sg[cmd->sg_cnt-1].length = last_len;
556                 }
557
558                 TRACE_MEM("Buf alloced (ucmd %p, cached_buff %d, ubuff %lx, "
559                         "last_len %d, l %d)", ucmd, cached_buff, ucmd->ubuff,
560                         last_len, cmd->sg[cmd->sg_cnt-1].length);
561
562                 if (unlikely(cmd->sg_cnt > cmd->tgt_dev->max_sg_cnt)) {
563                         static int ll;
564                         if (ll < 10) {
565                                 PRINT_INFO("Unable to complete command due to "
566                                         "SG IO count limitation (requested %d, "
567                                         "available %d, tgt lim %d)",
568                                         cmd->sg_cnt,
569                                         cmd->tgt_dev->max_sg_cnt,
570                                         cmd->tgt->sg_tablesize);
571                                 ll++;
572                         }
573                         cmd->sg = NULL;
574                         /* sgv will be freed in dev_user_free_sgv() */
575                         res = -1;
576                 }
577         } else {
578                 TRACE_MEM("Buf not alloced (ucmd %p, h %d, buff_cached, %d, "
579                         "sg_cnt %d, ubuff %lx, sgv %p", ucmd, ucmd->h,
580                         ucmd->buff_cached, cmd->sg_cnt, ucmd->ubuff, ucmd->sgv);
581                 if (unlikely(cmd->sg_cnt == 0)) {
582                         TRACE_MEM("Refused allocation (ucmd %p)", ucmd);
583                         sBUG_ON(ucmd->sgv != NULL);
584                         res = -1;
585                 } else {
586                         switch (ucmd->state) {
587                         case UCMD_STATE_BUF_ALLOCING:
588                                 res = 1;
589                                 break;
590                         case UCMD_STATE_EXECING:
591                                 res = -1;
592                                 break;
593                         default:
594                                 sBUG();
595                                 break;
596                         }
597                 }
598         }
599
600 out:
601         TRACE_EXIT_RES(res);
602         return res;
603 }
604
605 static int dev_user_alloc_space(struct scst_user_cmd *ucmd)
606 {
607         int rc, res = SCST_CMD_STATE_DEFAULT;
608         struct scst_cmd *cmd = ucmd->cmd;
609
610         TRACE_ENTRY();
611
612         ucmd->state = UCMD_STATE_BUF_ALLOCING;
613         cmd->dh_data_buf_alloced = 1;
614
615         rc = dev_user_alloc_sg(ucmd, is_buff_cached(ucmd));
616         if (rc == 0)
617                 goto out;
618         else if (rc < 0) {
619                 scst_set_busy(cmd);
620                 res = scst_get_cmd_abnormal_done_state(cmd);
621                 goto out;
622         }
623
624         if ((cmd->data_direction != SCST_DATA_WRITE) &&
625             !scst_is_cmd_local(cmd)) {
626                 TRACE_DBG("Delayed alloc, ucmd %p", ucmd);
627                 goto out;
628         }
629
630         ucmd->user_cmd.cmd_h = ucmd->h;
631         ucmd->user_cmd.subcode = SCST_USER_ALLOC_MEM;
632         ucmd->user_cmd.alloc_cmd.sess_h = (unsigned long)cmd->tgt_dev;
633         memcpy(ucmd->user_cmd.alloc_cmd.cdb, cmd->cdb,
634                 min(sizeof(ucmd->user_cmd.alloc_cmd.cdb), sizeof(cmd->cdb)));
635         ucmd->user_cmd.alloc_cmd.cdb_len = cmd->cdb_len;
636         ucmd->user_cmd.alloc_cmd.alloc_len = ucmd->buff_cached ?
637                 (cmd->sg_cnt << PAGE_SHIFT) : cmd->bufflen;
638         ucmd->user_cmd.alloc_cmd.queue_type = cmd->queue_type;
639         ucmd->user_cmd.alloc_cmd.data_direction = cmd->data_direction;
640         ucmd->user_cmd.alloc_cmd.sn = cmd->tgt_sn;
641
642         dev_user_add_to_ready(ucmd);
643
644         res = SCST_CMD_STATE_STOP;
645
646 out:
647         TRACE_EXIT_RES(res);
648         return res;
649 }
650
651 static struct scst_user_cmd *dev_user_alloc_ucmd(struct scst_user_dev *dev,
652         gfp_t gfp_mask)
653 {
654         struct scst_user_cmd *ucmd = NULL;
655
656         TRACE_ENTRY();
657
658 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 17)
659         ucmd = kmem_cache_alloc(user_cmd_cachep, gfp_mask);
660         if (ucmd != NULL)
661                 memset(ucmd, 0, sizeof(*ucmd));
662 #else
663         ucmd = kmem_cache_zalloc(user_cmd_cachep, gfp_mask);
664 #endif
665         if (unlikely(ucmd == NULL)) {
666                 TRACE(TRACE_OUT_OF_MEM, "Unable to allocate "
667                         "user cmd (gfp_mask %x)", gfp_mask);
668                 goto out;
669         }
670         ucmd->dev = dev;
671         atomic_set(&ucmd->ucmd_ref, 1);
672
673         cmd_insert_hash(ucmd);
674
675         TRACE_MEM("ucmd %p allocated", ucmd);
676
677 out:
678         TRACE_EXIT_HRES((unsigned long)ucmd);
679         return ucmd;
680 }
681
682 static int dev_user_get_block(struct scst_cmd *cmd)
683 {
684         struct scst_user_dev *dev = (struct scst_user_dev *)cmd->dev->dh_priv;
685         /*
686          * No need for locks here, since *_detach() can not be
687          * called, when there are existing commands.
688          */
689         TRACE_EXIT_RES(dev->block);
690         return dev->block;
691 }
692
693 static int dev_user_parse(struct scst_cmd *cmd)
694 {
695         int rc, res = SCST_CMD_STATE_DEFAULT;
696         struct scst_user_cmd *ucmd;
697         int atomic = scst_cmd_atomic(cmd);
698         struct scst_user_dev *dev = (struct scst_user_dev *)cmd->dev->dh_priv;
699         gfp_t gfp_mask = atomic ? GFP_ATOMIC : GFP_KERNEL;
700
701         TRACE_ENTRY();
702
703         if (cmd->dh_priv == NULL) {
704                 ucmd = dev_user_alloc_ucmd(dev, gfp_mask);
705                 if (unlikely(ucmd == NULL)) {
706                         if (atomic) {
707                                 res = SCST_CMD_STATE_NEED_THREAD_CTX;
708                                 goto out;
709                         } else {
710                                 scst_set_busy(cmd);
711                                 goto out_error;
712                         }
713                 }
714                 ucmd->cmd = cmd;
715                 cmd->dh_priv = ucmd;
716         } else {
717                 ucmd = (struct scst_user_cmd *)cmd->dh_priv;
718                 TRACE_DBG("Used ucmd %p, state %x", ucmd, ucmd->state);
719         }
720
721         TRACE_DBG("ucmd %p, cmd %p, state %x", ucmd, cmd, ucmd->state);
722
723         if (ucmd->state != UCMD_STATE_NEW)
724                 goto alloc;
725
726         switch (dev->parse_type) {
727         case SCST_USER_PARSE_STANDARD:
728                 TRACE_DBG("PARSE STANDARD: ucmd %p", ucmd);
729                 rc = dev->generic_parse(cmd, dev_user_get_block);
730                 if ((rc != 0) || (cmd->op_flags & SCST_INFO_INVALID))
731                         goto out_invalid;
732                 break;
733
734         case SCST_USER_PARSE_EXCEPTION:
735                 TRACE_DBG("PARSE EXCEPTION: ucmd %p", ucmd);
736                 rc = dev->generic_parse(cmd, dev_user_get_block);
737                 if ((rc == 0) && (!(cmd->op_flags & SCST_INFO_INVALID)))
738                         break;
739                 else if (rc == SCST_CMD_STATE_NEED_THREAD_CTX) {
740                         TRACE_MEM("Restarting PARSE to thread context "
741                                 "(ucmd %p)", ucmd);
742                         res = SCST_CMD_STATE_NEED_THREAD_CTX;
743                         goto out;
744                 }
745                 /* else go through */
746
747         case SCST_USER_PARSE_CALL:
748                 TRACE_DBG("Preparing PARSE for user space (ucmd=%p, h=%d, "
749                         "bufflen %d)", ucmd, ucmd->h, cmd->bufflen);
750                 ucmd->user_cmd.cmd_h = ucmd->h;
751                 ucmd->user_cmd.subcode = SCST_USER_PARSE;
752                 ucmd->user_cmd.parse_cmd.sess_h = (unsigned long)cmd->tgt_dev;
753                 memcpy(ucmd->user_cmd.parse_cmd.cdb, cmd->cdb,
754                         min(sizeof(ucmd->user_cmd.parse_cmd.cdb),
755                             sizeof(cmd->cdb)));
756                 ucmd->user_cmd.parse_cmd.cdb_len = cmd->cdb_len;
757                 ucmd->user_cmd.parse_cmd.timeout = cmd->timeout / HZ;
758                 ucmd->user_cmd.parse_cmd.bufflen = cmd->bufflen;
759                 ucmd->user_cmd.parse_cmd.queue_type = cmd->queue_type;
760                 ucmd->user_cmd.parse_cmd.data_direction = cmd->data_direction;
761                 ucmd->user_cmd.parse_cmd.expected_values_set =
762                                         cmd->expected_values_set;
763                 ucmd->user_cmd.parse_cmd.expected_data_direction =
764                                         cmd->expected_data_direction;
765                 ucmd->user_cmd.parse_cmd.expected_transfer_len =
766                                         cmd->expected_transfer_len;
767                 ucmd->user_cmd.parse_cmd.sn = cmd->tgt_sn;
768                 ucmd->state = UCMD_STATE_PARSING;
769                 dev_user_add_to_ready(ucmd);
770                 res = SCST_CMD_STATE_STOP;
771                 goto out;
772
773         default:
774                 sBUG();
775                 goto out;
776         }
777
778 alloc:
779         if (cmd->data_direction != SCST_DATA_NONE)
780                 res = dev_user_alloc_space(ucmd);
781
782 out:
783         TRACE_EXIT_RES(res);
784         return res;
785
786 out_invalid:
787         PRINT_ERROR("PARSE failed (ucmd %p, rc %d, invalid %d)", ucmd, rc,
788                 cmd->op_flags & SCST_INFO_INVALID);
789         scst_set_cmd_error(cmd, SCST_LOAD_SENSE(scst_sense_invalid_opcode));
790
791 out_error:
792         res = scst_get_cmd_abnormal_done_state(cmd);
793         goto out;
794 }
795
796 static void dev_user_flush_dcache(struct scst_user_cmd *ucmd)
797 {
798         struct scst_user_cmd *buf_ucmd = ucmd->buf_ucmd;
799         unsigned long start = buf_ucmd->ubuff;
800         int i, bufflen = ucmd->cmd->bufflen;
801
802         TRACE_ENTRY();
803
804         if (start == 0)
805                 goto out;
806
807         /*
808          * Possibly, flushing of all the pages from ucmd->cmd->sg can be
809          * faster, since it should be cache hot, while ucmd->buf_ucmd and
810          * buf_ucmd->data_pages are cache cold. But, from other side,
811          * sizeof(buf_ucmd->data_pages[0]) is considerably smaller, than
812          * sizeof(ucmd->cmd->sg[0]), so on big buffers going over 
813          * data_pages array can lead to less cache misses. So, real numbers are
814          * needed. ToDo.
815          */
816
817         for (i = 0; (bufflen > 0) && (i < buf_ucmd->num_data_pages); i++) {
818                 struct page *page;
819                 page = buf_ucmd->data_pages[i];
820 #ifdef ARCH_HAS_FLUSH_ANON_PAGE
821                 struct vm_area_struct *vma = find_vma(current->mm, start);
822                 if (vma != NULL)
823                         flush_anon_page(vma, page, start);
824 #endif
825                 flush_dcache_page(page);
826                 start += PAGE_SIZE;
827                 bufflen -= PAGE_SIZE;
828         }
829
830 out:
831         TRACE_EXIT();
832         return;
833 }
834
835 static int dev_user_exec(struct scst_cmd *cmd)
836 {
837         struct scst_user_cmd *ucmd = (struct scst_user_cmd *)cmd->dh_priv;
838         int res = SCST_EXEC_COMPLETED;
839
840         TRACE_ENTRY();
841
842 #if 0 /* We set exec_atomic in 0 to let SCST core know that we need a thread
843        * context to complete the necessary actions, but all we are going to
844        * do in this function is, in fact, atomic, so let's skip this check.
845        */
846         if (scst_cmd_atomic(cmd)) {
847                 TRACE_DBG("%s", "User exec() can not be called in atomic "
848                         "context, rescheduling to the thread");
849                 res = SCST_EXEC_NEED_THREAD;
850                 goto out;
851         }
852 #endif
853
854         TRACE_DBG("Preparing EXEC for user space (ucmd=%p, h=%d, "
855                 "bufflen %d, data_len %d, ubuff %lx)", ucmd, ucmd->h,
856                 cmd->bufflen, cmd->data_len, ucmd->ubuff);
857
858         if (cmd->data_direction == SCST_DATA_WRITE)
859                 dev_user_flush_dcache(ucmd);
860
861         ucmd->user_cmd.cmd_h = ucmd->h;
862         ucmd->user_cmd.subcode = SCST_USER_EXEC;
863         ucmd->user_cmd.exec_cmd.sess_h = (unsigned long)cmd->tgt_dev;
864         memcpy(ucmd->user_cmd.exec_cmd.cdb, cmd->cdb,
865                 min(sizeof(ucmd->user_cmd.exec_cmd.cdb),
866                     sizeof(cmd->cdb)));
867         ucmd->user_cmd.exec_cmd.cdb_len = cmd->cdb_len;
868         ucmd->user_cmd.exec_cmd.bufflen = cmd->bufflen;
869         ucmd->user_cmd.exec_cmd.data_len = cmd->data_len;
870         ucmd->user_cmd.exec_cmd.pbuf = ucmd->ubuff;
871         if ((ucmd->ubuff == 0) && (cmd->data_direction != SCST_DATA_NONE)) {
872                 ucmd->user_cmd.exec_cmd.alloc_len = ucmd->buff_cached ?
873                         (cmd->sg_cnt << PAGE_SHIFT) : cmd->bufflen;
874         }
875         ucmd->user_cmd.exec_cmd.queue_type = cmd->queue_type;
876         ucmd->user_cmd.exec_cmd.data_direction = cmd->data_direction;
877         ucmd->user_cmd.exec_cmd.partial = 0;
878         ucmd->user_cmd.exec_cmd.timeout = cmd->timeout / HZ;
879         ucmd->user_cmd.exec_cmd.sn = cmd->tgt_sn;
880
881         ucmd->state = UCMD_STATE_EXECING;
882
883         dev_user_add_to_ready(ucmd);
884
885         TRACE_EXIT_RES(res);
886         return res;
887 }
888
889 static void dev_user_free_sgv(struct scst_user_cmd *ucmd)
890 {
891         if (ucmd->sgv != NULL) {
892                 sgv_pool_free(ucmd->sgv, &ucmd->dev->udev_mem_lim);
893                 ucmd->sgv = NULL;
894         } else if (ucmd->data_pages != NULL) {
895                 /* We mapped pages, but for some reason didn't allocate them */
896                 ucmd_get(ucmd);
897                 __dev_user_free_sg_entries(ucmd);
898         }
899         return;
900 }
901
902 static void dev_user_on_free_cmd(struct scst_cmd *cmd)
903 {
904         struct scst_user_cmd *ucmd = (struct scst_user_cmd *)cmd->dh_priv;
905
906         TRACE_ENTRY();
907
908         if (unlikely(ucmd == NULL))
909                 goto out;
910
911         TRACE_MEM("ucmd %p, cmd %p, buff_cached %d, ubuff %lx", ucmd, ucmd->cmd,
912                 ucmd->buff_cached, ucmd->ubuff);
913
914         ucmd->cmd = NULL;
915         if (cmd->data_direction == SCST_DATA_WRITE && ucmd->buf_ucmd != NULL)
916                 ucmd->buf_ucmd->buf_dirty = 1;
917
918         if (ucmd->dev->on_free_cmd_type == SCST_USER_ON_FREE_CMD_IGNORE) {
919                 ucmd->state = UCMD_STATE_ON_FREE_SKIPPED;
920                 /* The state assignment must be before freeing sgv! */
921                 goto out_reply;
922         }
923
924         if (unlikely(!ucmd->seen_by_user)) {
925                 TRACE_MGMT_DBG("Not seen by user ucmd %p", ucmd);
926                 sBUG_ON((ucmd->sgv != NULL) || (ucmd->data_pages != NULL));
927                 goto out_reply;
928         }
929
930         ucmd->user_cmd.cmd_h = ucmd->h;
931         ucmd->user_cmd.subcode = SCST_USER_ON_FREE_CMD;
932
933         ucmd->user_cmd.on_free_cmd.pbuf = ucmd->ubuff;
934         ucmd->user_cmd.on_free_cmd.resp_data_len = cmd->resp_data_len;
935         ucmd->user_cmd.on_free_cmd.buffer_cached = ucmd->buff_cached;
936         ucmd->user_cmd.on_free_cmd.aborted = ucmd->aborted;
937         ucmd->user_cmd.on_free_cmd.status = cmd->status;
938         ucmd->user_cmd.on_free_cmd.delivery_status = cmd->delivery_status;
939
940         ucmd->state = UCMD_STATE_ON_FREEING;
941
942         dev_user_add_to_ready(ucmd);
943
944 out:
945         TRACE_EXIT();
946         return;
947
948 out_reply:
949         dev_user_process_reply_on_free(ucmd);
950         goto out;
951 }
952
953 static void dev_user_set_block(struct scst_cmd *cmd, int block)
954 {
955         struct scst_user_dev *dev = (struct scst_user_dev *)cmd->dev->dh_priv;
956         /*
957          * No need for locks here, since *_detach() can not be
958          * called, when there are existing commands.
959          */
960         TRACE_DBG("dev %p, new block %d", dev, block);
961         if (block != 0)
962                 dev->block = block;
963         else
964                 dev->block = dev->def_block;
965         return;
966 }
967
968 static int dev_user_disk_done(struct scst_cmd *cmd)
969 {
970         int res = SCST_CMD_STATE_DEFAULT;
971
972         TRACE_ENTRY();
973
974         res = scst_block_generic_dev_done(cmd, dev_user_set_block);
975
976         TRACE_EXIT_RES(res);
977         return res;
978 }
979
980 static int dev_user_tape_done(struct scst_cmd *cmd)
981 {
982         int res = SCST_CMD_STATE_DEFAULT;
983
984         TRACE_ENTRY();
985
986         res = scst_tape_generic_dev_done(cmd, dev_user_set_block);
987
988         TRACE_EXIT_RES(res);
989         return res;
990 }
991
992 static void dev_user_add_to_ready(struct scst_user_cmd *ucmd)
993 {
994         struct scst_user_dev *dev = ucmd->dev;
995         unsigned long flags;
996         int do_wake;
997
998         TRACE_ENTRY();
999
1000         do_wake = (in_interrupt() ||
1001                    (ucmd->state == UCMD_STATE_ON_CACHE_FREEING));
1002         if (ucmd->cmd)
1003                 do_wake |= ucmd->cmd->preprocessing_only;
1004
1005         spin_lock_irqsave(&dev->cmd_lists.cmd_list_lock, flags);
1006
1007         ucmd->this_state_unjammed = 0;
1008
1009         if ((ucmd->state == UCMD_STATE_PARSING) ||
1010             (ucmd->state == UCMD_STATE_BUF_ALLOCING)) {
1011                 /*
1012                  * If we don't put such commands in the queue head, then under
1013                  * high load we might delay threads, waiting for memory
1014                  * allocations, for too long and start loosing NOPs, which
1015                  * would lead to consider us by remote initiators as
1016                  * unresponsive and stuck => broken connections, etc. If none
1017                  * of our commands completed in NOP timeout to allow the head
1018                  * commands to go, then we are really overloaded and/or stuck.
1019                  */
1020                 TRACE_DBG("Adding ucmd %p (state %d) to head of ready "
1021                         "cmd list", ucmd, ucmd->state);
1022                 list_add(&ucmd->ready_cmd_list_entry,
1023                         &dev->ready_cmd_list);
1024                 do_wake = 1;
1025         } else if (unlikely(ucmd->state == UCMD_STATE_TM_EXECING) ||
1026                    unlikely(ucmd->state == UCMD_STATE_ATTACH_SESS) ||
1027                    unlikely(ucmd->state == UCMD_STATE_DETACH_SESS)) {
1028                 TRACE_MGMT_DBG("Adding mgmt ucmd %p (state %d) to head of "
1029                         "ready cmd list", ucmd, ucmd->state);
1030                 list_add(&ucmd->ready_cmd_list_entry,
1031                         &dev->ready_cmd_list);
1032                 do_wake = 1;
1033         } else if ((ucmd->cmd != NULL) &&
1034            unlikely((ucmd->cmd->queue_type == SCST_CMD_QUEUE_HEAD_OF_QUEUE))) {
1035                 TRACE_DBG("Adding HQ ucmd %p to head of ready cmd list", ucmd);
1036                 list_add(&ucmd->ready_cmd_list_entry, &dev->ready_cmd_list);
1037         } else {
1038                 TRACE_DBG("Adding ucmd %p to ready cmd list", ucmd);
1039                 list_add_tail(&ucmd->ready_cmd_list_entry,
1040                               &dev->ready_cmd_list);
1041         }
1042
1043         if (do_wake) {
1044                 TRACE_DBG("Waking up dev %p", dev);
1045                 wake_up(&dev->cmd_lists.cmd_list_waitQ);
1046         }
1047
1048         spin_unlock_irqrestore(&dev->cmd_lists.cmd_list_lock, flags);
1049
1050         TRACE_EXIT();
1051         return;
1052 }
1053
1054 static int dev_user_map_buf(struct scst_user_cmd *ucmd, unsigned long ubuff,
1055         int num_pg)
1056 {
1057         int res = 0, rc;
1058         int i;
1059
1060         TRACE_ENTRY();
1061
1062         if (unlikely(ubuff == 0))
1063                 goto out_nomem;
1064
1065         sBUG_ON(ucmd->data_pages != NULL);
1066
1067         ucmd->num_data_pages = num_pg;
1068
1069         ucmd->data_pages =
1070                 kmalloc(sizeof(*ucmd->data_pages) * ucmd->num_data_pages,
1071                           GFP_KERNEL);
1072         if (ucmd->data_pages == NULL) {
1073                 TRACE(TRACE_OUT_OF_MEM, "Unable to allocate data_pages array "
1074                         "(num_data_pages=%d)", ucmd->num_data_pages);
1075                 res = -ENOMEM;
1076                 goto out_nomem;
1077         }
1078
1079         TRACE_MEM("Mapping buffer (ucmd %p, ubuff %lx, ucmd->num_data_pages %d,"
1080                 " first_page_offset %d, len %d)", ucmd, ubuff,
1081                 ucmd->num_data_pages, (int)(ubuff & ~PAGE_MASK),
1082                 ucmd->cmd->bufflen);
1083
1084         down_read(&current->mm->mmap_sem);
1085         rc = get_user_pages(current, current->mm, ubuff, ucmd->num_data_pages,
1086                 1/*writable*/, 0/*don't force*/, ucmd->data_pages, NULL);
1087         up_read(&current->mm->mmap_sem);
1088
1089         /* get_user_pages() flushes dcache */
1090
1091         if (rc < ucmd->num_data_pages)
1092                 goto out_unmap;
1093
1094         ucmd->ubuff = ubuff;
1095         ucmd->first_page_offset = (ubuff & ~PAGE_MASK);
1096
1097 out:
1098         TRACE_EXIT_RES(res);
1099         return res;
1100
1101 out_nomem:
1102         scst_set_busy(ucmd->cmd);
1103         /* go through */
1104
1105 out_err:
1106         scst_set_cmd_abnormal_done_state(ucmd->cmd);
1107         goto out;
1108
1109 out_unmap:
1110         PRINT_ERROR("Failed to get %d user pages (rc %d)",
1111                 ucmd->num_data_pages, rc);
1112         if (rc > 0) {
1113                 for (i = 0; i < rc; i++)
1114                         page_cache_release(ucmd->data_pages[i]);
1115         }
1116         kfree(ucmd->data_pages);
1117         ucmd->data_pages = NULL;
1118         res = -EFAULT;
1119         scst_set_cmd_error(ucmd->cmd, SCST_LOAD_SENSE(scst_sense_hardw_error));
1120         goto out_err;
1121 }
1122
1123 static int dev_user_process_reply_alloc(struct scst_user_cmd *ucmd,
1124         struct scst_user_reply_cmd *reply)
1125 {
1126         int res = 0;
1127         struct scst_cmd *cmd = ucmd->cmd;
1128
1129         TRACE_ENTRY();
1130
1131         TRACE_DBG("ucmd %p, pbuf %llx", ucmd, reply->alloc_reply.pbuf);
1132
1133         if (likely(reply->alloc_reply.pbuf != 0)) {
1134                 int pages;
1135                 if (ucmd->buff_cached) {
1136                         if (unlikely((reply->alloc_reply.pbuf & ~PAGE_MASK) != 0)) {
1137                                 PRINT_ERROR("Supplied pbuf %llx isn't "
1138                                         "page aligned",
1139                                         reply->alloc_reply.pbuf);
1140                                 goto out_hwerr;
1141                         }
1142                         pages = cmd->sg_cnt;
1143                 } else
1144                         pages = calc_num_pg(reply->alloc_reply.pbuf,
1145                                             cmd->bufflen);
1146                 res = dev_user_map_buf(ucmd, reply->alloc_reply.pbuf, pages);
1147         } else {
1148                 scst_set_busy(ucmd->cmd);
1149                 scst_set_cmd_abnormal_done_state(ucmd->cmd);
1150         }
1151
1152 out_process:
1153         scst_process_active_cmd(cmd, false);
1154
1155         TRACE_EXIT_RES(res);
1156         return res;
1157
1158 out_hwerr:
1159         scst_set_cmd_error(cmd, SCST_LOAD_SENSE(scst_sense_hardw_error));
1160         scst_set_cmd_abnormal_done_state(ucmd->cmd);
1161         res = -EINVAL;
1162         goto out_process;
1163 }
1164
1165 static int dev_user_process_reply_parse(struct scst_user_cmd *ucmd,
1166         struct scst_user_reply_cmd *reply)
1167 {
1168         int res = 0;
1169         struct scst_user_scsi_cmd_reply_parse *preply =
1170                 &reply->parse_reply;
1171         struct scst_cmd *cmd = ucmd->cmd;
1172
1173         TRACE_ENTRY();
1174
1175         if (unlikely(preply->queue_type > SCST_CMD_QUEUE_ACA))
1176                 goto out_inval;
1177
1178         if (unlikely((preply->data_direction != SCST_DATA_WRITE) &&
1179                      (preply->data_direction != SCST_DATA_READ) &&
1180                      (preply->data_direction != SCST_DATA_NONE)))
1181                 goto out_inval;
1182
1183         if (unlikely((preply->data_direction != SCST_DATA_NONE) &&
1184                      (preply->bufflen == 0)))
1185                 goto out_inval;
1186
1187         if (unlikely((preply->bufflen < 0) || (preply->data_len < 0)))
1188                 goto out_inval;
1189
1190         TRACE_DBG("ucmd %p, queue_type %x, data_direction, %x, bufflen %d, "
1191                 "data_len %d, pbuf %llx", ucmd, preply->queue_type,
1192                 preply->data_direction, preply->bufflen, preply->data_len,
1193                 reply->alloc_reply.pbuf);
1194
1195         cmd->queue_type = preply->queue_type;
1196         cmd->data_direction = preply->data_direction;
1197         cmd->bufflen = preply->bufflen;
1198         cmd->data_len = preply->data_len;
1199
1200 out_process:
1201         scst_process_active_cmd(cmd, false);
1202
1203         TRACE_EXIT_RES(res);
1204         return res;
1205
1206 out_inval:
1207         PRINT_ERROR("Invalid parse_reply parameters (LUN %lld, op %x, cmd %p)",
1208                 (long long unsigned int)cmd->lun, cmd->cdb[0], cmd);
1209         PRINT_BUFFER("Invalid parse_reply", reply, sizeof(*reply));
1210         scst_set_cmd_error(cmd, SCST_LOAD_SENSE(scst_sense_hardw_error));
1211         scst_set_cmd_abnormal_done_state(cmd);
1212         res = -EINVAL;
1213         goto out_process;
1214 }
1215
1216 static int dev_user_process_reply_on_free(struct scst_user_cmd *ucmd)
1217 {
1218         int res = 0;
1219
1220         TRACE_ENTRY();
1221
1222         TRACE_DBG("ON FREE ucmd %p", ucmd);
1223
1224         dev_user_free_sgv(ucmd);
1225         ucmd_put(ucmd);
1226
1227         TRACE_EXIT_RES(res);
1228         return res;
1229 }
1230
1231 static int dev_user_process_reply_on_cache_free(struct scst_user_cmd *ucmd)
1232 {
1233         int res = 0;
1234
1235         TRACE_ENTRY();
1236
1237         TRACE_DBG("ON CACHE FREE ucmd %p", ucmd);
1238
1239         ucmd_put(ucmd);
1240
1241         TRACE_EXIT_RES(res);
1242         return res;
1243 }
1244
1245 static int dev_user_process_reply_exec(struct scst_user_cmd *ucmd,
1246         struct scst_user_reply_cmd *reply)
1247 {
1248         int res = 0;
1249         struct scst_user_scsi_cmd_reply_exec *ereply =
1250                 &reply->exec_reply;
1251         struct scst_cmd *cmd = ucmd->cmd;
1252
1253         TRACE_ENTRY();
1254
1255         if (ereply->reply_type == SCST_EXEC_REPLY_COMPLETED) {
1256                 if (ucmd->background_exec) {
1257                         TRACE_DBG("Background ucmd %p finished", ucmd);
1258                         ucmd_put(ucmd);
1259                         goto out;
1260                 }
1261                 if (unlikely(ereply->resp_data_len > cmd->bufflen))
1262                         goto out_inval;
1263                 if (unlikely((cmd->data_direction != SCST_DATA_READ) &&
1264                              (ereply->resp_data_len != 0)))
1265                         goto out_inval;
1266         } else if (ereply->reply_type == SCST_EXEC_REPLY_BACKGROUND) {
1267                 if (unlikely(ucmd->background_exec))
1268                         goto out_inval;
1269                 if (unlikely((cmd->data_direction == SCST_DATA_READ) ||
1270                              (cmd->resp_data_len != 0)))
1271                         goto out_inval;
1272                 ucmd_get_ordered(ucmd);
1273                 ucmd->background_exec = 1;
1274                 TRACE_DBG("Background ucmd %p", ucmd);
1275                 goto out_compl;
1276         } else
1277                 goto out_inval;
1278
1279         TRACE_DBG("ucmd %p, status %d, resp_data_len %d", ucmd,
1280                 ereply->status, ereply->resp_data_len);
1281
1282          if (ereply->resp_data_len != 0) {
1283                 if (ucmd->ubuff == 0) {
1284                         int pages, rc;
1285                         if (unlikely(ereply->pbuf == 0))
1286                                 goto out_busy;
1287                         if (ucmd->buff_cached) {
1288                                 if (unlikely((ereply->pbuf & ~PAGE_MASK) != 0)) {
1289                                         PRINT_ERROR("Supplied pbuf %llx isn't "
1290                                                 "page aligned", ereply->pbuf);
1291                                         goto out_hwerr;
1292                                 }
1293                                 pages = cmd->sg_cnt;
1294                         } else
1295                                 pages = calc_num_pg(ereply->pbuf, cmd->bufflen);
1296                         rc = dev_user_map_buf(ucmd, ereply->pbuf, pages);
1297                         if ((rc != 0) || (ucmd->ubuff == 0))
1298                                 goto out_compl;
1299
1300                         rc = dev_user_alloc_sg(ucmd, ucmd->buff_cached);
1301                         if (unlikely(rc != 0))
1302                                 goto out_busy;
1303                 } else
1304                         dev_user_flush_dcache(ucmd);
1305                 cmd->may_need_dma_sync = 1;
1306                 scst_set_resp_data_len(cmd, ereply->resp_data_len);
1307         } else if (cmd->resp_data_len != ereply->resp_data_len) {
1308                 if (ucmd->ubuff == 0)
1309                         cmd->resp_data_len = ereply->resp_data_len;
1310                 else
1311                         scst_set_resp_data_len(cmd, ereply->resp_data_len);
1312         }
1313
1314         cmd->status = ereply->status;
1315         if (ereply->sense_len != 0) {
1316                 res = scst_alloc_sense(cmd, 0);
1317                 if (res != 0)
1318                         goto out_compl;
1319                 res = copy_from_user(cmd->sense,
1320                         (void __user *)(unsigned long)ereply->psense_buffer,
1321                         min((unsigned int)SCST_SENSE_BUFFERSIZE,
1322                                 (unsigned int)ereply->sense_len));
1323                 if (res < 0) {
1324                         PRINT_ERROR("%s", "Unable to get sense data");
1325                         goto out_hwerr_res_set;
1326                 }
1327         }
1328
1329 out_compl:
1330         cmd->completed = 1;
1331         cmd->scst_cmd_done(cmd, SCST_CMD_STATE_DEFAULT, SCST_CONTEXT_DIRECT);
1332         /* !! At this point cmd can be already freed !! */
1333
1334 out:
1335         TRACE_EXIT_RES(res);
1336         return res;
1337
1338 out_inval:
1339         PRINT_ERROR("Invalid exec_reply parameters (LUN %lld, op %x, cmd %p)",
1340                 (long long unsigned int)cmd->lun, cmd->cdb[0], cmd);
1341         PRINT_BUFFER("Invalid exec_reply", reply, sizeof(*reply));
1342
1343 out_hwerr:
1344         res = -EINVAL;
1345
1346 out_hwerr_res_set:
1347         if (ucmd->background_exec) {
1348                 ucmd_put(ucmd);
1349                 goto out;
1350         } else {
1351                 scst_set_cmd_error(cmd,
1352                                    SCST_LOAD_SENSE(scst_sense_hardw_error));
1353                 goto out_compl;
1354         }
1355
1356 out_busy:
1357         scst_set_busy(cmd);
1358         goto out_compl;
1359 }
1360
1361 static int dev_user_process_reply(struct scst_user_dev *dev,
1362         struct scst_user_reply_cmd *reply)
1363 {
1364         int res = 0;
1365         struct scst_user_cmd *ucmd;
1366         int state;
1367
1368         TRACE_ENTRY();
1369
1370         spin_lock_irq(&dev->cmd_lists.cmd_list_lock);
1371
1372         ucmd = __ucmd_find_hash(dev, reply->cmd_h);
1373         if (unlikely(ucmd == NULL)) {
1374                 TRACE_MGMT_DBG("cmd_h %d not found", reply->cmd_h);
1375                 res = -ESRCH;
1376                 goto out_unlock;
1377         }
1378
1379         if (unlikely(ucmd_get_check(ucmd))) {
1380                 TRACE_MGMT_DBG("Found being destroyed cmd_h %d", reply->cmd_h);
1381                 res = -ESRCH;
1382                 goto out_unlock;
1383         }
1384
1385         if (ucmd->background_exec) {
1386                 state = UCMD_STATE_EXECING;
1387                 goto unlock_process;
1388         }
1389
1390         if (unlikely(ucmd->this_state_unjammed)) {
1391                 TRACE_MGMT_DBG("Reply on unjammed ucmd %p, ignoring",
1392                         ucmd);
1393                 goto out_unlock_put;
1394         }
1395
1396         if (unlikely(!ucmd->sent_to_user)) {
1397                 TRACE_MGMT_DBG("Ucmd %p isn't in the sent to user "
1398                         "state %x", ucmd, ucmd->state);
1399                 res = -EINVAL;
1400                 goto out_unlock_put;
1401         }
1402
1403         if (unlikely(reply->subcode != ucmd->user_cmd.subcode))
1404                 goto out_wrong_state;
1405
1406         if (unlikely(_IOC_NR(reply->subcode) != ucmd->state))
1407                 goto out_wrong_state;
1408
1409         state = ucmd->state;
1410         ucmd->sent_to_user = 0;
1411
1412 unlock_process:
1413         spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
1414
1415         switch (state) {
1416         case UCMD_STATE_PARSING:
1417                 res = dev_user_process_reply_parse(ucmd, reply);
1418                 break;
1419
1420         case UCMD_STATE_BUF_ALLOCING:
1421                 res = dev_user_process_reply_alloc(ucmd, reply);
1422                 break;
1423
1424         case UCMD_STATE_EXECING:
1425                 res = dev_user_process_reply_exec(ucmd, reply);
1426                 break;
1427
1428         case UCMD_STATE_ON_FREEING:
1429                 res = dev_user_process_reply_on_free(ucmd);
1430                 break;
1431
1432         case UCMD_STATE_ON_CACHE_FREEING:
1433                 res = dev_user_process_reply_on_cache_free(ucmd);
1434                 break;
1435
1436         case UCMD_STATE_TM_EXECING:
1437                 res = dev_user_process_reply_tm_exec(ucmd, reply->result);
1438                 break;
1439
1440         case UCMD_STATE_ATTACH_SESS:
1441         case UCMD_STATE_DETACH_SESS:
1442                 res = dev_user_process_reply_sess(ucmd, reply->result);
1443                 break;
1444
1445         default:
1446                 sBUG();
1447                 break;
1448         }
1449
1450 out_put:
1451         ucmd_put(ucmd);
1452
1453 out:
1454         TRACE_EXIT_RES(res);
1455         return res;
1456
1457 out_wrong_state:
1458         PRINT_ERROR("Command's %p subcode %x doesn't match internal "
1459                 "command's state %x or reply->subcode (%x) != ucmd->subcode "
1460                 "(%x)", ucmd, _IOC_NR(reply->subcode), ucmd->state,
1461                 reply->subcode, ucmd->user_cmd.subcode);
1462         res = -EINVAL;
1463         dev_user_unjam_cmd(ucmd, 0, NULL);
1464
1465 out_unlock_put:
1466         spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
1467         goto out_put;
1468
1469 out_unlock:
1470         spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
1471         goto out;
1472 }
1473
1474 static int dev_user_reply_cmd(struct file *file, void __user *arg)
1475 {
1476         int res = 0;
1477         struct scst_user_dev *dev;
1478         struct scst_user_reply_cmd reply;
1479
1480         TRACE_ENTRY();
1481
1482         mutex_lock(&dev_priv_mutex);
1483         dev = (struct scst_user_dev *)file->private_data;
1484         res = dev_user_check_reg(dev);
1485         if (res != 0) {
1486                 mutex_unlock(&dev_priv_mutex);
1487                 goto out;
1488         }
1489         down_read(&dev->dev_rwsem);
1490         mutex_unlock(&dev_priv_mutex);
1491
1492         res = copy_from_user(&reply, arg, sizeof(reply));
1493         if (res < 0)
1494                 goto out_up;
1495
1496         TRACE_MGMT_DBG("Reply for dev %s", dev->name);
1497
1498         TRACE_BUFFER("Reply", &reply, sizeof(reply));
1499
1500         res = dev_user_process_reply(dev, &reply);
1501         if (res < 0)
1502                 goto out_up;
1503
1504 out_up:
1505         up_read(&dev->dev_rwsem);
1506
1507 out:
1508         TRACE_EXIT_RES(res);
1509         return res;
1510 }
1511
1512 static int dev_user_process_scst_commands(struct scst_user_dev *dev)
1513 {
1514         int res = 0;
1515
1516         TRACE_ENTRY();
1517
1518         while (!list_empty(&dev->cmd_lists.active_cmd_list)) {
1519                 struct scst_cmd *cmd = list_entry(
1520                         dev->cmd_lists.active_cmd_list.next, typeof(*cmd),
1521                         cmd_list_entry);
1522                 TRACE_DBG("Deleting cmd %p from active cmd list", cmd);
1523                 list_del(&cmd->cmd_list_entry);
1524                 spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
1525                 scst_process_active_cmd(cmd, false);
1526                 spin_lock_irq(&dev->cmd_lists.cmd_list_lock);
1527                 res++;
1528         }
1529
1530         TRACE_EXIT_RES(res);
1531         return res;
1532 }
1533
1534 /* Called under cmd_lists.cmd_list_lock and IRQ off */
1535 static struct scst_user_cmd *__dev_user_get_next_cmd(struct list_head *cmd_list)
1536 {
1537         struct scst_user_cmd *u;
1538
1539 again:
1540         u = NULL;
1541         if (!list_empty(cmd_list)) {
1542                 u = list_entry(cmd_list->next, typeof(*u),
1543                                ready_cmd_list_entry);
1544
1545                 TRACE_DBG("Found ready ucmd %p", u);
1546                 list_del(&u->ready_cmd_list_entry);
1547
1548                 EXTRACHECKS_BUG_ON(u->this_state_unjammed);
1549
1550                 if (u->cmd != NULL) {
1551                         if (u->state == UCMD_STATE_EXECING) {
1552                                 struct scst_user_dev *dev = u->dev;
1553                                 int rc;
1554
1555                                 EXTRACHECKS_BUG_ON(u->jammed);
1556
1557                                 spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
1558
1559                                 rc = scst_check_local_events(u->cmd);
1560                                 if (unlikely(rc != 0)) {
1561                                         u->cmd->scst_cmd_done(u->cmd,
1562                                                 SCST_CMD_STATE_DEFAULT,
1563                                                 SCST_CONTEXT_DIRECT);
1564                                         /*
1565                                          * !! At this point cmd & u can be !!
1566                                          * !! already freed                !!
1567                                          */
1568                                         spin_lock_irq(
1569                                                 &dev->cmd_lists.cmd_list_lock);
1570                                         goto again;
1571                                 }
1572
1573                                 spin_lock_irq(&dev->cmd_lists.cmd_list_lock);
1574                         } else if (unlikely(test_bit(SCST_CMD_ABORTED,
1575                                         &u->cmd->cmd_flags))) {
1576                                 switch (u->state) {
1577                                 case UCMD_STATE_PARSING:
1578                                 case UCMD_STATE_BUF_ALLOCING:
1579                                         TRACE_MGMT_DBG("Aborting ucmd %p", u);
1580                                         dev_user_unjam_cmd(u, 0, NULL);
1581                                         goto again;
1582                                 case UCMD_STATE_EXECING:
1583                                         EXTRACHECKS_BUG_ON(1);
1584                                 }
1585                         }
1586                 }
1587                 u->sent_to_user = 1;
1588                 u->seen_by_user = 1;
1589         }
1590         return u;
1591 }
1592
1593 static inline int test_cmd_lists(struct scst_user_dev *dev)
1594 {
1595         int res = !list_empty(&dev->cmd_lists.active_cmd_list) ||
1596                   !list_empty(&dev->ready_cmd_list) ||
1597                   !dev->blocking || dev->cleanup_done ||
1598                   signal_pending(current);
1599         return res;
1600 }
1601
1602 /* Called under cmd_lists.cmd_list_lock and IRQ off */
1603 static int dev_user_get_next_cmd(struct scst_user_dev *dev,
1604         struct scst_user_cmd **ucmd)
1605 {
1606         int res = 0;
1607         wait_queue_t wait;
1608
1609         TRACE_ENTRY();
1610
1611         init_waitqueue_entry(&wait, current);
1612
1613         while (1) {
1614                 if (!test_cmd_lists(dev)) {
1615                         add_wait_queue_exclusive(&dev->cmd_lists.cmd_list_waitQ,
1616                                 &wait);
1617                         for (;;) {
1618                                 set_current_state(TASK_INTERRUPTIBLE);
1619                                 if (test_cmd_lists(dev))
1620                                         break;
1621                                 spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
1622                                 schedule();
1623                                 spin_lock_irq(&dev->cmd_lists.cmd_list_lock);
1624                         }
1625                         set_current_state(TASK_RUNNING);
1626                         remove_wait_queue(&dev->cmd_lists.cmd_list_waitQ,
1627                                 &wait);
1628                 }
1629
1630                 dev_user_process_scst_commands(dev);
1631
1632                 *ucmd = __dev_user_get_next_cmd(&dev->ready_cmd_list);
1633                 if (*ucmd != NULL)
1634                         break;
1635
1636                 if (!dev->blocking || dev->cleanup_done) {
1637                         res = -EAGAIN;
1638                         TRACE_DBG("No ready commands, returning %d", res);
1639                         break;
1640                 }
1641
1642                 if (signal_pending(current)) {
1643                         res = -EINTR;
1644                         TRACE_DBG("Signal pending, returning %d", res);
1645                         break;
1646                 }
1647         }
1648
1649         TRACE_EXIT_RES(res);
1650         return res;
1651 }
1652
1653 static int dev_user_reply_get_cmd(struct file *file, void __user *arg)
1654 {
1655         int res = 0;
1656         struct scst_user_dev *dev;
1657         struct scst_user_get_cmd *cmd;
1658         struct scst_user_reply_cmd *reply;
1659         struct scst_user_cmd *ucmd;
1660         uint64_t ureply;
1661
1662         TRACE_ENTRY();
1663
1664         mutex_lock(&dev_priv_mutex);
1665         dev = (struct scst_user_dev *)file->private_data;
1666         res = dev_user_check_reg(dev);
1667         if (res != 0) {
1668                 mutex_unlock(&dev_priv_mutex);
1669                 goto out;
1670         }
1671         down_read(&dev->dev_rwsem);
1672         mutex_unlock(&dev_priv_mutex);
1673
1674         res = copy_from_user(&ureply, arg, sizeof(ureply));
1675         if (res < 0)
1676                 goto out_up;
1677
1678         TRACE_DBG("ureply %lld (dev %s)", (long long unsigned int)ureply,
1679                 dev->name);
1680
1681         cmd = kmem_cache_alloc(user_get_cmd_cachep, GFP_KERNEL);
1682         if (cmd == NULL) {
1683                 res = -ENOMEM;
1684                 goto out_up;
1685         }
1686
1687         if (ureply != 0) {
1688                 unsigned long u = (unsigned long)ureply;
1689                 reply = (struct scst_user_reply_cmd *)cmd;
1690                 res = copy_from_user(reply, (void __user *)u, sizeof(*reply));
1691                 if (res < 0)
1692                         goto out_free;
1693
1694                 TRACE_BUFFER("Reply", reply, sizeof(*reply));
1695
1696                 res = dev_user_process_reply(dev, reply);
1697                 if (res < 0)
1698                         goto out_free;
1699         }
1700
1701         spin_lock_irq(&dev->cmd_lists.cmd_list_lock);
1702         res = dev_user_get_next_cmd(dev, &ucmd);
1703         if (res == 0) {
1704                 *cmd = ucmd->user_cmd;
1705                 spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
1706                 TRACE_BUFFER("UCMD", cmd, sizeof(*cmd));
1707                 res = copy_to_user(arg, cmd, sizeof(*cmd));
1708         } else
1709                 spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
1710
1711 out_free:
1712         kmem_cache_free(user_get_cmd_cachep, cmd);
1713
1714 out_up:
1715         up_read(&dev->dev_rwsem);
1716
1717 out:
1718         TRACE_EXIT_RES(res);
1719         return res;
1720 }
1721
1722 static long dev_user_ioctl(struct file *file, unsigned int cmd,
1723         unsigned long arg)
1724 {
1725         long res;
1726
1727         TRACE_ENTRY();
1728
1729         switch (cmd) {
1730         case SCST_USER_REPLY_AND_GET_CMD:
1731                 TRACE_DBG("%s", "REPLY_AND_GET_CMD");
1732                 res = dev_user_reply_get_cmd(file, (void __user *)arg);
1733                 break;
1734
1735         case SCST_USER_REPLY_CMD:
1736                 TRACE_DBG("%s", "REPLY_CMD");
1737                 res = dev_user_reply_cmd(file, (void __user *)arg);
1738                 break;
1739
1740         case SCST_USER_REGISTER_DEVICE:
1741         {
1742                 struct scst_user_dev_desc *dev_desc;
1743                 TRACE_DBG("%s", "REGISTER_DEVICE");
1744                 dev_desc = kmalloc(sizeof(*dev_desc), GFP_KERNEL);
1745                 if (dev_desc == NULL) {
1746                         res = -ENOMEM;
1747                         goto out;
1748                 }
1749                 res = copy_from_user(dev_desc, (void __user *)arg,
1750                                      sizeof(*dev_desc));
1751                 if (res < 0) {
1752                         kfree(dev_desc);
1753                         goto out;
1754                 }
1755                 TRACE_BUFFER("dev_desc", dev_desc, sizeof(*dev_desc));
1756                 dev_desc->name[sizeof(dev_desc->name)-1] = '\0';
1757                 res = dev_user_register_dev(file, dev_desc);
1758                 kfree(dev_desc);
1759                 break;
1760         }
1761
1762         case SCST_USER_SET_OPTIONS:
1763         {
1764                 struct scst_user_opt opt;
1765                 TRACE_DBG("%s", "SET_OPTIONS");
1766                 res = copy_from_user(&opt, (void __user *)arg, sizeof(opt));
1767                 if (res < 0)
1768                         goto out;
1769                 TRACE_BUFFER("opt", &opt, sizeof(opt));
1770                 res = dev_user_set_opt(file, &opt);
1771                 break;
1772         }
1773
1774         case SCST_USER_GET_OPTIONS:
1775                 TRACE_DBG("%s", "GET_OPTIONS");
1776                 res = dev_user_get_opt(file, (void __user *)arg);
1777                 break;
1778
1779         default:
1780                 PRINT_ERROR("Invalid ioctl cmd %x", cmd);
1781                 res = -EINVAL;
1782                 goto out;
1783         }
1784
1785 out:
1786         TRACE_EXIT_RES(res);
1787         return res;
1788 }
1789
1790 static unsigned int dev_user_poll(struct file *file, poll_table *wait)
1791 {
1792         int res = 0;
1793         struct scst_user_dev *dev;
1794
1795         TRACE_ENTRY();
1796
1797         mutex_lock(&dev_priv_mutex);
1798         dev = (struct scst_user_dev *)file->private_data;
1799         res = dev_user_check_reg(dev);
1800         if (res != 0) {
1801                 mutex_unlock(&dev_priv_mutex);
1802                 goto out;
1803         }
1804         down_read(&dev->dev_rwsem);
1805         mutex_unlock(&dev_priv_mutex);
1806
1807         spin_lock_irq(&dev->cmd_lists.cmd_list_lock);
1808
1809         if (!list_empty(&dev->ready_cmd_list) ||
1810             !list_empty(&dev->cmd_lists.active_cmd_list)) {
1811                 res |= POLLIN | POLLRDNORM;
1812                 goto out_unlock;
1813         }
1814
1815         spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
1816
1817         TRACE_DBG("Before poll_wait() (dev %s)", dev->name);
1818         poll_wait(file, &dev->cmd_lists.cmd_list_waitQ, wait);
1819         TRACE_DBG("After poll_wait() (dev %s)", dev->name);
1820
1821         spin_lock_irq(&dev->cmd_lists.cmd_list_lock);
1822
1823         if (!list_empty(&dev->ready_cmd_list) ||
1824             !list_empty(&dev->cmd_lists.active_cmd_list)) {
1825                 res |= POLLIN | POLLRDNORM;
1826                 goto out_unlock;
1827         }
1828
1829 out_unlock:
1830         spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
1831
1832         up_read(&dev->dev_rwsem);
1833
1834 out:
1835         TRACE_EXIT_HRES(res);
1836         return res;
1837 }
1838
1839 /*
1840  * Called under cmd_lists.cmd_list_lock, but can drop it inside, then reacquire.
1841  */
1842 static void dev_user_unjam_cmd(struct scst_user_cmd *ucmd, int busy,
1843         unsigned long *flags)
1844 {
1845         int state = ucmd->state;
1846         struct scst_user_dev *dev = ucmd->dev;
1847
1848         TRACE_ENTRY();
1849
1850         if (ucmd->this_state_unjammed)
1851                 goto out;
1852
1853         TRACE_MGMT_DBG("Unjamming ucmd %p (busy %d, state %x)", ucmd, busy,
1854                 state);
1855
1856         ucmd->jammed = 1;
1857         ucmd->this_state_unjammed = 1;
1858         ucmd->sent_to_user = 0;
1859
1860         switch (state) {
1861         case UCMD_STATE_PARSING:
1862         case UCMD_STATE_BUF_ALLOCING:
1863                 if (test_bit(SCST_CMD_ABORTED, &ucmd->cmd->cmd_flags))
1864                         ucmd->aborted = 1;
1865                 else {
1866                         if (busy)
1867                                 scst_set_busy(ucmd->cmd);
1868                         else
1869                                 scst_set_cmd_error(ucmd->cmd,
1870                                        SCST_LOAD_SENSE(scst_sense_hardw_error));
1871                 }
1872                 scst_set_cmd_abnormal_done_state(ucmd->cmd);
1873
1874                 TRACE_MGMT_DBG("Adding ucmd %p to active list", ucmd);
1875                 list_add(&ucmd->cmd->cmd_list_entry,
1876                         &ucmd->cmd->cmd_lists->active_cmd_list);
1877                 wake_up(&ucmd->dev->cmd_lists.cmd_list_waitQ);
1878                 break;
1879
1880         case UCMD_STATE_EXECING:
1881                 if (flags != NULL)
1882                         spin_unlock_irqrestore(&dev->cmd_lists.cmd_list_lock,
1883                                                *flags);
1884                 else
1885                         spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
1886
1887                 TRACE_MGMT_DBG("EXEC: unjamming ucmd %p", ucmd);
1888
1889                 if (test_bit(SCST_CMD_ABORTED, &ucmd->cmd->cmd_flags))
1890                         ucmd->aborted = 1;
1891                 else {
1892                         if (busy)
1893                                 scst_set_busy(ucmd->cmd);
1894                         else
1895                                 scst_set_cmd_error(ucmd->cmd,
1896                                        SCST_LOAD_SENSE(scst_sense_hardw_error));
1897                 }
1898
1899                 ucmd->cmd->scst_cmd_done(ucmd->cmd, SCST_CMD_STATE_DEFAULT,
1900                         SCST_CONTEXT_DIRECT);
1901                 /* !! At this point cmd and ucmd can be already freed !! */
1902
1903                 if (flags != NULL)
1904                         spin_lock_irqsave(&dev->cmd_lists.cmd_list_lock,
1905                                           *flags);
1906                 else
1907                         spin_lock_irq(&dev->cmd_lists.cmd_list_lock);
1908                 break;
1909
1910         case UCMD_STATE_ON_FREEING:
1911         case UCMD_STATE_ON_CACHE_FREEING:
1912         case UCMD_STATE_TM_EXECING:
1913         case UCMD_STATE_ATTACH_SESS:
1914         case UCMD_STATE_DETACH_SESS:
1915         {
1916                 if (flags != NULL)
1917                         spin_unlock_irqrestore(&dev->cmd_lists.cmd_list_lock,
1918                                                *flags);
1919                 else
1920                         spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
1921
1922                 switch (state) {
1923                 case UCMD_STATE_ON_FREEING:
1924                         dev_user_process_reply_on_free(ucmd);
1925                         break;
1926
1927                 case UCMD_STATE_ON_CACHE_FREEING:
1928                         dev_user_process_reply_on_cache_free(ucmd);
1929                         break;
1930
1931                 case UCMD_STATE_TM_EXECING:
1932                         dev_user_process_reply_tm_exec(ucmd,
1933                                                        SCST_MGMT_STATUS_FAILED);
1934                         break;
1935
1936                 case UCMD_STATE_ATTACH_SESS:
1937                 case UCMD_STATE_DETACH_SESS:
1938                         dev_user_process_reply_sess(ucmd, -EFAULT);
1939                         break;
1940                 }
1941
1942                 if (flags != NULL)
1943                         spin_lock_irqsave(&dev->cmd_lists.cmd_list_lock,
1944                                           *flags);
1945                 else
1946                         spin_lock_irq(&dev->cmd_lists.cmd_list_lock);
1947                 break;
1948         }
1949
1950         default:
1951                 PRINT_CRIT_ERROR("Wrong ucmd state %x", state);
1952                 sBUG();
1953                 break;
1954         }
1955
1956 out:
1957         TRACE_EXIT();
1958         return;
1959 }
1960
1961 static void dev_user_unjam_dev(struct scst_user_dev *dev)
1962 {
1963         int i;
1964         struct scst_user_cmd *ucmd;
1965
1966         TRACE_ENTRY();
1967
1968         TRACE_MGMT_DBG("Unjamming dev %p", dev);
1969
1970         spin_lock_irq(&dev->cmd_lists.cmd_list_lock);
1971
1972 repeat:
1973         for (i = 0; i < (int)ARRAY_SIZE(dev->ucmd_hash); i++) {
1974                 struct list_head *head = &dev->ucmd_hash[i];
1975
1976                 list_for_each_entry(ucmd, head, hash_list_entry) {
1977                         if (!ucmd->sent_to_user)
1978                                 continue;
1979
1980                         if (ucmd_get_check(ucmd))
1981                                 continue;
1982
1983                         TRACE_MGMT_DBG("ucmd %p, state %x, scst_cmd %p", ucmd,
1984                                 ucmd->state, ucmd->cmd);
1985
1986                         dev_user_unjam_cmd(ucmd, 0, NULL);
1987
1988                         spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
1989                         ucmd_put(ucmd);
1990                         spin_lock_irq(&dev->cmd_lists.cmd_list_lock);
1991
1992                         goto repeat;
1993                 }
1994         }
1995
1996         if (dev_user_process_scst_commands(dev) != 0)
1997                 goto repeat;
1998
1999         spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
2000
2001         TRACE_EXIT();
2002         return;
2003 }
2004
2005 static int dev_user_process_reply_tm_exec(struct scst_user_cmd *ucmd,
2006         int status)
2007 {
2008         int res = 0;
2009
2010         TRACE_ENTRY();
2011
2012         TRACE_MGMT_DBG("TM reply (ucmd %p, fn %d, status %d)", ucmd,
2013                 ucmd->user_cmd.tm_cmd.fn, status);
2014
2015         if (status == SCST_MGMT_STATUS_TASK_NOT_EXIST) {
2016                 /*
2017                  * It is possible that user space seen TM cmd before cmd
2018                  * to abort or will never see it at all, because it was
2019                  * aborted on the way there. So, it is safe to return
2020                  * success instead, because, if there is the TM cmd at this
2021                  * point, then the cmd to abort apparrently does exist.
2022                  */
2023                 status = SCST_MGMT_STATUS_SUCCESS;
2024         }
2025
2026         scst_async_mcmd_completed(ucmd->mcmd, status);
2027
2028         ucmd_put(ucmd);
2029
2030         TRACE_EXIT_RES(res);
2031         return res;
2032 }
2033
2034 static void dev_user_abort_ready_commands(struct scst_user_dev *dev)
2035 {
2036         struct scst_user_cmd *ucmd;
2037         unsigned long flags;
2038
2039         TRACE_ENTRY();
2040
2041         spin_lock_irqsave(&dev->cmd_lists.cmd_list_lock, flags);
2042 again:
2043         list_for_each_entry(ucmd, &dev->ready_cmd_list, ready_cmd_list_entry) {
2044                 if ((ucmd->cmd != NULL) && !ucmd->seen_by_user &&
2045                     test_bit(SCST_CMD_ABORTED, &ucmd->cmd->cmd_flags)) {
2046                         switch (ucmd->state) {
2047                         case UCMD_STATE_PARSING:
2048                         case UCMD_STATE_BUF_ALLOCING:
2049                         case UCMD_STATE_EXECING:
2050                                 TRACE_MGMT_DBG("Aborting ready ucmd %p", ucmd);
2051                                 list_del(&ucmd->ready_cmd_list_entry);
2052                                 dev_user_unjam_cmd(ucmd, 0, &flags);
2053                                 goto again;
2054                         }
2055                 }
2056         }
2057
2058         spin_unlock_irqrestore(&dev->cmd_lists.cmd_list_lock, flags);
2059
2060         TRACE_EXIT();
2061         return;
2062 }
2063
2064 static int dev_user_task_mgmt_fn(struct scst_mgmt_cmd *mcmd,
2065         struct scst_tgt_dev *tgt_dev)
2066 {
2067         struct scst_user_cmd *ucmd;
2068         struct scst_user_dev *dev =
2069                 (struct scst_user_dev *)tgt_dev->dev->dh_priv;
2070         struct scst_user_cmd *ucmd_to_abort = NULL;
2071
2072         TRACE_ENTRY();
2073
2074         /*
2075          * In the used approach we don't do anything with hung devices, which
2076          * stopped responding and/or have stuck commands. We forcedly abort such
2077          * commands only if they not yet sent to the user space or if the device
2078          * is getting unloaded, e.g. if its handler program gets killed. This is
2079          * because it's pretty hard to distinguish between stuck and temporary
2080          * overloaded states of the device. There are several reasons for that:
2081          *
2082          * 1. Some commands need a lot of time to complete (several hours),
2083          *    so for an impatient user such command(s) will always look as
2084          *    stuck.
2085          *
2086          * 2. If we forcedly abort, i.e. abort before it's actually completed
2087          *    in the user space, just one command, we will have to put the whole
2088          *    device offline until we are sure that no more previously aborted
2089          *    commands will get executed. Otherwise, we might have a possibility
2090          *    for data corruption, when aborted and reported as completed
2091          *    command actually gets executed *after* new commands sent
2092          *    after the force abort was done. Many journaling file systems and
2093          *    databases use "provide required commands order via queue draining"
2094          *    approach and not putting the whole device offline after the forced
2095          *    abort will break it. This makes our decision, if a command stuck
2096          *    or not, cost a lot.
2097          *
2098          * So, we leave policy definition if a device stuck or not to
2099          * the user space and simply let all commands live until they are
2100          * completed or their devices get closed/killed. This approach is very
2101          * much OK, but can affect management commands, which need activity
2102          * suspending via scst_suspend_activity() function such as devices or
2103          * targets registration/removal. But during normal life such commands
2104          * should be rare. Plus, when possible, scst_suspend_activity() will
2105          * return after timeout EBUSY status to allow caller to not stuck
2106          * forever as well.
2107          *
2108          * But, anyway, ToDo, we should reimplement that in the SCST core, so
2109          * stuck commands would affect only related devices.
2110          */
2111
2112         dev_user_abort_ready_commands(dev);
2113
2114         /* We can't afford missing TM command due to memory shortage */
2115         ucmd = dev_user_alloc_ucmd(dev, GFP_KERNEL|__GFP_NOFAIL);
2116
2117         ucmd->user_cmd.cmd_h = ucmd->h;
2118         ucmd->user_cmd.subcode = SCST_USER_TASK_MGMT;
2119         ucmd->user_cmd.tm_cmd.sess_h = (unsigned long)tgt_dev;
2120         ucmd->user_cmd.tm_cmd.fn = mcmd->fn;
2121         ucmd->user_cmd.tm_cmd.cmd_sn = mcmd->cmd_sn;
2122         ucmd->user_cmd.tm_cmd.cmd_sn_set = mcmd->cmd_sn_set;
2123
2124         if (mcmd->cmd_to_abort != NULL) {
2125                 ucmd_to_abort =
2126                         (struct scst_user_cmd *)mcmd->cmd_to_abort->dh_priv;
2127                 if (ucmd_to_abort != NULL)
2128                         ucmd->user_cmd.tm_cmd.cmd_h_to_abort = ucmd_to_abort->h;
2129         }
2130
2131         TRACE_MGMT_DBG("Preparing TM ucmd %p (h %d, fn %d, cmd_to_abort %p, "
2132                 "ucmd_to_abort %p, cmd_h_to_abort %d)", ucmd, ucmd->h,
2133                 mcmd->fn, mcmd->cmd_to_abort, ucmd_to_abort,
2134                 ucmd->user_cmd.tm_cmd.cmd_h_to_abort);
2135
2136         ucmd->mcmd = mcmd;
2137         ucmd->state = UCMD_STATE_TM_EXECING;
2138
2139         scst_prepare_async_mcmd(mcmd);
2140
2141         dev_user_add_to_ready(ucmd);
2142
2143         TRACE_EXIT();
2144         return SCST_DEV_TM_NOT_COMPLETED;
2145 }
2146
2147 static int dev_user_attach(struct scst_device *sdev)
2148 {
2149         int res = 0;
2150         struct scst_user_dev *dev = NULL, *d;
2151
2152         TRACE_ENTRY();
2153
2154         spin_lock(&dev_list_lock);
2155         list_for_each_entry(d, &dev_list, dev_list_entry) {
2156                 if (strcmp(d->name, sdev->virt_name) == 0) {
2157                         dev = d;
2158                         break;
2159                 }
2160         }
2161         spin_unlock(&dev_list_lock);
2162         if (dev == NULL) {
2163                 PRINT_ERROR("Device %s not found", sdev->virt_name);
2164                 res = -EINVAL;
2165                 goto out;
2166         }
2167
2168         sdev->p_cmd_lists = &dev->cmd_lists;
2169         sdev->dh_priv = dev;
2170         sdev->tst = dev->tst;
2171         sdev->queue_alg = dev->queue_alg;
2172         sdev->swp = dev->swp;
2173         sdev->tas = dev->tas;
2174         sdev->has_own_order_mgmt = dev->has_own_order_mgmt;
2175
2176         dev->sdev = sdev;
2177
2178         PRINT_INFO("Attached user space SCSI target virtual device \"%s\"",
2179                 dev->name);
2180
2181 out:
2182         TRACE_EXIT();
2183         return res;
2184 }
2185
2186 static void dev_user_detach(struct scst_device *sdev)
2187 {
2188         struct scst_user_dev *dev = (struct scst_user_dev *)sdev->dh_priv;
2189
2190         TRACE_ENTRY();
2191
2192         TRACE_DBG("virt_id %d", sdev->virt_id);
2193
2194         PRINT_INFO("Detached user space SCSI target virtual device \"%s\"",
2195                 dev->name);
2196
2197         /* dev will be freed by the caller */
2198         sdev->dh_priv = NULL;
2199         dev->sdev = NULL;
2200
2201         TRACE_EXIT();
2202         return;
2203 }
2204
2205 static int dev_user_process_reply_sess(struct scst_user_cmd *ucmd, int status)
2206 {
2207         int res = 0;
2208         unsigned long flags;
2209
2210         TRACE_ENTRY();
2211
2212         TRACE_MGMT_DBG("ucmd %p, cmpl %p, status %d", ucmd, ucmd->cmpl, status);
2213
2214         spin_lock_irqsave(&ucmd->dev->cmd_lists.cmd_list_lock, flags);
2215
2216         if (ucmd->state == UCMD_STATE_ATTACH_SESS) {
2217                 TRACE_MGMT_DBG("%s", "ATTACH_SESS finished");
2218                 ucmd->result = status;
2219         } else if (ucmd->state == UCMD_STATE_DETACH_SESS) {
2220                 TRACE_MGMT_DBG("%s", "DETACH_SESS finished");
2221         } else
2222                 sBUG();
2223
2224         if (ucmd->cmpl != NULL)
2225                 complete_all(ucmd->cmpl);
2226
2227         spin_unlock_irqrestore(&ucmd->dev->cmd_lists.cmd_list_lock, flags);
2228
2229         ucmd_put(ucmd);
2230
2231         TRACE_EXIT_RES(res);
2232         return res;
2233 }
2234
2235 static int dev_user_attach_tgt(struct scst_tgt_dev *tgt_dev)
2236 {
2237         struct scst_user_dev *dev =
2238                 (struct scst_user_dev *)tgt_dev->dev->dh_priv;
2239         int res = 0, rc;
2240         struct scst_user_cmd *ucmd;
2241         DECLARE_COMPLETION_ONSTACK(cmpl);
2242
2243         TRACE_ENTRY();
2244
2245         ucmd = dev_user_alloc_ucmd(dev, GFP_KERNEL);
2246         if (ucmd == NULL)
2247                 goto out_nomem;
2248
2249         ucmd->cmpl = &cmpl;
2250
2251         ucmd->user_cmd.cmd_h = ucmd->h;
2252         ucmd->user_cmd.subcode = SCST_USER_ATTACH_SESS;
2253         ucmd->user_cmd.sess.sess_h = (unsigned long)tgt_dev;
2254         ucmd->user_cmd.sess.lun = (uint64_t)tgt_dev->lun;
2255         ucmd->user_cmd.sess.threads_num = tgt_dev->sess->tgt->tgtt->threads_num;
2256         ucmd->user_cmd.sess.rd_only = tgt_dev->acg_dev->rd_only_flag;
2257         strncpy(ucmd->user_cmd.sess.initiator_name,
2258                 tgt_dev->sess->initiator_name,
2259                 sizeof(ucmd->user_cmd.sess.initiator_name)-1);
2260         ucmd->user_cmd.sess.initiator_name[
2261                 sizeof(ucmd->user_cmd.sess.initiator_name)-1] = '\0';
2262
2263         TRACE_MGMT_DBG("Preparing ATTACH_SESS %p (h %d, sess_h %llx, LUN %llx, "
2264                 "threads_num %d, rd_only_flag %d, initiator %s)", ucmd, ucmd->h,
2265                 ucmd->user_cmd.sess.sess_h, ucmd->user_cmd.sess.lun,
2266                 ucmd->user_cmd.sess.threads_num, ucmd->user_cmd.sess.rd_only,
2267                 ucmd->user_cmd.sess.initiator_name);
2268
2269         ucmd->state = UCMD_STATE_ATTACH_SESS;
2270
2271         ucmd_get(ucmd);
2272
2273         dev_user_add_to_ready(ucmd);
2274
2275         rc = wait_for_completion_timeout(ucmd->cmpl, DEV_USER_ATTACH_TIMEOUT);
2276         if (rc > 0)
2277                 res = ucmd->result;
2278         else {
2279                 PRINT_ERROR("%s", "ATTACH_SESS command timeout");
2280                 res = -EFAULT;
2281         }
2282
2283         sBUG_ON(irqs_disabled());
2284
2285         spin_lock_irq(&dev->cmd_lists.cmd_list_lock);
2286         ucmd->cmpl = NULL;
2287         spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
2288
2289         ucmd_put(ucmd);
2290
2291 out:
2292         TRACE_EXIT_RES(res);
2293         return res;
2294
2295 out_nomem:
2296         res = -ENOMEM;
2297         goto out;
2298 }
2299
2300 static void dev_user_detach_tgt(struct scst_tgt_dev *tgt_dev)
2301 {
2302         struct scst_user_dev *dev =
2303                 (struct scst_user_dev *)tgt_dev->dev->dh_priv;
2304         struct scst_user_cmd *ucmd;
2305
2306         TRACE_ENTRY();
2307
2308         /*
2309          * We can't miss TM command due to memory shortage, because it might
2310          * lead to a memory leak in the user space handler.
2311          */
2312         ucmd = dev_user_alloc_ucmd(dev, GFP_KERNEL|__GFP_NOFAIL);
2313         if (ucmd == NULL)
2314                 goto out;
2315
2316         TRACE_MGMT_DBG("Preparing DETACH_SESS %p (h %d, sess_h %llx)", ucmd,
2317                 ucmd->h, ucmd->user_cmd.sess.sess_h);
2318
2319         ucmd->user_cmd.cmd_h = ucmd->h;
2320         ucmd->user_cmd.subcode = SCST_USER_DETACH_SESS;
2321         ucmd->user_cmd.sess.sess_h = (unsigned long)tgt_dev;
2322
2323         ucmd->state = UCMD_STATE_DETACH_SESS;
2324
2325         dev_user_add_to_ready(ucmd);
2326
2327 out:
2328         TRACE_EXIT();
2329         return;
2330 }
2331
2332 /* No locks are needed, but the activity must be suspended */
2333 static void dev_user_setup_functions(struct scst_user_dev *dev)
2334 {
2335         TRACE_ENTRY();
2336
2337         dev->devtype.parse = dev_user_parse;
2338         dev->devtype.dev_done = NULL;
2339
2340         if (dev->parse_type != SCST_USER_PARSE_CALL) {
2341                 switch (dev->devtype.type) {
2342                 case TYPE_DISK:
2343                         dev->generic_parse = scst_sbc_generic_parse;
2344                         dev->devtype.dev_done = dev_user_disk_done;
2345                         break;
2346
2347                 case TYPE_TAPE:
2348                         dev->generic_parse = scst_tape_generic_parse;
2349                         dev->devtype.dev_done = dev_user_tape_done;
2350                         break;
2351
2352                 case TYPE_MOD:
2353                         dev->generic_parse = scst_modisk_generic_parse;
2354                         dev->devtype.dev_done = dev_user_disk_done;
2355                         break;
2356
2357                 case TYPE_ROM:
2358                         dev->generic_parse = scst_cdrom_generic_parse;
2359                         dev->devtype.dev_done = dev_user_disk_done;
2360                         break;
2361
2362                 case TYPE_MEDIUM_CHANGER:
2363                         dev->generic_parse = scst_changer_generic_parse;
2364                         break;
2365
2366                 case TYPE_PROCESSOR:
2367                         dev->generic_parse = scst_processor_generic_parse;
2368                         break;
2369
2370                 case TYPE_RAID:
2371                         dev->generic_parse = scst_raid_generic_parse;
2372                         break;
2373
2374                 default:
2375                         PRINT_INFO("Unknown SCSI type %x, using PARSE_CALL "
2376                                 "for it", dev->devtype.type);
2377                         dev->parse_type = SCST_USER_PARSE_CALL;
2378                         break;
2379                 }
2380         } else {
2381                 dev->generic_parse = NULL;
2382                 dev->devtype.dev_done = NULL;
2383         }
2384
2385         TRACE_EXIT();
2386         return;
2387 }
2388
2389 static int dev_user_check_version(const struct scst_user_dev_desc *dev_desc)
2390 {
2391         char ver[sizeof(DEV_USER_VERSION)+1];
2392         int res;
2393
2394         res = copy_from_user(ver,
2395                         (void __user *)(unsigned long)dev_desc->version_str,
2396                         sizeof(ver));
2397         if (res < 0) {
2398                 PRINT_ERROR("%s", "Unable to get version string");
2399                 goto out;
2400         }
2401         ver[sizeof(ver)-1] = '\0';
2402
2403         if (strcmp(ver, DEV_USER_VERSION) != 0) {
2404                 /* ->name already 0-terminated in dev_user_ioctl() */
2405                 PRINT_ERROR("Incorrect version of user device %s (%s)",
2406                         dev_desc->name, ver);
2407                 res = -EINVAL;
2408                 goto out;
2409         }
2410
2411 out:
2412         return res;
2413 }
2414
2415 static int dev_user_register_dev(struct file *file,
2416         const struct scst_user_dev_desc *dev_desc)
2417 {
2418         int res = -ENOMEM, i;
2419         struct scst_user_dev *dev, *d;
2420         int block;
2421
2422         TRACE_ENTRY();
2423
2424         res = dev_user_check_version(dev_desc);
2425         if (res != 0)
2426                 goto out;
2427
2428         switch (dev_desc->type) {
2429         case TYPE_DISK:
2430         case TYPE_ROM:
2431         case TYPE_MOD:
2432                 if (dev_desc->block_size == 0) {
2433                         PRINT_ERROR("Wrong block size %d",
2434                                     dev_desc->block_size);
2435                         res = -EINVAL;
2436                         goto out;
2437                 }
2438                 block = scst_calc_block_shift(dev_desc->block_size);
2439                 if (block == -1) {
2440                         res = -EINVAL;
2441                         goto out;
2442                 }
2443                 break;
2444         default:
2445                 block = dev_desc->block_size;
2446                 break;
2447         }
2448
2449         if (!try_module_get(THIS_MODULE)) {
2450                 PRINT_ERROR("%s", "Fail to get module");
2451                 goto out;
2452         }
2453
2454         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2455         if (dev == NULL)
2456                 goto out_put;
2457
2458         init_rwsem(&dev->dev_rwsem);
2459         spin_lock_init(&dev->cmd_lists.cmd_list_lock);
2460         INIT_LIST_HEAD(&dev->cmd_lists.active_cmd_list);
2461         init_waitqueue_head(&dev->cmd_lists.cmd_list_waitQ);
2462         INIT_LIST_HEAD(&dev->ready_cmd_list);
2463         if (file->f_flags & O_NONBLOCK) {
2464                 TRACE_DBG("%s", "Non-blocking operations");
2465                 dev->blocking = 0;
2466         } else
2467                 dev->blocking = 1;
2468         for (i = 0; i < (int)ARRAY_SIZE(dev->ucmd_hash); i++)
2469                 INIT_LIST_HEAD(&dev->ucmd_hash[i]);
2470
2471         strncpy(dev->name, dev_desc->name, sizeof(dev->name)-1);
2472         dev->name[sizeof(dev->name)-1] = '\0';
2473
2474         scst_init_mem_lim(&dev->udev_mem_lim);
2475
2476         /*
2477          * We don't use clustered pool, since it implies pages reordering,
2478          * which isn't possible with user space supplied buffers. Although
2479          * it's still possible to cluster pages by the tail of each other,
2480          * seems it doesn't worth the effort.
2481          */
2482         dev->pool = sgv_pool_create(dev->name, 0);
2483         if (dev->pool == NULL)
2484                 goto out_put;
2485         sgv_pool_set_allocator(dev->pool, dev_user_alloc_pages,
2486                 dev_user_free_sg_entries);
2487
2488         scnprintf(dev->devtype.name, sizeof(dev->devtype.name), "dh-%s",
2489                 dev->name);
2490         dev->devtype.type = dev_desc->type;
2491         dev->devtype.threads_num = -1;
2492         dev->devtype.parse_atomic = 1;
2493         dev->devtype.exec_atomic = 0; /* no point to make it 1 */
2494         dev->devtype.dev_done_atomic = 1;
2495         dev->devtype.no_proc = 1;
2496         dev->devtype.attach = dev_user_attach;
2497         dev->devtype.detach = dev_user_detach;
2498         dev->devtype.attach_tgt = dev_user_attach_tgt;
2499         dev->devtype.detach_tgt = dev_user_detach_tgt;
2500         dev->devtype.exec = dev_user_exec;
2501         dev->devtype.on_free_cmd = dev_user_on_free_cmd;
2502         dev->devtype.task_mgmt_fn = dev_user_task_mgmt_fn;
2503
2504         init_completion(&dev->cleanup_cmpl);
2505         dev->block = block;
2506         dev->def_block = block;
2507
2508         res = __dev_user_set_opt(dev, &dev_desc->opt);
2509
2510         TRACE_MEM("dev %p, name %s", dev, dev->name);
2511
2512         spin_lock(&dev_list_lock);
2513
2514         list_for_each_entry(d, &dev_list, dev_list_entry) {
2515                 if (strcmp(d->name, dev->name) == 0) {
2516                         PRINT_ERROR("Device %s already exist",
2517                                 dev->name);
2518                         res = -EEXIST;
2519                         spin_unlock(&dev_list_lock);
2520                         goto out_free;
2521                 }
2522         }
2523
2524         list_add_tail(&dev->dev_list_entry, &dev_list);
2525
2526         spin_unlock(&dev_list_lock);
2527
2528         if (res != 0)
2529                 goto out_del_free;
2530
2531         res = scst_register_virtual_dev_driver(&dev->devtype);
2532         if (res < 0)
2533                 goto out_del_free;
2534
2535         dev->virt_id = scst_register_virtual_device(&dev->devtype, dev->name);
2536         if (dev->virt_id < 0) {
2537                 res = dev->virt_id;
2538                 goto out_unreg_handler;
2539         }
2540
2541         mutex_lock(&dev_priv_mutex);
2542         if (file->private_data != NULL) {
2543                 mutex_unlock(&dev_priv_mutex);
2544                 PRINT_ERROR("%s", "Device already registered");
2545                 res = -EINVAL;
2546                 goto out_unreg_drv;
2547         }
2548         file->private_data = dev;
2549         mutex_unlock(&dev_priv_mutex);
2550
2551 out:
2552         TRACE_EXIT_RES(res);
2553         return res;
2554
2555 out_unreg_drv:
2556         scst_unregister_virtual_device(dev->virt_id);
2557
2558 out_unreg_handler:
2559         scst_unregister_virtual_dev_driver(&dev->devtype);
2560
2561 out_del_free:
2562         spin_lock(&dev_list_lock);
2563         list_del(&dev->dev_list_entry);
2564         spin_unlock(&dev_list_lock);
2565
2566 out_free:
2567         sgv_pool_destroy(dev->pool);
2568         kfree(dev);
2569         goto out_put;
2570
2571 out_put:
2572         module_put(THIS_MODULE);
2573         goto out;
2574 }
2575
2576 static int __dev_user_set_opt(struct scst_user_dev *dev,
2577         const struct scst_user_opt *opt)
2578 {
2579         int res = 0;
2580
2581         TRACE_ENTRY();
2582
2583         TRACE_DBG("dev %s, parse_type %x, on_free_cmd_type %x, "
2584                 "memory_reuse_type %x, partial_transfers_type %x, "
2585                 "partial_len %d", dev->name, opt->parse_type,
2586                 opt->on_free_cmd_type, opt->memory_reuse_type,
2587                 opt->partial_transfers_type, opt->partial_len);
2588
2589         if (opt->parse_type > SCST_USER_MAX_PARSE_OPT ||
2590             opt->on_free_cmd_type > SCST_USER_MAX_ON_FREE_CMD_OPT ||
2591             opt->memory_reuse_type > SCST_USER_MAX_MEM_REUSE_OPT ||
2592             opt->partial_transfers_type > SCST_USER_MAX_PARTIAL_TRANSFERS_OPT) {
2593                 PRINT_ERROR("%s", "Invalid option");
2594                 res = -EINVAL;
2595                 goto out;
2596         }
2597
2598         if (((opt->tst != SCST_CONTR_MODE_ONE_TASK_SET) &&
2599              (opt->tst != SCST_CONTR_MODE_SEP_TASK_SETS)) ||
2600             ((opt->queue_alg != SCST_CONTR_MODE_QUEUE_ALG_RESTRICTED_REORDER) &&
2601              (opt->queue_alg != SCST_CONTR_MODE_QUEUE_ALG_UNRESTRICTED_REORDER)) ||
2602             (opt->swp > 1) || (opt->tas > 1) || (opt->has_own_order_mgmt > 1)) {
2603                 PRINT_ERROR("Invalid SCSI option (tst %x, queue_alg %x, swp %x,"
2604                         " tas %x, has_own_order_mgmt %x)", opt->tst,
2605                         opt->queue_alg, opt->swp, opt->tas,
2606                         opt->has_own_order_mgmt);
2607                 res = -EINVAL;
2608                 goto out;
2609         }
2610
2611         dev->parse_type = opt->parse_type;
2612         dev->on_free_cmd_type = opt->on_free_cmd_type;
2613         dev->memory_reuse_type = opt->memory_reuse_type;
2614         dev->partial_transfers_type = opt->partial_transfers_type;
2615         dev->partial_len = opt->partial_len;
2616
2617         dev->tst = opt->tst;
2618         dev->queue_alg = opt->queue_alg;
2619         dev->swp = opt->swp;
2620         dev->tas = opt->tas;
2621         dev->has_own_order_mgmt = opt->has_own_order_mgmt;
2622         if (dev->sdev != NULL) {
2623                 dev->sdev->tst = opt->tst;
2624                 dev->sdev->queue_alg = opt->queue_alg;
2625                 dev->sdev->swp = opt->swp;
2626                 dev->sdev->tas = opt->tas;
2627                 dev->sdev->has_own_order_mgmt = opt->has_own_order_mgmt;
2628         }
2629
2630         dev_user_setup_functions(dev);
2631
2632 out:
2633         TRACE_EXIT_RES(res);
2634         return res;
2635 }
2636
2637 static int dev_user_set_opt(struct file *file, const struct scst_user_opt *opt)
2638 {
2639         int res = 0;
2640         struct scst_user_dev *dev;
2641
2642         TRACE_ENTRY();
2643
2644         mutex_lock(&dev_priv_mutex);
2645         dev = (struct scst_user_dev *)file->private_data;
2646         res = dev_user_check_reg(dev);
2647         if (res != 0) {
2648                 mutex_unlock(&dev_priv_mutex);
2649                 goto out;
2650         }
2651         down_write(&dev->dev_rwsem);
2652         mutex_unlock(&dev_priv_mutex);
2653
2654         res = scst_suspend_activity(true);
2655         if (res != 0)
2656                 goto out;
2657
2658         res = __dev_user_set_opt(dev, opt);
2659
2660         scst_resume_activity();
2661
2662         up_write(&dev->dev_rwsem);
2663
2664 out:
2665         TRACE_EXIT_RES(res);
2666         return res;
2667 }
2668
2669 static int dev_user_get_opt(struct file *file, void __user *arg)
2670 {
2671         int res = 0;
2672         struct scst_user_dev *dev;
2673         struct scst_user_opt opt;
2674
2675         TRACE_ENTRY();
2676
2677         mutex_lock(&dev_priv_mutex);
2678         dev = (struct scst_user_dev *)file->private_data;
2679         res = dev_user_check_reg(dev);
2680         if (res != 0) {
2681                 mutex_unlock(&dev_priv_mutex);
2682                 goto out;
2683         }
2684         down_read(&dev->dev_rwsem);
2685         mutex_unlock(&dev_priv_mutex);
2686
2687         opt.parse_type = dev->parse_type;
2688         opt.on_free_cmd_type = dev->on_free_cmd_type;
2689         opt.memory_reuse_type = dev->memory_reuse_type;
2690         opt.partial_transfers_type = dev->partial_transfers_type;
2691         opt.partial_len = dev->partial_len;
2692         opt.tst = dev->tst;
2693         opt.queue_alg = dev->queue_alg;
2694         opt.tas = dev->tas;
2695         opt.swp = dev->swp;
2696         opt.has_own_order_mgmt = dev->has_own_order_mgmt;
2697
2698         TRACE_DBG("dev %s, parse_type %x, on_free_cmd_type %x, "
2699                 "memory_reuse_type %x, partial_transfers_type %x, "
2700                 "partial_len %d", dev->name, opt.parse_type,
2701                 opt.on_free_cmd_type, opt.memory_reuse_type,
2702                 opt.partial_transfers_type, opt.partial_len);
2703
2704         res = copy_to_user(arg, &opt, sizeof(opt));
2705
2706         up_read(&dev->dev_rwsem);
2707 out:
2708         TRACE_EXIT_RES(res);
2709         return res;
2710 }
2711
2712 static int dev_usr_parse(struct scst_cmd *cmd)
2713 {
2714         sBUG();
2715         return SCST_CMD_STATE_DEFAULT;
2716 }
2717
2718 /* Needed only for /proc support */
2719 #define USR_TYPE {                      \
2720         .name =         DEV_USER_NAME,  \
2721         .type =         -1,             \
2722         .parse =        dev_usr_parse,  \
2723 }
2724
2725 static struct scst_dev_type dev_user_devtype = USR_TYPE;
2726
2727 static int dev_user_release(struct inode *inode, struct file *file)
2728 {
2729         int res = 0;
2730         struct scst_user_dev *dev;
2731
2732         TRACE_ENTRY();
2733
2734         mutex_lock(&dev_priv_mutex);
2735         dev = (struct scst_user_dev *)file->private_data;
2736         if (dev == NULL) {
2737                 mutex_unlock(&dev_priv_mutex);
2738                 goto out;
2739         }
2740         file->private_data = NULL;
2741
2742         TRACE(TRACE_MGMT, "Releasing dev %s", dev->name);
2743
2744         spin_lock(&dev_list_lock);
2745         list_del(&dev->dev_list_entry);
2746         spin_unlock(&dev_list_lock);
2747
2748         mutex_unlock(&dev_priv_mutex);
2749
2750         down_write(&dev->dev_rwsem);
2751
2752         spin_lock(&cleanup_lock);
2753         list_add_tail(&dev->cleanup_list_entry, &cleanup_list);
2754         spin_unlock(&cleanup_lock);
2755
2756         wake_up(&cleanup_list_waitQ);
2757         wake_up(&dev->cmd_lists.cmd_list_waitQ);
2758
2759         scst_unregister_virtual_device(dev->virt_id);
2760         scst_unregister_virtual_dev_driver(&dev->devtype);
2761
2762         sgv_pool_destroy(dev->pool);
2763
2764         TRACE_DBG("Unregistering finished (dev %p)", dev);
2765
2766         dev->cleanup_done = 1;
2767
2768         wake_up(&cleanup_list_waitQ);
2769         wake_up(&dev->cmd_lists.cmd_list_waitQ);
2770
2771         wait_for_completion(&dev->cleanup_cmpl);
2772
2773         up_write(&dev->dev_rwsem); /* to make the debug check happy */
2774
2775         TRACE_DBG("Releasing completed (dev %p)", dev);
2776
2777         kfree(dev);
2778
2779         module_put(THIS_MODULE);
2780
2781 out:
2782         TRACE_EXIT_RES(res);
2783         return res;
2784 }
2785
2786 static int dev_user_process_cleanup(struct scst_user_dev *dev)
2787 {
2788         struct scst_user_cmd *ucmd;
2789         int rc, res = 1;
2790
2791         TRACE_ENTRY();
2792
2793         dev->blocking = 0;
2794
2795         while (1) {
2796                 TRACE_DBG("Cleanuping dev %p", dev);
2797
2798                 dev_user_unjam_dev(dev);
2799
2800                 spin_lock_irq(&dev->cmd_lists.cmd_list_lock);
2801
2802                 rc = dev_user_get_next_cmd(dev, &ucmd);
2803                 if (rc == 0)
2804                         dev_user_unjam_cmd(ucmd, 1, NULL);
2805
2806                 spin_unlock_irq(&dev->cmd_lists.cmd_list_lock);
2807
2808                 if (rc == -EAGAIN) {
2809                         if (dev->cleanup_done)
2810                                 break;
2811                         else {
2812                                 TRACE_DBG("No more commands (dev %p)", dev);
2813                                 goto out;
2814                         }
2815                 }
2816         }
2817
2818 #ifdef CONFIG_SCST_EXTRACHECKS
2819 {
2820         int i;
2821         for (i = 0; i < (int)ARRAY_SIZE(dev->ucmd_hash); i++) {
2822                 struct list_head *head = &dev->ucmd_hash[i];
2823                 struct scst_user_cmd *ucmd2;
2824 again:
2825                 list_for_each_entry(ucmd2, head, hash_list_entry) {
2826                         PRINT_ERROR("Lost ucmd %p (state %x, ref %d)", ucmd2,
2827                                 ucmd2->state, atomic_read(&ucmd2->ucmd_ref));
2828                         ucmd_put(ucmd2);
2829                         goto again;
2830                 }
2831         }
2832 }
2833 #endif
2834
2835         TRACE_DBG("Cleanuping done (dev %p)", dev);
2836         complete_all(&dev->cleanup_cmpl);
2837         res = 0;
2838
2839 out:
2840         TRACE_EXIT_RES(res);
2841         return res;
2842 }
2843
2844 static inline int test_cleanup_list(void)
2845 {
2846         int res = !list_empty(&cleanup_list) ||
2847                   unlikely(kthread_should_stop());
2848         return res;
2849 }
2850
2851 static int dev_user_cleanup_thread(void *arg)
2852 {
2853         TRACE_ENTRY();
2854
2855         PRINT_INFO("Cleanup thread started, PID %d", current->pid);
2856
2857         current->flags |= PF_NOFREEZE;
2858
2859         spin_lock(&cleanup_lock);
2860         while (!kthread_should_stop()) {
2861                 wait_queue_t wait;
2862                 init_waitqueue_entry(&wait, current);
2863
2864                 if (!test_cleanup_list()) {
2865                         add_wait_queue_exclusive(&cleanup_list_waitQ, &wait);
2866                         for (;;) {
2867                                 set_current_state(TASK_INTERRUPTIBLE);
2868                                 if (test_cleanup_list())
2869                                         break;
2870                                 spin_unlock(&cleanup_lock);
2871                                 schedule();
2872                                 spin_lock(&cleanup_lock);
2873                         }
2874                         set_current_state(TASK_RUNNING);
2875                         remove_wait_queue(&cleanup_list_waitQ, &wait);
2876                 }
2877
2878                 /*
2879                  * We have to poll devices, because commands can go from SCST
2880                  * core on cmd_list_waitQ and we have no practical way to
2881                  * detect them.
2882                  */
2883
2884                 while (1) {
2885                         struct scst_user_dev *dev;
2886                         LIST_HEAD(cl_devs);
2887
2888                         while (!list_empty(&cleanup_list)) {
2889                                 int rc;
2890
2891                                 dev = list_entry(cleanup_list.next,
2892                                         typeof(*dev), cleanup_list_entry);
2893                                 list_del(&dev->cleanup_list_entry);
2894
2895                                 spin_unlock(&cleanup_lock);
2896                                 rc = dev_user_process_cleanup(dev);
2897                                 spin_lock(&cleanup_lock);
2898
2899                                 if (rc != 0)
2900                                         list_add_tail(&dev->cleanup_list_entry,
2901                                                 &cl_devs);
2902                         }
2903
2904                         if (list_empty(&cl_devs))
2905                                 break;
2906
2907                         spin_unlock(&cleanup_lock);
2908                         msleep(100);
2909                         spin_lock(&cleanup_lock);
2910
2911                         while (!list_empty(&cl_devs)) {
2912                                 dev = list_entry(cl_devs.next, typeof(*dev),
2913                                         cleanup_list_entry);
2914                                 list_move_tail(&dev->cleanup_list_entry,
2915                                         &cleanup_list);
2916                         }
2917                 }
2918         }
2919         spin_unlock(&cleanup_lock);
2920
2921         /*
2922          * If kthread_should_stop() is true, we are guaranteed to be
2923          * on the module unload, so cleanup_list must be empty.
2924          */
2925         sBUG_ON(!list_empty(&cleanup_list));
2926
2927         PRINT_INFO("Cleanup thread PID %d finished", current->pid);
2928
2929         TRACE_EXIT();
2930         return 0;
2931 }
2932
2933 static int __init init_scst_user(void)
2934 {
2935         int res = 0;
2936         struct max_get_reply {
2937                 union {
2938                         struct scst_user_get_cmd g;
2939                         struct scst_user_reply_cmd r;
2940                 };
2941         };
2942 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 21)
2943         struct class_device *class_member;
2944 #else
2945         struct device *dev;
2946 #endif
2947
2948         TRACE_ENTRY();
2949
2950 #if defined(CONFIG_HIGHMEM4G) || defined(CONFIG_HIGHMEM64G)
2951         PRINT_ERROR("%s", "HIGHMEM kernel configurations are not supported. "
2952                 "Consider change VMSPLIT option or use 64-bit "
2953                 "configuration instead. See README file for details.");
2954         res = -EINVAL;
2955         goto out;
2956 #endif
2957
2958         user_cmd_cachep = KMEM_CACHE(scst_user_cmd, SCST_SLAB_FLAGS);
2959         if (user_cmd_cachep == NULL) {
2960                 res = -ENOMEM;
2961                 goto out;
2962         }
2963
2964         user_get_cmd_cachep = KMEM_CACHE(max_get_reply, SCST_SLAB_FLAGS);
2965         if (user_get_cmd_cachep == NULL) {
2966                 res = -ENOMEM;
2967                 goto out_cache;
2968         }
2969
2970         dev_user_devtype.module = THIS_MODULE;
2971
2972         res = scst_register_virtual_dev_driver(&dev_user_devtype);
2973         if (res < 0)
2974                 goto out_cache1;
2975
2976         res = scst_dev_handler_build_std_proc(&dev_user_devtype);
2977         if (res != 0)
2978                 goto out_unreg;
2979
2980         dev_user_sysfs_class = class_create(THIS_MODULE, DEV_USER_NAME);
2981         if (IS_ERR(dev_user_sysfs_class)) {
2982                 PRINT_ERROR("%s", "Unable create sysfs class for SCST user "
2983                         "space handler");
2984                 res = PTR_ERR(dev_user_sysfs_class);
2985                 goto out_proc;
2986         }
2987
2988         res = register_chrdev(DEV_USER_MAJOR, DEV_USER_NAME, &dev_user_fops);
2989         if (res) {
2990                 PRINT_ERROR("Unable to get major %d for SCSI tapes",
2991                             DEV_USER_MAJOR);
2992                 goto out_class;
2993         }
2994
2995 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 21)
2996         class_member = class_device_create(dev_user_sysfs_class, NULL,
2997                                 MKDEV(DEV_USER_MAJOR, 0), NULL, DEV_USER_NAME);
2998         if (IS_ERR(class_member)) {
2999                 res = PTR_ERR(class_member);
3000                 goto out_chrdev;
3001         }
3002 #else
3003         dev = device_create(dev_user_sysfs_class, NULL,
3004                             MKDEV(DEV_USER_MAJOR, 0),
3005 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
3006                                 NULL,
3007 #endif
3008                                 DEV_USER_NAME);
3009         if (IS_ERR(dev)) {
3010                 res = PTR_ERR(dev);
3011                 goto out_chrdev;
3012         }
3013 #endif
3014
3015         cleanup_thread = kthread_run(dev_user_cleanup_thread, NULL,
3016                 "scst_usr_cleanupd");
3017         if (IS_ERR(cleanup_thread)) {
3018                 res = PTR_ERR(cleanup_thread);
3019                 PRINT_ERROR("kthread_create() failed: %d", res);
3020                 goto out_dev;
3021         }
3022
3023 out:
3024         TRACE_EXIT_RES(res);
3025         return res;
3026
3027 out_dev:
3028 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 21)
3029         class_device_destroy(dev_user_sysfs_class, MKDEV(DEV_USER_MAJOR, 0));
3030 #else
3031         device_destroy(dev_user_sysfs_class, MKDEV(DEV_USER_MAJOR, 0));
3032 #endif
3033
3034 out_chrdev:
3035         unregister_chrdev(DEV_USER_MAJOR, DEV_USER_NAME);
3036
3037 out_class:
3038         class_destroy(dev_user_sysfs_class);
3039
3040 out_proc:
3041         scst_dev_handler_destroy_std_proc(&dev_user_devtype);
3042
3043 out_unreg:
3044         scst_unregister_dev_driver(&dev_user_devtype);
3045
3046 out_cache1:
3047         kmem_cache_destroy(user_get_cmd_cachep);
3048
3049 out_cache:
3050         kmem_cache_destroy(user_cmd_cachep);
3051         goto out;
3052 }
3053
3054 static void __exit exit_scst_user(void)
3055 {
3056         int rc;
3057
3058         TRACE_ENTRY();
3059
3060         rc = kthread_stop(cleanup_thread);
3061         if (rc < 0)
3062                 TRACE_MGMT_DBG("kthread_stop() failed: %d", rc);
3063
3064         unregister_chrdev(DEV_USER_MAJOR, DEV_USER_NAME);
3065 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 21)
3066         class_device_destroy(dev_user_sysfs_class, MKDEV(DEV_USER_MAJOR, 0));
3067 #else
3068         device_destroy(dev_user_sysfs_class, MKDEV(DEV_USER_MAJOR, 0));
3069 #endif
3070         class_destroy(dev_user_sysfs_class);
3071
3072         scst_dev_handler_destroy_std_proc(&dev_user_devtype);
3073         scst_unregister_virtual_dev_driver(&dev_user_devtype);
3074
3075         kmem_cache_destroy(user_get_cmd_cachep);
3076         kmem_cache_destroy(user_cmd_cachep);
3077
3078         TRACE_EXIT();
3079         return;
3080 }
3081
3082 module_init(init_scst_user);
3083 module_exit(exit_scst_user);
3084
3085 MODULE_AUTHOR("Vladislav Bolkhovitin");
3086 MODULE_LICENSE("GPL");
3087 MODULE_DESCRIPTION("Virtual user space device handler for SCST");
3088 MODULE_VERSION(SCST_VERSION_STRING);
3089 MODULE_ALIAS_CHARDEV_MAJOR(DEV_USER_MAJOR);