Whamcloud - gitweb
LU-6245 server: remove types abstraction from MDS/MGS code
[fs/lustre-release.git] / lustre / mdt / mdt_coordinator.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2011, 2012 Commissariat a l'energie atomique et aux energies
24  *                          alternatives
25  *
26  * Copyright (c) 2013, 2014, Intel Corporation.
27  * Use is subject to license terms.
28  */
29 /*
30  * lustre/mdt/mdt_coordinator.c
31  *
32  * Lustre HSM Coordinator
33  *
34  * Author: Jacques-Charles Lafoucriere <jacques-charles.lafoucriere@cea.fr>
35  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
36  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
37  */
38
39 #define DEBUG_SUBSYSTEM S_MDS
40
41 #include <linux/kthread.h>
42 #include <obd_support.h>
43 #include <lustre_net.h>
44 #include <lustre_export.h>
45 #include <obd.h>
46 #include <lprocfs_status.h>
47 #include <lustre_log.h>
48 #include <lustre_kernelcomm.h>
49 #include "mdt_internal.h"
50
51 static struct lprocfs_vars lprocfs_mdt_hsm_vars[];
52
53 /**
54  * get obj and HSM attributes on a fid
55  * \param mti [IN] context
56  * \param fid [IN] object fid
57  * \param hsm [OUT] HSM meta data
58  * \retval obj or error (-ENOENT if not found)
59  */
60 struct mdt_object *mdt_hsm_get_md_hsm(struct mdt_thread_info *mti,
61                                       const struct lu_fid *fid,
62                                       struct md_hsm *hsm)
63 {
64         struct md_attr          *ma;
65         struct mdt_object       *obj;
66         int                      rc;
67         ENTRY;
68
69         ma = &mti->mti_attr;
70         ma->ma_need = MA_HSM;
71         ma->ma_valid = 0;
72
73         /* find object by FID */
74         obj = mdt_object_find(mti->mti_env, mti->mti_mdt, fid);
75         if (IS_ERR(obj))
76                 RETURN(obj);
77
78         if (!mdt_object_exists(obj)) {
79                 /* no more object */
80                 mdt_object_put(mti->mti_env, obj);
81                 RETURN(ERR_PTR(-ENOENT));
82         }
83
84         rc = mdt_attr_get_complex(mti, obj, ma);
85         if (rc) {
86                 mdt_object_put(mti->mti_env, obj);
87                 RETURN(ERR_PTR(rc));
88         }
89
90         if (ma->ma_valid & MA_HSM)
91                 *hsm = ma->ma_hsm;
92         else
93                 memset(hsm, 0, sizeof(*hsm));
94         ma->ma_valid = 0;
95         RETURN(obj);
96 }
97
98 void mdt_hsm_dump_hal(int level, const char *prefix,
99                       struct hsm_action_list *hal)
100 {
101         int                      i, sz;
102         struct hsm_action_item  *hai;
103         char                     buf[12];
104
105         CDEBUG(level, "%s: HAL header: version %X count %d compound %#llx"
106                       " archive_id %d flags %#llx\n",
107                prefix, hal->hal_version, hal->hal_count,
108                hal->hal_compound_id, hal->hal_archive_id, hal->hal_flags);
109
110         hai = hai_first(hal);
111         for (i = 0; i < hal->hal_count; i++) {
112                 sz = hai->hai_len - sizeof(*hai);
113                 CDEBUG(level, "%s %d: fid="DFID" dfid="DFID
114                        " compound/cookie=%#llx/%#llx"
115                        " action=%s extent=%#llx-%#llx gid=%#llx"
116                        " datalen=%d data=[%s]\n",
117                        prefix, i,
118                        PFID(&hai->hai_fid), PFID(&hai->hai_dfid),
119                        hal->hal_compound_id, hai->hai_cookie,
120                        hsm_copytool_action2name(hai->hai_action),
121                        hai->hai_extent.offset,
122                        hai->hai_extent.length,
123                        hai->hai_gid, sz,
124                        hai_dump_data_field(hai, buf, sizeof(buf)));
125                 hai = hai_next(hai);
126         }
127 }
128
129 /**
130  * data passed to llog_cat_process() callback
131  * to scan requests and take actions
132  */
133 struct hsm_scan_request {
134         int                      hal_sz;
135         int                      hal_used_sz;
136         struct hsm_action_list  *hal;
137 };
138
139 struct hsm_scan_data {
140         struct mdt_thread_info          *mti;
141         char                             fs_name[MTI_NAME_MAXLEN+1];
142         /* request to be send to agents */
143         int                              max_requests;  /** vector size */
144         int                              request_cnt;   /** used count */
145         struct hsm_scan_request         *request;
146 };
147
148 /**
149  *  llog_cat_process() callback, used to:
150  *  - find waiting request and start action
151  *  - purge canceled and done requests
152  * \param env [IN] environment
153  * \param llh [IN] llog handle
154  * \param hdr [IN] llog record
155  * \param data [IN/OUT] cb data = struct hsm_scan_data
156  * \retval 0 success
157  * \retval -ve failure
158  */
159 static int mdt_coordinator_cb(const struct lu_env *env,
160                               struct llog_handle *llh,
161                               struct llog_rec_hdr *hdr,
162                               void *data)
163 {
164         struct llog_agent_req_rec       *larr;
165         struct hsm_scan_data            *hsd;
166         struct hsm_action_item          *hai;
167         struct mdt_device               *mdt;
168         struct coordinator              *cdt;
169         int                              rc;
170         ENTRY;
171
172         hsd = data;
173         mdt = hsd->mti->mti_mdt;
174         cdt = &mdt->mdt_coordinator;
175
176         larr = (struct llog_agent_req_rec *)hdr;
177         dump_llog_agent_req_rec("mdt_coordinator_cb(): ", larr);
178         switch (larr->arr_status) {
179         case ARS_WAITING: {
180                 int i;
181                 struct hsm_scan_request *request;
182
183                 /* Are agents full? */
184                 if (atomic_read(&cdt->cdt_request_count) >=
185                     cdt->cdt_max_requests)
186                         break;
187
188                 /* first search whether the request is found in the
189                  * list we have built. */
190                 request = NULL;
191                 for (i = 0; i < hsd->request_cnt; i++) {
192                         if (hsd->request[i].hal->hal_compound_id ==
193                             larr->arr_compound_id) {
194                                 request = &hsd->request[i];
195                                 break;
196                         }
197                 }
198
199                 if (!request) {
200                         struct hsm_action_list *hal;
201
202                         if (hsd->request_cnt == hsd->max_requests)
203                                 /* Unknown request and no more room
204                                  * for a new request. Continue to scan
205                                  * to find other entries for already
206                                  * existing requests.
207                                  */
208                                 RETURN(0);
209
210                         request = &hsd->request[hsd->request_cnt];
211
212                         /* allocates hai vector size just needs to be large
213                          * enough */
214                         request->hal_sz =
215                                 sizeof(*request->hal) +
216                                 cfs_size_round(MTI_NAME_MAXLEN+1) +
217                                 2 * cfs_size_round(larr->arr_hai.hai_len);
218                         OBD_ALLOC(hal, request->hal_sz);
219                         if (!hal)
220                                 RETURN(-ENOMEM);
221                         hal->hal_version = HAL_VERSION;
222                         strlcpy(hal->hal_fsname, hsd->fs_name,
223                                 MTI_NAME_MAXLEN + 1);
224                         hal->hal_compound_id = larr->arr_compound_id;
225                         hal->hal_archive_id = larr->arr_archive_id;
226                         hal->hal_flags = larr->arr_flags;
227                         hal->hal_count = 0;
228                         request->hal_used_sz = hal_size(hal);
229                         request->hal = hal;
230                         hsd->request_cnt++;
231                         hai = hai_first(hal);
232                 } else {
233                         /* request is known */
234                         /* we check if record archive num is the same as the
235                          * known request, if not we will serve it in multiple
236                          * time because we do not know if the agent can serve
237                          * multiple backend
238                          * a use case is a compound made of multiple restore
239                          * where the files are not archived in the same backend
240                          */
241                         if (larr->arr_archive_id !=
242                             request->hal->hal_archive_id)
243                                 RETURN(0);
244
245                         if (request->hal_sz <
246                             request->hal_used_sz +
247                             cfs_size_round(larr->arr_hai.hai_len)) {
248                                 /* Not enough room, need an extension */
249                                 void *hal_buffer;
250                                 int sz;
251
252                                 sz = 2 * request->hal_sz;
253                                 OBD_ALLOC(hal_buffer, sz);
254                                 if (!hal_buffer)
255                                         RETURN(-ENOMEM);
256                                 memcpy(hal_buffer, request->hal,
257                                        request->hal_used_sz);
258                                 OBD_FREE(request->hal,
259                                          request->hal_sz);
260                                 request->hal = hal_buffer;
261                                 request->hal_sz = sz;
262                         }
263                         hai = hai_first(request->hal);
264                         for (i = 0; i < request->hal->hal_count; i++)
265                                 hai = hai_next(hai);
266                 }
267                 memcpy(hai, &larr->arr_hai, larr->arr_hai.hai_len);
268                 hai->hai_cookie = larr->arr_hai.hai_cookie;
269                 hai->hai_gid = larr->arr_hai.hai_gid;
270
271                 request->hal_used_sz += cfs_size_round(hai->hai_len);
272                 request->hal->hal_count++;
273                 break;
274         }
275         case ARS_STARTED: {
276                 struct hsm_progress_kernel pgs;
277                 struct cdt_agent_req *car;
278                 cfs_time_t now = cfs_time_current_sec();
279                 cfs_time_t last;
280
281                 /* we search for a running request
282                  * error may happen if coordinator crashes or stopped
283                  * with running request
284                  */
285                 car = mdt_cdt_find_request(cdt, larr->arr_hai.hai_cookie, NULL);
286                 if (car == NULL) {
287                         last = larr->arr_req_create;
288                 } else {
289                         last = car->car_req_update;
290                         mdt_cdt_put_request(car);
291                 }
292
293                 /* test if request too long, if yes cancel it
294                  * the same way the copy tool acknowledge a cancel request */
295                 if (now <= last + cdt->cdt_active_req_timeout)
296                         RETURN(0);
297
298                 dump_llog_agent_req_rec("request timed out, start cleaning",
299                                         larr);
300                 /* a too old cancel request just needs to be removed
301                  * this can happen, if copy tool does not support
302                  * cancel for other requests, we have to remove the
303                  * running request and notify the copytool */
304                 pgs.hpk_fid = larr->arr_hai.hai_fid;
305                 pgs.hpk_cookie = larr->arr_hai.hai_cookie;
306                 pgs.hpk_extent = larr->arr_hai.hai_extent;
307                 pgs.hpk_flags = HP_FLAG_COMPLETED;
308                 pgs.hpk_errval = ENOSYS;
309                 pgs.hpk_data_version = 0;
310
311                 /* update request state, but do not record in llog, to
312                  * avoid deadlock on cdt_llog_lock */
313                 rc = mdt_hsm_update_request_state(hsd->mti, &pgs, 0);
314                 if (rc)
315                         CERROR("%s: cannot cleanup timed out request: "
316                                DFID" for cookie %#llx action=%s\n",
317                                mdt_obd_name(mdt),
318                                PFID(&pgs.hpk_fid), pgs.hpk_cookie,
319                                hsm_copytool_action2name(
320                                        larr->arr_hai.hai_action));
321
322                 if (rc == -ENOENT) {
323                         /* The request no longer exists, forget
324                          * about it, and do not send a cancel request
325                          * to the client, for which an error will be
326                          * sent back, leading to an endless cycle of
327                          * cancellation. */
328                         RETURN(LLOG_DEL_RECORD);
329                 }
330
331                 /* XXX A cancel request cannot be cancelled. */
332                 if (larr->arr_hai.hai_action == HSMA_CANCEL)
333                         RETURN(0);
334
335                 larr->arr_status = ARS_CANCELED;
336                 larr->arr_req_change = now;
337                 rc = llog_write(hsd->mti->mti_env, llh, hdr, hdr->lrh_index);
338                 if (rc < 0)
339                         CERROR("%s: cannot update agent log: rc = %d\n",
340                                mdt_obd_name(mdt), rc);
341                 break;
342         }
343         case ARS_FAILED:
344         case ARS_CANCELED:
345         case ARS_SUCCEED:
346                 if ((larr->arr_req_change + cdt->cdt_grace_delay) <
347                     cfs_time_current_sec())
348                         RETURN(LLOG_DEL_RECORD);
349                 break;
350         }
351         RETURN(0);
352 }
353
354 /**
355  * create /proc entries for coordinator
356  * \param mdt [IN]
357  * \retval 0 success
358  * \retval -ve failure
359  */
360 int hsm_cdt_procfs_init(struct mdt_device *mdt)
361 {
362         struct coordinator      *cdt = &mdt->mdt_coordinator;
363         int                      rc = 0;
364         ENTRY;
365
366         /* init /proc entries, failure is not critical */
367         cdt->cdt_proc_dir = lprocfs_register("hsm",
368                                              mdt2obd_dev(mdt)->obd_proc_entry,
369                                              lprocfs_mdt_hsm_vars, mdt);
370         if (IS_ERR(cdt->cdt_proc_dir)) {
371                 rc = PTR_ERR(cdt->cdt_proc_dir);
372                 CERROR("%s: Cannot create 'hsm' directory in mdt proc dir,"
373                        " rc=%d\n", mdt_obd_name(mdt), rc);
374                 cdt->cdt_proc_dir = NULL;
375                 RETURN(rc);
376         }
377
378         RETURN(0);
379 }
380
381 /**
382  * remove /proc entries for coordinator
383  * \param mdt [IN]
384  */
385 void  hsm_cdt_procfs_fini(struct mdt_device *mdt)
386 {
387         struct coordinator      *cdt = &mdt->mdt_coordinator;
388
389         LASSERT(cdt->cdt_state == CDT_STOPPED);
390         if (cdt->cdt_proc_dir != NULL)
391                 lprocfs_remove(&cdt->cdt_proc_dir);
392 }
393
394 /**
395  * get vector of hsm cdt /proc vars
396  * \param none
397  * \retval var vector
398  */
399 struct lprocfs_vars *hsm_cdt_get_proc_vars(void)
400 {
401         return lprocfs_mdt_hsm_vars;
402 }
403
404 /**
405  * coordinator thread
406  * \param data [IN] obd device
407  * \retval 0 success
408  * \retval -ve failure
409  */
410 static int mdt_coordinator(void *data)
411 {
412         struct mdt_thread_info  *mti = data;
413         struct mdt_device       *mdt = mti->mti_mdt;
414         struct coordinator      *cdt = &mdt->mdt_coordinator;
415         struct hsm_scan_data     hsd = { NULL };
416         int                      rc = 0;
417         int                      request_sz;
418         ENTRY;
419
420         cdt->cdt_thread.t_flags = SVC_RUNNING;
421         wake_up(&cdt->cdt_thread.t_ctl_waitq);
422
423         CDEBUG(D_HSM, "%s: coordinator thread starting, pid=%d\n",
424                mdt_obd_name(mdt), current_pid());
425
426         /* we use a copy of cdt_max_requests in the cb, so if cdt_max_requests
427          * increases due to a change from /proc we do not overflow the
428          * hsd.request[] vector
429          */
430         hsd.max_requests = cdt->cdt_max_requests;
431         request_sz = hsd.max_requests * sizeof(*hsd.request);
432         OBD_ALLOC(hsd.request, request_sz);
433         if (!hsd.request)
434                 GOTO(out, rc = -ENOMEM);
435
436         hsd.mti = mti;
437         obd_uuid2fsname(hsd.fs_name, mdt_obd_name(mdt), MTI_NAME_MAXLEN);
438
439         while (1) {
440                 struct l_wait_info lwi;
441                 int i;
442
443                 lwi = LWI_TIMEOUT(cfs_time_seconds(cdt->cdt_loop_period),
444                                   NULL, NULL);
445                 l_wait_event(cdt->cdt_thread.t_ctl_waitq,
446                              (cdt->cdt_thread.t_flags &
447                               (SVC_STOPPING|SVC_EVENT)),
448                              &lwi);
449
450                 CDEBUG(D_HSM, "coordinator resumes\n");
451
452                 if (cdt->cdt_thread.t_flags & SVC_STOPPING ||
453                     cdt->cdt_state == CDT_STOPPING) {
454                         cdt->cdt_thread.t_flags &= ~SVC_STOPPING;
455                         rc = 0;
456                         break;
457                 }
458
459                 /* wake up before timeout, new work arrives */
460                 if (cdt->cdt_thread.t_flags & SVC_EVENT)
461                         cdt->cdt_thread.t_flags &= ~SVC_EVENT;
462
463                 /* if coordinator is suspended continue to wait */
464                 if (cdt->cdt_state == CDT_DISABLE) {
465                         CDEBUG(D_HSM, "disable state, coordinator sleeps\n");
466                         continue;
467                 }
468
469                 CDEBUG(D_HSM, "coordinator starts reading llog\n");
470
471                 if (hsd.max_requests != cdt->cdt_max_requests) {
472                         /* cdt_max_requests has changed,
473                          * we need to allocate a new buffer
474                          */
475                         OBD_FREE(hsd.request, request_sz);
476                         hsd.max_requests = cdt->cdt_max_requests;
477                         request_sz = hsd.max_requests * sizeof(*hsd.request);
478                         OBD_ALLOC(hsd.request, request_sz);
479                         if (!hsd.request) {
480                                 rc = -ENOMEM;
481                                 break;
482                         }
483                 }
484
485                 hsd.request_cnt = 0;
486
487                 rc = cdt_llog_process(mti->mti_env, mdt,
488                                       mdt_coordinator_cb, &hsd);
489                 if (rc < 0)
490                         goto clean_cb_alloc;
491
492                 CDEBUG(D_HSM, "found %d requests to send\n", hsd.request_cnt);
493
494                 if (list_empty(&cdt->cdt_agents)) {
495                         CDEBUG(D_HSM, "no agent available, "
496                                       "coordinator sleeps\n");
497                         goto clean_cb_alloc;
498                 }
499
500                 /* here hsd contains a list of requests to be started */
501                 for (i = 0; i < hsd.request_cnt; i++) {
502                         struct hsm_scan_request *request = &hsd.request[i];
503                         struct hsm_action_list  *hal = request->hal;
504                         struct hsm_action_item  *hai;
505                         __u64                   *cookies;
506                         int                      sz, j;
507                         enum agent_req_status    status;
508
509                         /* still room for work ? */
510                         if (atomic_read(&cdt->cdt_request_count) >=
511                             cdt->cdt_max_requests)
512                                 break;
513
514                         rc = mdt_hsm_agent_send(mti, hal, 0);
515                         /* if failure, we suppose it is temporary
516                          * if the copy tool failed to do the request
517                          * it has to use hsm_progress
518                          */
519                         status = (rc ? ARS_WAITING : ARS_STARTED);
520
521                         /* set up cookie vector to set records status
522                          * after copy tools start or failed
523                          */
524                         sz = hal->hal_count * sizeof(__u64);
525                         OBD_ALLOC(cookies, sz);
526                         if (cookies == NULL)
527                                 continue;
528
529                         hai = hai_first(hal);
530                         for (j = 0; j < hal->hal_count; j++) {
531                                 cookies[j] = hai->hai_cookie;
532                                 hai = hai_next(hai);
533                         }
534
535                         rc = mdt_agent_record_update(mti->mti_env, mdt, cookies,
536                                                      hal->hal_count, status);
537                         if (rc)
538                                 CERROR("%s: mdt_agent_record_update() failed, "
539                                        "rc=%d, cannot update status to %s "
540                                        "for %d cookies\n",
541                                        mdt_obd_name(mdt), rc,
542                                        agent_req_status2name(status),
543                                        hal->hal_count);
544
545                         OBD_FREE(cookies, sz);
546                 }
547 clean_cb_alloc:
548                 /* free hal allocated by callback */
549                 for (i = 0; i < hsd.request_cnt; i++) {
550                         struct hsm_scan_request *request = &hsd.request[i];
551
552                         OBD_FREE(request->hal, request->hal_sz);
553                 }
554         }
555         EXIT;
556 out:
557         if (hsd.request)
558                 OBD_FREE(hsd.request, request_sz);
559
560         if (cdt->cdt_state == CDT_STOPPING) {
561                 /* request comes from /proc path, so we need to clean cdt
562                  * struct */
563                  mdt_hsm_cdt_stop(mdt);
564                  mdt->mdt_opts.mo_coordinator = 0;
565         } else {
566                 /* request comes from a thread event, generated
567                  * by mdt_stop_coordinator(), we have to ack
568                  * and cdt cleaning will be done by event sender
569                  */
570                 cdt->cdt_thread.t_flags = SVC_STOPPED;
571                 wake_up(&cdt->cdt_thread.t_ctl_waitq);
572         }
573
574         if (rc != 0)
575                 CERROR("%s: coordinator thread exiting, process=%d, rc=%d\n",
576                        mdt_obd_name(mdt), current_pid(), rc);
577         else
578                 CDEBUG(D_HSM, "%s: coordinator thread exiting, process=%d,"
579                               " no error\n",
580                        mdt_obd_name(mdt), current_pid());
581
582         return rc;
583 }
584
585 /**
586  * lookup a restore handle by FID
587  * caller needs to hold cdt_restore_lock
588  * \param cdt [IN] coordinator
589  * \param fid [IN] FID
590  * \retval cdt_restore_handle found
591  * \retval NULL not found
592  */
593 struct cdt_restore_handle *mdt_hsm_restore_hdl_find(struct coordinator *cdt,
594                                                        const struct lu_fid *fid)
595 {
596         struct cdt_restore_handle       *crh;
597         ENTRY;
598
599         list_for_each_entry(crh, &cdt->cdt_restore_hdl, crh_list) {
600                 if (lu_fid_eq(&crh->crh_fid, fid))
601                         RETURN(crh);
602         }
603         RETURN(NULL);
604 }
605
606 /**
607  * data passed to llog_cat_process() callback
608  * to scan requests and take actions
609  */
610 struct hsm_restore_data {
611         struct mdt_thread_info  *hrd_mti;
612 };
613
614 /**
615  *  llog_cat_process() callback, used to:
616  *  - find restore request and allocate the restore handle
617  * \param env [IN] environment
618  * \param llh [IN] llog handle
619  * \param hdr [IN] llog record
620  * \param data [IN/OUT] cb data = struct hsm_restore_data
621  * \retval 0 success
622  * \retval -ve failure
623  */
624 static int hsm_restore_cb(const struct lu_env *env,
625                           struct llog_handle *llh,
626                           struct llog_rec_hdr *hdr, void *data)
627 {
628         struct llog_agent_req_rec       *larr;
629         struct hsm_restore_data         *hrd;
630         struct cdt_restore_handle       *crh;
631         struct hsm_action_item          *hai;
632         struct mdt_thread_info          *mti;
633         struct coordinator              *cdt;
634         struct mdt_object               *child;
635         int rc;
636         ENTRY;
637
638         hrd = data;
639         mti = hrd->hrd_mti;
640         cdt = &mti->mti_mdt->mdt_coordinator;
641
642         larr = (struct llog_agent_req_rec *)hdr;
643         hai = &larr->arr_hai;
644         if (hai->hai_cookie > cdt->cdt_last_cookie)
645                 /* update the cookie to avoid collision */
646                 cdt->cdt_last_cookie = hai->hai_cookie + 1;
647
648         if (hai->hai_action != HSMA_RESTORE ||
649             agent_req_in_final_state(larr->arr_status))
650                 RETURN(0);
651
652         /* restore request not in a final state */
653
654         /* force replay of restore requests left in started state from previous
655          * CDT context, to be canceled later if finally found to be incompatible
656          * when being re-started */
657         if (larr->arr_status == ARS_STARTED) {
658                 larr->arr_status = ARS_WAITING;
659                 larr->arr_req_change = cfs_time_current_sec();
660                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
661                 if (rc != 0)
662                         GOTO(out, rc);
663         }
664
665         OBD_SLAB_ALLOC_PTR(crh, mdt_hsm_cdt_kmem);
666         if (crh == NULL)
667                 RETURN(-ENOMEM);
668
669         crh->crh_fid = hai->hai_fid;
670         /* in V1 all file is restored
671         crh->extent.start = hai->hai_extent.offset;
672         crh->extent.end = hai->hai_extent.offset + hai->hai_extent.length;
673         */
674         crh->crh_extent.start = 0;
675         crh->crh_extent.end = hai->hai_extent.length;
676         /* get the layout lock */
677         mdt_lock_reg_init(&crh->crh_lh, LCK_EX);
678         child = mdt_object_find_lock(mti, &crh->crh_fid, &crh->crh_lh,
679                                      MDS_INODELOCK_LAYOUT);
680         if (IS_ERR(child))
681                 GOTO(out, rc = PTR_ERR(child));
682
683         rc = 0;
684         /* we choose to not keep a reference
685          * on the object during the restore time which can be very long */
686         mdt_object_put(mti->mti_env, child);
687
688         mutex_lock(&cdt->cdt_restore_lock);
689         list_add_tail(&crh->crh_list, &cdt->cdt_restore_hdl);
690         mutex_unlock(&cdt->cdt_restore_lock);
691
692 out:
693         RETURN(rc);
694 }
695
696 /**
697  * restore coordinator state at startup
698  * the goal is to take a layout lock for each registered restore request
699  * \param mti [IN] context
700  */
701 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti)
702 {
703         struct hsm_restore_data  hrd;
704         int                      rc;
705         ENTRY;
706
707         hrd.hrd_mti = mti;
708
709         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt,
710                               hsm_restore_cb, &hrd);
711
712         RETURN(rc);
713 }
714
715 static int hsm_init_ucred(struct lu_ucred *uc)
716 {
717         ENTRY;
718
719         uc->uc_valid = UCRED_OLD;
720         uc->uc_o_uid = 0;
721         uc->uc_o_gid = 0;
722         uc->uc_o_fsuid = 0;
723         uc->uc_o_fsgid = 0;
724         uc->uc_uid = 0;
725         uc->uc_gid = 0;
726         uc->uc_fsuid = 0;
727         uc->uc_fsgid = 0;
728         uc->uc_suppgids[0] = -1;
729         uc->uc_suppgids[1] = -1;
730         uc->uc_cap = CFS_CAP_FS_MASK;
731         uc->uc_umask = 0777;
732         uc->uc_ginfo = NULL;
733         uc->uc_identity = NULL;
734
735         RETURN(0);
736 }
737
738 /**
739  * wake up coordinator thread
740  * \param mdt [IN] device
741  * \retval 0 success
742  * \retval -ve failure
743  */
744 int mdt_hsm_cdt_wakeup(struct mdt_device *mdt)
745 {
746         struct coordinator      *cdt = &mdt->mdt_coordinator;
747         ENTRY;
748
749         if (cdt->cdt_state == CDT_STOPPED)
750                 RETURN(-ESRCH);
751
752         /* wake up coordinator */
753         cdt->cdt_thread.t_flags = SVC_EVENT;
754         wake_up(&cdt->cdt_thread.t_ctl_waitq);
755
756         RETURN(0);
757 }
758
759 /**
760  * initialize coordinator struct
761  * \param mdt [IN] device
762  * \retval 0 success
763  * \retval -ve failure
764  */
765 int mdt_hsm_cdt_init(struct mdt_device *mdt)
766 {
767         struct coordinator      *cdt = &mdt->mdt_coordinator;
768         struct mdt_thread_info  *cdt_mti = NULL;
769         int                      rc;
770         ENTRY;
771
772         cdt->cdt_state = CDT_STOPPED;
773
774         init_waitqueue_head(&cdt->cdt_thread.t_ctl_waitq);
775         mutex_init(&cdt->cdt_llog_lock);
776         init_rwsem(&cdt->cdt_agent_lock);
777         init_rwsem(&cdt->cdt_request_lock);
778         mutex_init(&cdt->cdt_restore_lock);
779
780         INIT_LIST_HEAD(&cdt->cdt_requests);
781         INIT_LIST_HEAD(&cdt->cdt_agents);
782         INIT_LIST_HEAD(&cdt->cdt_restore_hdl);
783
784         rc = lu_env_init(&cdt->cdt_env, LCT_MD_THREAD);
785         if (rc < 0)
786                 RETURN(rc);
787
788         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
789         rc = lu_context_init(&cdt->cdt_session, LCT_SERVER_SESSION);
790         if (rc == 0) {
791                 lu_context_enter(&cdt->cdt_session);
792                 cdt->cdt_env.le_ses = &cdt->cdt_session;
793         } else {
794                 lu_env_fini(&cdt->cdt_env);
795                 RETURN(rc);
796         }
797
798         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
799         LASSERT(cdt_mti != NULL);
800
801         cdt_mti->mti_env = &cdt->cdt_env;
802         cdt_mti->mti_mdt = mdt;
803
804         hsm_init_ucred(mdt_ucred(cdt_mti));
805
806         /* default values for /proc tunnables
807          * can be override by MGS conf */
808         cdt->cdt_default_archive_id = 1;
809         cdt->cdt_grace_delay = 60;
810         cdt->cdt_loop_period = 10;
811         cdt->cdt_max_requests = 3;
812         cdt->cdt_policy = CDT_DEFAULT_POLICY;
813         cdt->cdt_active_req_timeout = 3600;
814
815         RETURN(0);
816 }
817
818 /**
819  * free a coordinator thread
820  * \param mdt [IN] device
821  */
822 int  mdt_hsm_cdt_fini(struct mdt_device *mdt)
823 {
824         struct coordinator *cdt = &mdt->mdt_coordinator;
825         ENTRY;
826
827         lu_context_exit(cdt->cdt_env.le_ses);
828         lu_context_fini(cdt->cdt_env.le_ses);
829
830         lu_env_fini(&cdt->cdt_env);
831
832         RETURN(0);
833 }
834
835 /**
836  * start a coordinator thread
837  * \param mdt [IN] device
838  * \retval 0 success
839  * \retval -ve failure
840  */
841 int mdt_hsm_cdt_start(struct mdt_device *mdt)
842 {
843         struct coordinator      *cdt = &mdt->mdt_coordinator;
844         int                      rc;
845         void                    *ptr;
846         struct mdt_thread_info  *cdt_mti;
847         struct task_struct      *task;
848         ENTRY;
849
850         /* functions defined but not yet used
851          * this avoid compilation warning
852          */
853         ptr = dump_requests;
854
855         if (cdt->cdt_state != CDT_STOPPED) {
856                 CERROR("%s: Coordinator already started\n",
857                        mdt_obd_name(mdt));
858                 RETURN(-EALREADY);
859         }
860
861         CLASSERT(1 << (CDT_POLICY_SHIFT_COUNT - 1) == CDT_POLICY_LAST);
862         cdt->cdt_policy = CDT_DEFAULT_POLICY;
863
864         cdt->cdt_state = CDT_INIT;
865
866         atomic_set(&cdt->cdt_compound_id, cfs_time_current_sec());
867         /* just need to be larger than previous one */
868         /* cdt_last_cookie is protected by cdt_llog_lock */
869         cdt->cdt_last_cookie = cfs_time_current_sec();
870         atomic_set(&cdt->cdt_request_count, 0);
871         cdt->cdt_user_request_mask = (1UL << HSMA_RESTORE);
872         cdt->cdt_group_request_mask = (1UL << HSMA_RESTORE);
873         cdt->cdt_other_request_mask = (1UL << HSMA_RESTORE);
874
875         /* to avoid deadlock when start is made through /proc
876          * /proc entries are created by the coordinator thread */
877
878         /* set up list of started restore requests */
879         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
880         rc = mdt_hsm_pending_restore(cdt_mti);
881         if (rc)
882                 CERROR("%s: cannot take the layout locks needed"
883                        " for registered restore: %d\n",
884                        mdt_obd_name(mdt), rc);
885
886         task = kthread_run(mdt_coordinator, cdt_mti, "hsm_cdtr");
887         if (IS_ERR(task)) {
888                 rc = PTR_ERR(task);
889                 cdt->cdt_state = CDT_STOPPED;
890                 CERROR("%s: error starting coordinator thread: %d\n",
891                        mdt_obd_name(mdt), rc);
892                 RETURN(rc);
893         } else {
894                 CDEBUG(D_HSM, "%s: coordinator thread started\n",
895                        mdt_obd_name(mdt));
896                 rc = 0;
897         }
898
899         wait_event(cdt->cdt_thread.t_ctl_waitq,
900                        (cdt->cdt_thread.t_flags & SVC_RUNNING));
901
902         cdt->cdt_state = CDT_RUNNING;
903         mdt->mdt_opts.mo_coordinator = 1;
904         RETURN(0);
905 }
906
907 /**
908  * stop a coordinator thread
909  * \param mdt [IN] device
910  */
911 int mdt_hsm_cdt_stop(struct mdt_device *mdt)
912 {
913         struct coordinator              *cdt = &mdt->mdt_coordinator;
914         struct cdt_agent_req            *car, *tmp1;
915         struct hsm_agent                *ha, *tmp2;
916         struct cdt_restore_handle       *crh, *tmp3;
917         struct mdt_thread_info          *cdt_mti;
918         ENTRY;
919
920         if (cdt->cdt_state == CDT_STOPPED) {
921                 CERROR("%s: Coordinator already stopped\n",
922                        mdt_obd_name(mdt));
923                 RETURN(-EALREADY);
924         }
925
926         if (cdt->cdt_state != CDT_STOPPING) {
927                 /* stop coordinator thread before cleaning */
928                 cdt->cdt_thread.t_flags = SVC_STOPPING;
929                 wake_up(&cdt->cdt_thread.t_ctl_waitq);
930                 wait_event(cdt->cdt_thread.t_ctl_waitq,
931                            cdt->cdt_thread.t_flags & SVC_STOPPED);
932         }
933         cdt->cdt_state = CDT_STOPPED;
934
935         /* start cleaning */
936         down_write(&cdt->cdt_request_lock);
937         list_for_each_entry_safe(car, tmp1, &cdt->cdt_requests,
938                                  car_request_list) {
939                 list_del(&car->car_request_list);
940                 mdt_cdt_free_request(car);
941         }
942         up_write(&cdt->cdt_request_lock);
943
944         down_write(&cdt->cdt_agent_lock);
945         list_for_each_entry_safe(ha, tmp2, &cdt->cdt_agents, ha_list) {
946                 list_del(&ha->ha_list);
947                 OBD_FREE_PTR(ha);
948         }
949         up_write(&cdt->cdt_agent_lock);
950
951         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
952         mutex_lock(&cdt->cdt_restore_lock);
953         list_for_each_entry_safe(crh, tmp3, &cdt->cdt_restore_hdl, crh_list) {
954                 struct mdt_object       *child;
955
956                 /* give back layout lock */
957                 child = mdt_object_find(&cdt->cdt_env, mdt, &crh->crh_fid);
958                 if (!IS_ERR(child))
959                         mdt_object_unlock_put(cdt_mti, child, &crh->crh_lh, 1);
960
961                 list_del(&crh->crh_list);
962
963                 OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
964         }
965         mutex_unlock(&cdt->cdt_restore_lock);
966
967         mdt->mdt_opts.mo_coordinator = 0;
968
969         RETURN(0);
970 }
971
972 /**
973  * register all requests from an hal in the memory list
974  * \param mti [IN] context
975  * \param hal [IN] request
976  * \param uuid [OUT] in case of CANCEL, the uuid of the agent
977  *  which is running the CT
978  * \retval 0 success
979  * \retval -ve failure
980  */
981 int mdt_hsm_add_hal(struct mdt_thread_info *mti,
982                     struct hsm_action_list *hal, struct obd_uuid *uuid)
983 {
984         struct mdt_device       *mdt = mti->mti_mdt;
985         struct coordinator      *cdt = &mdt->mdt_coordinator;
986         struct hsm_action_item  *hai;
987         int                      rc = 0, i;
988         ENTRY;
989
990         /* register request in memory list */
991         hai = hai_first(hal);
992         for (i = 0; i < hal->hal_count; i++, hai = hai_next(hai)) {
993                 struct cdt_agent_req *car;
994
995                 /* in case of a cancel request, we first mark the ondisk
996                  * record of the request we want to stop as canceled
997                  * this does not change the cancel record
998                  * it will be done when updating the request status
999                  */
1000                 if (hai->hai_action == HSMA_CANCEL) {
1001                         rc = mdt_agent_record_update(mti->mti_env, mti->mti_mdt,
1002                                                      &hai->hai_cookie,
1003                                                      1, ARS_CANCELED);
1004                         if (rc) {
1005                                 CERROR("%s: mdt_agent_record_update() failed, "
1006                                        "rc=%d, cannot update status to %s "
1007                                        "for cookie %#llx\n",
1008                                        mdt_obd_name(mdt), rc,
1009                                        agent_req_status2name(ARS_CANCELED),
1010                                        hai->hai_cookie);
1011                                 GOTO(out, rc);
1012                         }
1013
1014                         /* find the running request to set it canceled */
1015                         car = mdt_cdt_find_request(cdt, hai->hai_cookie, NULL);
1016                         if (car != NULL) {
1017                                 car->car_canceled = 1;
1018                                 /* uuid has to be changed to the one running the
1019                                 * request to cancel */
1020                                 *uuid = car->car_uuid;
1021                                 mdt_cdt_put_request(car);
1022                         }
1023                         /* no need to memorize cancel request
1024                          * this also avoid a deadlock when we receive
1025                          * a purge all requests command
1026                          */
1027                         continue;
1028                 }
1029
1030                 if (hai->hai_action == HSMA_ARCHIVE) {
1031                         struct mdt_object *obj;
1032                         struct md_hsm hsm;
1033
1034                         obj = mdt_hsm_get_md_hsm(mti, &hai->hai_fid, &hsm);
1035                         if (IS_ERR(obj) && (PTR_ERR(obj) == -ENOENT))
1036                                 continue;
1037                         if (IS_ERR(obj))
1038                                 GOTO(out, rc = PTR_ERR(obj));
1039
1040                         hsm.mh_flags |= HS_EXISTS;
1041                         hsm.mh_arch_id = hal->hal_archive_id;
1042                         rc = mdt_hsm_attr_set(mti, obj, &hsm);
1043                         mdt_object_put(mti->mti_env, obj);
1044                         if (rc)
1045                                 GOTO(out, rc);
1046                 }
1047
1048                 car = mdt_cdt_alloc_request(hal->hal_compound_id,
1049                                             hal->hal_archive_id, hal->hal_flags,
1050                                             uuid, hai);
1051                 if (IS_ERR(car))
1052                         GOTO(out, rc = PTR_ERR(car));
1053
1054                 rc = mdt_cdt_add_request(cdt, car);
1055                 if (rc != 0)
1056                         mdt_cdt_free_request(car);
1057         }
1058 out:
1059         RETURN(rc);
1060 }
1061
1062 /**
1063  * swap layouts between 2 fids
1064  * \param mti [IN] context
1065  * \param fid1 [IN]
1066  * \param fid2 [IN]
1067  * \param mh_common [IN] MD HSM
1068  */
1069 static int hsm_swap_layouts(struct mdt_thread_info *mti,
1070                             const lustre_fid *fid, const lustre_fid *dfid,
1071                             struct md_hsm *mh_common)
1072 {
1073         struct mdt_device       *mdt = mti->mti_mdt;
1074         struct mdt_object       *child1, *child2;
1075         struct mdt_lock_handle  *lh2;
1076         int                      rc;
1077         ENTRY;
1078
1079         child1 = mdt_object_find(mti->mti_env, mdt, fid);
1080         if (IS_ERR(child1))
1081                 GOTO(out, rc = PTR_ERR(child1));
1082
1083         /* we already have layout lock on FID so take only
1084          * on dfid */
1085         lh2 = &mti->mti_lh[MDT_LH_OLD];
1086         mdt_lock_reg_init(lh2, LCK_EX);
1087         child2 = mdt_object_find_lock(mti, dfid, lh2, MDS_INODELOCK_LAYOUT);
1088         if (IS_ERR(child2))
1089                 GOTO(out_child1, rc = PTR_ERR(child2));
1090
1091         /* if copy tool closes the volatile before sending the final
1092          * progress through llapi_hsm_copy_end(), all the objects
1093          * are removed and mdd_swap_layout LBUG */
1094         if (!mdt_object_exists(child2)) {
1095                 CERROR("%s: Copytool has closed volatile file "DFID"\n",
1096                        mdt_obd_name(mti->mti_mdt), PFID(dfid));
1097                 GOTO(out_child2, rc = -ENOENT);
1098         }
1099         /* Since we only handle restores here, unconditionally use
1100          * SWAP_LAYOUTS_MDS_HSM flag to ensure original layout will
1101          * be preserved in case of failure during swap_layout and not
1102          * leave a file in an intermediate but incoherent state.
1103          * But need to setup HSM xattr of data FID before, reuse
1104          * mti and mh presets for FID in hsm_cdt_request_completed(),
1105          * only need to clear RELEASED and DIRTY.
1106          */
1107         mh_common->mh_flags &= ~(HS_RELEASED | HS_DIRTY);
1108         rc = mdt_hsm_attr_set(mti, child2, mh_common);
1109         if (rc == 0)
1110                 rc = mo_swap_layouts(mti->mti_env,
1111                                      mdt_object_child(child1),
1112                                      mdt_object_child(child2),
1113                                      SWAP_LAYOUTS_MDS_HSM);
1114
1115 out_child2:
1116         mdt_object_unlock_put(mti, child2, lh2, 1);
1117 out_child1:
1118         mdt_object_put(mti->mti_env, child1);
1119 out:
1120         RETURN(rc);
1121 }
1122
1123 /**
1124  * update status of a completed request
1125  * \param mti [IN] context
1126  * \param pgs [IN] progress of the copy tool
1127  * \param update_record [IN] update llog record
1128  * \retval 0 success
1129  * \retval -ve failure
1130  */
1131 static int hsm_cdt_request_completed(struct mdt_thread_info *mti,
1132                                      struct hsm_progress_kernel *pgs,
1133                                      const struct cdt_agent_req *car,
1134                                      enum agent_req_status *status)
1135 {
1136         const struct lu_env     *env = mti->mti_env;
1137         struct mdt_device       *mdt = mti->mti_mdt;
1138         struct coordinator      *cdt = &mdt->mdt_coordinator;
1139         struct mdt_object       *obj = NULL;
1140         int                      cl_flags = 0, rc = 0;
1141         struct md_hsm            mh;
1142         bool                     is_mh_changed;
1143         ENTRY;
1144
1145         /* default is to retry */
1146         *status = ARS_WAITING;
1147
1148         /* find object by FID */
1149         obj = mdt_hsm_get_md_hsm(mti, &car->car_hai->hai_fid, &mh);
1150         /* we will update MD HSM only if needed */
1151         is_mh_changed = false;
1152         if (IS_ERR(obj)) {
1153                 /* object removed */
1154                 *status = ARS_SUCCEED;
1155                 goto unlock;
1156         }
1157
1158         /* no need to change mh->mh_arch_id
1159          * mdt_hsm_get_md_hsm() got it from disk and it is still valid
1160          */
1161         if (pgs->hpk_errval != 0) {
1162                 switch (pgs->hpk_errval) {
1163                 case ENOSYS:
1164                         /* the copy tool does not support cancel
1165                          * so the cancel request is failed
1166                          * As we cannot distinguish a cancel progress
1167                          * from another action progress (they have the
1168                          * same cookie), we suppose here the CT returns
1169                          * ENOSYS only if does not support cancel
1170                          */
1171                         /* this can also happen when cdt calls it to
1172                          * for a timed out request */
1173                         *status = ARS_FAILED;
1174                         /* to have a cancel event in changelog */
1175                         pgs->hpk_errval = ECANCELED;
1176                         break;
1177                 case ECANCELED:
1178                         /* the request record has already been set to
1179                          * ARS_CANCELED, this set the cancel request
1180                          * to ARS_SUCCEED */
1181                         *status = ARS_SUCCEED;
1182                         break;
1183                 default:
1184                         *status = (cdt->cdt_policy & CDT_NORETRY_ACTION ||
1185                                    !(pgs->hpk_flags & HP_FLAG_RETRY) ?
1186                                    ARS_FAILED : ARS_WAITING);
1187                         break;
1188                 }
1189
1190                 if (pgs->hpk_errval > CLF_HSM_MAXERROR) {
1191                         CERROR("%s: Request %#llx on "DFID
1192                                " failed, error code %d too large\n",
1193                                mdt_obd_name(mdt),
1194                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1195                                pgs->hpk_errval);
1196                         hsm_set_cl_error(&cl_flags,
1197                                          CLF_HSM_ERROVERFLOW);
1198                         rc = -EINVAL;
1199                 } else {
1200                         hsm_set_cl_error(&cl_flags, pgs->hpk_errval);
1201                 }
1202
1203                 switch (car->car_hai->hai_action) {
1204                 case HSMA_ARCHIVE:
1205                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1206                         break;
1207                 case HSMA_RESTORE:
1208                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1209                         break;
1210                 case HSMA_REMOVE:
1211                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1212                         break;
1213                 case HSMA_CANCEL:
1214                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1215                         CERROR("%s: Failed request %#llx on "DFID
1216                                " cannot be a CANCEL\n",
1217                                mdt_obd_name(mdt),
1218                                pgs->hpk_cookie,
1219                                PFID(&pgs->hpk_fid));
1220                         break;
1221                 default:
1222                         CERROR("%s: Failed request %#llx on "DFID
1223                                " %d is an unknown action\n",
1224                                mdt_obd_name(mdt),
1225                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1226                                car->car_hai->hai_action);
1227                         rc = -EINVAL;
1228                         break;
1229                 }
1230         } else {
1231                 *status = ARS_SUCCEED;
1232                 switch (car->car_hai->hai_action) {
1233                 case HSMA_ARCHIVE:
1234                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1235                         /* set ARCHIVE keep EXIST and clear LOST and
1236                          * DIRTY */
1237                         mh.mh_arch_ver = pgs->hpk_data_version;
1238                         mh.mh_flags |= HS_ARCHIVED;
1239                         mh.mh_flags &= ~(HS_LOST|HS_DIRTY);
1240                         is_mh_changed = true;
1241                         break;
1242                 case HSMA_RESTORE:
1243                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1244
1245                         /* do not clear RELEASED and DIRTY here
1246                          * this will occur in hsm_swap_layouts()
1247                          */
1248
1249                         /* Restoring has changed the file version on
1250                          * disk. */
1251                         mh.mh_arch_ver = pgs->hpk_data_version;
1252                         is_mh_changed = true;
1253                         break;
1254                 case HSMA_REMOVE:
1255                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1256                         /* clear ARCHIVED EXISTS and LOST */
1257                         mh.mh_flags &= ~(HS_ARCHIVED | HS_EXISTS | HS_LOST);
1258                         is_mh_changed = true;
1259                         break;
1260                 case HSMA_CANCEL:
1261                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1262                         CERROR("%s: Successful request %#llx on "DFID" cannot be a CANCEL\n",
1263                                mdt_obd_name(mdt),
1264                                pgs->hpk_cookie,
1265                                PFID(&pgs->hpk_fid));
1266                         break;
1267                 default:
1268                         CERROR("%s: Successful request %#llx on "DFID" %d is an unknown action\n",
1269                                mdt_obd_name(mdt),
1270                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1271                                car->car_hai->hai_action);
1272                         rc = -EINVAL;
1273                         break;
1274                 }
1275         }
1276
1277         /* rc != 0 means error when analysing action, it may come from
1278          * a crasy CT no need to manage DIRTY
1279          */
1280         if (rc == 0)
1281                 hsm_set_cl_flags(&cl_flags,
1282                                  mh.mh_flags & HS_DIRTY ? CLF_HSM_DIRTY : 0);
1283
1284         /* unlock is done later, after layout lock management */
1285         if (is_mh_changed)
1286                 rc = mdt_hsm_attr_set(mti, obj, &mh);
1287
1288 unlock:
1289         /* we give back layout lock only if restore was successful or
1290          * if restore was canceled or if policy is to not retry
1291          * in other cases we just unlock the object */
1292         if (car->car_hai->hai_action == HSMA_RESTORE &&
1293             (pgs->hpk_errval == 0 || pgs->hpk_errval == ECANCELED ||
1294              cdt->cdt_policy & CDT_NORETRY_ACTION)) {
1295                 struct cdt_restore_handle       *crh;
1296
1297                 /* restore in data FID done, we swap the layouts
1298                  * only if restore is successful */
1299                 if (pgs->hpk_errval == 0) {
1300                         rc = hsm_swap_layouts(mti, &car->car_hai->hai_fid,
1301                                               &car->car_hai->hai_dfid, &mh);
1302                         if (rc) {
1303                                 if (cdt->cdt_policy & CDT_NORETRY_ACTION)
1304                                         *status = ARS_FAILED;
1305                                 pgs->hpk_errval = -rc;
1306                         }
1307                 }
1308                 /* we have to retry, so keep layout lock */
1309                 if (*status == ARS_WAITING)
1310                         GOTO(out, rc);
1311
1312                 /* give back layout lock */
1313                 mutex_lock(&cdt->cdt_restore_lock);
1314                 crh = mdt_hsm_restore_hdl_find(cdt, &car->car_hai->hai_fid);
1315                 if (crh != NULL)
1316                         list_del(&crh->crh_list);
1317                 mutex_unlock(&cdt->cdt_restore_lock);
1318                 /* just give back layout lock, we keep
1319                  * the reference which is given back
1320                  * later with the lock for HSM flags */
1321                 if (!IS_ERR(obj) && crh != NULL)
1322                         mdt_object_unlock(mti, obj, &crh->crh_lh, 1);
1323
1324                 if (crh != NULL)
1325                         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
1326         }
1327
1328         GOTO(out, rc);
1329
1330 out:
1331         if (obj != NULL && !IS_ERR(obj)) {
1332                 mo_changelog(env, CL_HSM, cl_flags,
1333                              mdt_object_child(obj));
1334                 mdt_object_put(mti->mti_env, obj);
1335         }
1336
1337         RETURN(rc);
1338 }
1339
1340 /**
1341  * update status of a request
1342  * \param mti [IN] context
1343  * \param pgs [IN] progress of the copy tool
1344  * \param update_record [IN] update llog record
1345  * \retval 0 success
1346  * \retval -ve failure
1347  */
1348 int mdt_hsm_update_request_state(struct mdt_thread_info *mti,
1349                                  struct hsm_progress_kernel *pgs,
1350                                  const int update_record)
1351 {
1352         struct mdt_device       *mdt = mti->mti_mdt;
1353         struct coordinator      *cdt = &mdt->mdt_coordinator;
1354         struct cdt_agent_req    *car;
1355         int                      rc = 0;
1356         ENTRY;
1357
1358         /* no coordinator started, so we cannot serve requests */
1359         if (cdt->cdt_state == CDT_STOPPED)
1360                 RETURN(-EAGAIN);
1361
1362         /* first do sanity checks */
1363         car = mdt_cdt_update_request(cdt, pgs);
1364         if (IS_ERR(car)) {
1365                 CERROR("%s: Cannot find running request for cookie %#llx"
1366                        " on fid="DFID"\n",
1367                        mdt_obd_name(mdt),
1368                        pgs->hpk_cookie, PFID(&pgs->hpk_fid));
1369
1370                 RETURN(PTR_ERR(car));
1371         }
1372
1373         CDEBUG(D_HSM, "Progress received for fid="DFID" cookie=%#llx"
1374                       " action=%s flags=%d err=%d fid="DFID" dfid="DFID"\n",
1375                       PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1376                       hsm_copytool_action2name(car->car_hai->hai_action),
1377                       pgs->hpk_flags, pgs->hpk_errval,
1378                       PFID(&car->car_hai->hai_fid),
1379                       PFID(&car->car_hai->hai_dfid));
1380
1381         /* progress is done on FID or data FID depending of the action and
1382          * of the copy progress */
1383         /* for restore progress is used to send back the data FID to cdt */
1384         if (car->car_hai->hai_action == HSMA_RESTORE &&
1385             lu_fid_eq(&car->car_hai->hai_fid, &car->car_hai->hai_dfid))
1386                 car->car_hai->hai_dfid = pgs->hpk_fid;
1387
1388         if ((car->car_hai->hai_action == HSMA_RESTORE ||
1389              car->car_hai->hai_action == HSMA_ARCHIVE) &&
1390             (!lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_dfid) &&
1391              !lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_fid))) {
1392                 CERROR("%s: Progress on "DFID" for cookie %#llx"
1393                        " does not match request FID "DFID" nor data FID "
1394                        DFID"\n",
1395                        mdt_obd_name(mdt),
1396                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1397                        PFID(&car->car_hai->hai_fid),
1398                        PFID(&car->car_hai->hai_dfid));
1399                 GOTO(out, rc = -EINVAL);
1400         }
1401
1402         if (pgs->hpk_errval != 0 && !(pgs->hpk_flags & HP_FLAG_COMPLETED)) {
1403                 CERROR("%s: Progress on "DFID" for cookie %#llx action=%s"
1404                        " is not coherent (err=%d and not completed"
1405                        " (flags=%d))\n",
1406                        mdt_obd_name(mdt),
1407                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1408                        hsm_copytool_action2name(car->car_hai->hai_action),
1409                        pgs->hpk_errval, pgs->hpk_flags);
1410                 GOTO(out, rc = -EINVAL);
1411         }
1412
1413         /* now progress is valid */
1414
1415         /* we use a root like ucred */
1416         hsm_init_ucred(mdt_ucred(mti));
1417
1418         if (pgs->hpk_flags & HP_FLAG_COMPLETED) {
1419                 enum agent_req_status    status;
1420
1421                 rc = hsm_cdt_request_completed(mti, pgs, car, &status);
1422
1423                 /* remove request from memory list */
1424                 mdt_cdt_remove_request(cdt, pgs->hpk_cookie);
1425
1426                 CDEBUG(D_HSM, "Updating record: fid="DFID" cookie=%#llx"
1427                               " action=%s status=%s\n", PFID(&pgs->hpk_fid),
1428                        pgs->hpk_cookie,
1429                        hsm_copytool_action2name(car->car_hai->hai_action),
1430                        agent_req_status2name(status));
1431
1432                 if (update_record) {
1433                         int rc1;
1434
1435                         rc1 = mdt_agent_record_update(mti->mti_env, mdt,
1436                                                      &pgs->hpk_cookie, 1,
1437                                                      status);
1438                         if (rc1)
1439                                 CERROR("%s: mdt_agent_record_update() failed,"
1440                                        " rc=%d, cannot update status to %s"
1441                                        " for cookie %#llx\n",
1442                                        mdt_obd_name(mdt), rc1,
1443                                        agent_req_status2name(status),
1444                                        pgs->hpk_cookie);
1445                         rc = (rc != 0 ? rc : rc1);
1446                 }
1447                 /* ct has completed a request, so a slot is available, wakeup
1448                  * cdt to find new work */
1449                 mdt_hsm_cdt_wakeup(mdt);
1450         } else {
1451                 /* if copytool send a progress on a canceled request
1452                  * we inform copytool it should stop
1453                  */
1454                 if (car->car_canceled == 1)
1455                         rc = -ECANCELED;
1456         }
1457         GOTO(out, rc);
1458
1459 out:
1460         /* remove ref got from mdt_cdt_update_request() */
1461         mdt_cdt_put_request(car);
1462
1463         return rc;
1464 }
1465
1466
1467 /**
1468  * data passed to llog_cat_process() callback
1469  * to cancel requests
1470  */
1471 struct hsm_cancel_all_data {
1472         struct mdt_device       *mdt;
1473 };
1474
1475 /**
1476  *  llog_cat_process() callback, used to:
1477  *  - purge all requests
1478  * \param env [IN] environment
1479  * \param llh [IN] llog handle
1480  * \param hdr [IN] llog record
1481  * \param data [IN] cb data = struct hsm_cancel_all_data
1482  * \retval 0 success
1483  * \retval -ve failure
1484  */
1485 static int mdt_cancel_all_cb(const struct lu_env *env,
1486                              struct llog_handle *llh,
1487                              struct llog_rec_hdr *hdr, void *data)
1488 {
1489         struct llog_agent_req_rec       *larr;
1490         struct hsm_cancel_all_data      *hcad;
1491         int                              rc = 0;
1492         ENTRY;
1493
1494         larr = (struct llog_agent_req_rec *)hdr;
1495         hcad = data;
1496         if (larr->arr_status == ARS_WAITING ||
1497             larr->arr_status == ARS_STARTED) {
1498                 larr->arr_status = ARS_CANCELED;
1499                 larr->arr_req_change = cfs_time_current_sec();
1500                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
1501         }
1502
1503         RETURN(rc);
1504 }
1505
1506 /**
1507  * cancel all actions
1508  * \param obd [IN] MDT device
1509  */
1510 static int hsm_cancel_all_actions(struct mdt_device *mdt)
1511 {
1512         struct mdt_thread_info          *mti;
1513         struct coordinator              *cdt = &mdt->mdt_coordinator;
1514         struct cdt_agent_req            *car;
1515         struct hsm_action_list          *hal = NULL;
1516         struct hsm_action_item          *hai;
1517         struct hsm_cancel_all_data       hcad;
1518         int                              hal_sz = 0, hal_len, rc;
1519         enum cdt_states                  save_state;
1520         ENTRY;
1521
1522         /* retrieve coordinator context */
1523         mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1524
1525         /* disable coordinator */
1526         save_state = cdt->cdt_state;
1527         cdt->cdt_state = CDT_DISABLE;
1528
1529         /* send cancel to all running requests */
1530         down_read(&cdt->cdt_request_lock);
1531         list_for_each_entry(car, &cdt->cdt_requests, car_request_list) {
1532                 mdt_cdt_get_request(car);
1533                 /* request is not yet removed from list, it will be done
1534                  * when copytool will return progress
1535                  */
1536
1537                 if (car->car_hai->hai_action == HSMA_CANCEL) {
1538                         mdt_cdt_put_request(car);
1539                         continue;
1540                 }
1541
1542                 /* needed size */
1543                 hal_len = sizeof(*hal) + cfs_size_round(MTI_NAME_MAXLEN + 1) +
1544                           cfs_size_round(car->car_hai->hai_len);
1545
1546                 if (hal_len > hal_sz && hal_sz > 0) {
1547                         /* not enough room, free old buffer */
1548                         OBD_FREE(hal, hal_sz);
1549                         hal = NULL;
1550                 }
1551
1552                 /* empty buffer, allocate one */
1553                 if (hal == NULL) {
1554                         hal_sz = hal_len;
1555                         OBD_ALLOC(hal, hal_sz);
1556                         if (hal == NULL) {
1557                                 mdt_cdt_put_request(car);
1558                                 up_read(&cdt->cdt_request_lock);
1559                                 GOTO(out, rc = -ENOMEM);
1560                         }
1561                 }
1562
1563                 hal->hal_version = HAL_VERSION;
1564                 obd_uuid2fsname(hal->hal_fsname, mdt_obd_name(mdt),
1565                                 MTI_NAME_MAXLEN);
1566                 hal->hal_fsname[MTI_NAME_MAXLEN] = '\0';
1567                 hal->hal_compound_id = car->car_compound_id;
1568                 hal->hal_archive_id = car->car_archive_id;
1569                 hal->hal_flags = car->car_flags;
1570                 hal->hal_count = 0;
1571
1572                 hai = hai_first(hal);
1573                 memcpy(hai, car->car_hai, car->car_hai->hai_len);
1574                 hai->hai_action = HSMA_CANCEL;
1575                 hal->hal_count = 1;
1576
1577                 /* it is possible to safely call mdt_hsm_agent_send()
1578                  * (ie without a deadlock on cdt_request_lock), because the
1579                  * write lock is taken only if we are not in purge mode
1580                  * (mdt_hsm_agent_send() does not call mdt_cdt_add_request()
1581                  *   nor mdt_cdt_remove_request())
1582                  */
1583                 /* no conflict with cdt thread because cdt is disable and we
1584                  * have the request lock */
1585                 mdt_hsm_agent_send(mti, hal, 1);
1586
1587                 mdt_cdt_put_request(car);
1588         }
1589         up_read(&cdt->cdt_request_lock);
1590
1591         if (hal != NULL)
1592                 OBD_FREE(hal, hal_sz);
1593
1594         /* cancel all on-disk records */
1595         hcad.mdt = mdt;
1596
1597         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt,
1598                               mdt_cancel_all_cb, &hcad);
1599 out:
1600         /* enable coordinator */
1601         cdt->cdt_state = save_state;
1602
1603         RETURN(rc);
1604 }
1605
1606 /**
1607  * check if a request is compatible with file status
1608  * \param hai [IN] request description
1609  * \param hal_an [IN] request archive number (not used)
1610  * \param rq_flags [IN] request flags
1611  * \param hsm [IN] file HSM metadata
1612  * \retval boolean
1613  */
1614 bool mdt_hsm_is_action_compat(const struct hsm_action_item *hai,
1615                               const int hal_an, const __u64 rq_flags,
1616                               const struct md_hsm *hsm)
1617 {
1618         int      is_compat = false;
1619         int      hsm_flags;
1620         ENTRY;
1621
1622         hsm_flags = hsm->mh_flags;
1623         switch (hai->hai_action) {
1624         case HSMA_ARCHIVE:
1625                 if (!(hsm_flags & HS_NOARCHIVE) &&
1626                     (hsm_flags & HS_DIRTY || !(hsm_flags & HS_ARCHIVED)))
1627                         is_compat = true;
1628                 break;
1629         case HSMA_RESTORE:
1630                 if (!(hsm_flags & HS_DIRTY) && (hsm_flags & HS_RELEASED) &&
1631                     hsm_flags & HS_ARCHIVED && !(hsm_flags & HS_LOST))
1632                         is_compat = true;
1633                 break;
1634         case HSMA_REMOVE:
1635                 if (!(hsm_flags & HS_RELEASED) &&
1636                     (hsm_flags & (HS_ARCHIVED | HS_EXISTS)))
1637                         is_compat = true;
1638                 break;
1639         case HSMA_CANCEL:
1640                 is_compat = true;
1641                 break;
1642         }
1643         CDEBUG(D_HSM, "fid="DFID" action=%s flags=%#llx"
1644                       " extent=%#llx-%#llx hsm_flags=%.8X %s\n",
1645                       PFID(&hai->hai_fid),
1646                       hsm_copytool_action2name(hai->hai_action), rq_flags,
1647                       hai->hai_extent.offset, hai->hai_extent.length,
1648                       hsm->mh_flags,
1649                       (is_compat ? "compatible" : "uncompatible"));
1650
1651         RETURN(is_compat);
1652 }
1653
1654 /*
1655  * /proc interface used to get/set HSM behaviour (cdt->cdt_policy)
1656  */
1657 static const struct {
1658         __u64            bit;
1659         char            *name;
1660         char            *nickname;
1661 } hsm_policy_names[] = {
1662         { CDT_NONBLOCKING_RESTORE,      "NonBlockingRestore",   "NBR"},
1663         { CDT_NORETRY_ACTION,           "NoRetryAction",        "NRA"},
1664         { 0 },
1665 };
1666
1667 /**
1668  * convert a policy name to a bit
1669  * \param name [IN] policy name
1670  * \retval 0 unknown
1671  * \retval   policy bit
1672  */
1673 static __u64 hsm_policy_str2bit(const char *name)
1674 {
1675         int      i;
1676
1677         for (i = 0; hsm_policy_names[i].bit != 0; i++)
1678                 if (strcmp(hsm_policy_names[i].nickname, name) == 0 ||
1679                     strcmp(hsm_policy_names[i].name, name) == 0)
1680                         return hsm_policy_names[i].bit;
1681         return 0;
1682 }
1683
1684 /**
1685  * convert a policy bit field to a string
1686  * \param mask [IN] policy bit field
1687  * \param hexa [IN] print mask before bit names
1688  * \param buffer [OUT] string
1689  * \param count [IN] size of buffer
1690  */
1691 static void hsm_policy_bit2str(struct seq_file *m, const __u64 mask,
1692                                 const bool hexa)
1693 {
1694         int      i, j;
1695         __u64    bit;
1696         ENTRY;
1697
1698         if (hexa)
1699                 seq_printf(m, "(%#llx) ", mask);
1700
1701         for (i = 0; i < CDT_POLICY_SHIFT_COUNT; i++) {
1702                 bit = (1ULL << i);
1703
1704                 for (j = 0; hsm_policy_names[j].bit != 0; j++) {
1705                         if (hsm_policy_names[j].bit == bit)
1706                                 break;
1707                 }
1708                 if (bit & mask)
1709                         seq_printf(m, "[%s] ", hsm_policy_names[j].name);
1710                 else
1711                         seq_printf(m, "%s ", hsm_policy_names[j].name);
1712         }
1713         /* remove last ' ' */
1714         m->count--;
1715         seq_putc(m, '\0');
1716 }
1717
1718 /* methods to read/write HSM policy flags */
1719 static int mdt_hsm_policy_seq_show(struct seq_file *m, void *data)
1720 {
1721         struct mdt_device       *mdt = m->private;
1722         struct coordinator      *cdt = &mdt->mdt_coordinator;
1723         ENTRY;
1724
1725         hsm_policy_bit2str(m, cdt->cdt_policy, false);
1726         RETURN(0);
1727 }
1728
1729 static ssize_t
1730 mdt_hsm_policy_seq_write(struct file *file, const char __user *buffer,
1731                          size_t count, loff_t *off)
1732 {
1733         struct seq_file         *m = file->private_data;
1734         struct mdt_device       *mdt = m->private;
1735         struct coordinator      *cdt = &mdt->mdt_coordinator;
1736         char                    *start, *token, sign;
1737         char                    *buf;
1738         __u64                    policy;
1739         __u64                    add_mask, remove_mask, set_mask;
1740         int                      rc;
1741         ENTRY;
1742
1743         if (count + 1 > PAGE_SIZE)
1744                 RETURN(-EINVAL);
1745
1746         OBD_ALLOC(buf, count + 1);
1747         if (buf == NULL)
1748                 RETURN(-ENOMEM);
1749
1750         if (copy_from_user(buf, buffer, count))
1751                 GOTO(out, rc = -EFAULT);
1752
1753         buf[count] = '\0';
1754
1755         start = buf;
1756         CDEBUG(D_HSM, "%s: receive new policy: '%s'\n", mdt_obd_name(mdt),
1757                start);
1758
1759         add_mask = remove_mask = set_mask = 0;
1760         do {
1761                 token = strsep(&start, "\n ");
1762                 sign = *token;
1763
1764                 if (sign == '\0')
1765                         continue;
1766
1767                 if (sign == '-' || sign == '+')
1768                         token++;
1769
1770                 policy = hsm_policy_str2bit(token);
1771                 if (policy == 0) {
1772                         CWARN("%s: '%s' is unknown, "
1773                               "supported policies are:\n", mdt_obd_name(mdt),
1774                               token);
1775                         hsm_policy_bit2str(m, 0, false);
1776                         GOTO(out, rc = -EINVAL);
1777                 }
1778                 switch (sign) {
1779                 case '-':
1780                         remove_mask |= policy;
1781                         break;
1782                 case '+':
1783                         add_mask |= policy;
1784                         break;
1785                 default:
1786                         set_mask |= policy;
1787                         break;
1788                 }
1789
1790         } while (start != NULL);
1791
1792         CDEBUG(D_HSM, "%s: new policy: rm=%#llx add=%#llx set=%#llx\n",
1793                mdt_obd_name(mdt), remove_mask, add_mask, set_mask);
1794
1795         /* if no sign in all string, it is a clear and set
1796          * if some sign found, all unsigned are converted
1797          * to add
1798          * P1 P2 = set to P1 and P2
1799          * P1 -P2 = add P1 clear P2 same as +P1 -P2
1800          */
1801         if (remove_mask == 0 && add_mask == 0) {
1802                 cdt->cdt_policy = set_mask;
1803         } else {
1804                 cdt->cdt_policy |= set_mask | add_mask;
1805                 cdt->cdt_policy &= ~remove_mask;
1806         }
1807
1808         GOTO(out, rc = count);
1809
1810 out:
1811         OBD_FREE(buf, count + 1);
1812         RETURN(rc);
1813 }
1814 LPROC_SEQ_FOPS(mdt_hsm_policy);
1815
1816 #define GENERATE_PROC_METHOD(VAR)                                       \
1817 static int mdt_hsm_##VAR##_seq_show(struct seq_file *m, void *data)     \
1818 {                                                                       \
1819         struct mdt_device       *mdt = m->private;                      \
1820         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
1821         ENTRY;                                                          \
1822                                                                         \
1823         seq_printf(m, "%llu\n", (__u64)cdt->VAR);                       \
1824         RETURN(0);                                                      \
1825 }                                                                       \
1826 static ssize_t                                                          \
1827 mdt_hsm_##VAR##_seq_write(struct file *file, const char __user *buffer, \
1828                           size_t count, loff_t *off)                    \
1829                                                                         \
1830 {                                                                       \
1831         struct seq_file         *m = file->private_data;                \
1832         struct mdt_device       *mdt = m->private;                      \
1833         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
1834         __s64                    val;                                   \
1835         int                      rc;                                    \
1836         ENTRY;                                                          \
1837                                                                         \
1838         rc = lprocfs_str_to_s64(buffer, count, &val);                   \
1839         if (rc)                                                         \
1840                 RETURN(rc);                                             \
1841         if (val > 0 && val < INT_MAX) {                                 \
1842                 cdt->VAR = val;                                         \
1843                 RETURN(count);                                          \
1844         }                                                               \
1845         RETURN(-EINVAL);                                                \
1846 }                                                                       \
1847
1848 GENERATE_PROC_METHOD(cdt_loop_period)
1849 GENERATE_PROC_METHOD(cdt_grace_delay)
1850 GENERATE_PROC_METHOD(cdt_active_req_timeout)
1851 GENERATE_PROC_METHOD(cdt_max_requests)
1852 GENERATE_PROC_METHOD(cdt_default_archive_id)
1853
1854 /*
1855  * procfs write method for MDT/hsm_control
1856  * proc entry is in mdt directory so data is mdt obd_device pointer
1857  */
1858 #define CDT_ENABLE_CMD   "enabled"
1859 #define CDT_STOP_CMD     "shutdown"
1860 #define CDT_DISABLE_CMD  "disabled"
1861 #define CDT_PURGE_CMD    "purge"
1862 #define CDT_HELP_CMD     "help"
1863 #define CDT_MAX_CMD_LEN  10
1864
1865 ssize_t
1866 mdt_hsm_cdt_control_seq_write(struct file *file, const char __user *buffer,
1867                               size_t count, loff_t *off)
1868 {
1869         struct seq_file         *m = file->private_data;
1870         struct obd_device       *obd = m->private;
1871         struct mdt_device       *mdt = mdt_dev(obd->obd_lu_dev);
1872         struct coordinator      *cdt = &(mdt->mdt_coordinator);
1873         int                      rc, usage = 0;
1874         char                     kernbuf[CDT_MAX_CMD_LEN];
1875         ENTRY;
1876
1877         if (count == 0 || count >= sizeof(kernbuf))
1878                 RETURN(-EINVAL);
1879
1880         if (copy_from_user(kernbuf, buffer, count))
1881                 RETURN(-EFAULT);
1882         kernbuf[count] = 0;
1883
1884         if (kernbuf[count - 1] == '\n')
1885                 kernbuf[count - 1] = 0;
1886
1887         rc = 0;
1888         if (strcmp(kernbuf, CDT_ENABLE_CMD) == 0) {
1889                 if (cdt->cdt_state == CDT_DISABLE) {
1890                         cdt->cdt_state = CDT_RUNNING;
1891                         mdt_hsm_cdt_wakeup(mdt);
1892                 } else {
1893                         rc = mdt_hsm_cdt_start(mdt);
1894                 }
1895         } else if (strcmp(kernbuf, CDT_STOP_CMD) == 0) {
1896                 if ((cdt->cdt_state == CDT_STOPPING) ||
1897                     (cdt->cdt_state == CDT_STOPPED)) {
1898                         CERROR("%s: Coordinator already stopped\n",
1899                                mdt_obd_name(mdt));
1900                         rc = -EALREADY;
1901                 } else {
1902                         cdt->cdt_state = CDT_STOPPING;
1903                 }
1904         } else if (strcmp(kernbuf, CDT_DISABLE_CMD) == 0) {
1905                 if ((cdt->cdt_state == CDT_STOPPING) ||
1906                     (cdt->cdt_state == CDT_STOPPED)) {
1907                         CERROR("%s: Coordinator is stopped\n",
1908                                mdt_obd_name(mdt));
1909                         rc = -EINVAL;
1910                 } else {
1911                         cdt->cdt_state = CDT_DISABLE;
1912                 }
1913         } else if (strcmp(kernbuf, CDT_PURGE_CMD) == 0) {
1914                 rc = hsm_cancel_all_actions(mdt);
1915         } else if (strcmp(kernbuf, CDT_HELP_CMD) == 0) {
1916                 usage = 1;
1917         } else {
1918                 usage = 1;
1919                 rc = -EINVAL;
1920         }
1921
1922         if (usage == 1)
1923                 CERROR("%s: Valid coordinator control commands are: "
1924                        "%s %s %s %s %s\n", mdt_obd_name(mdt),
1925                        CDT_ENABLE_CMD, CDT_STOP_CMD, CDT_DISABLE_CMD,
1926                        CDT_PURGE_CMD, CDT_HELP_CMD);
1927
1928         if (rc)
1929                 RETURN(rc);
1930
1931         RETURN(count);
1932 }
1933
1934 int mdt_hsm_cdt_control_seq_show(struct seq_file *m, void *data)
1935 {
1936         struct obd_device       *obd = m->private;
1937         struct coordinator      *cdt;
1938         ENTRY;
1939
1940         cdt = &(mdt_dev(obd->obd_lu_dev)->mdt_coordinator);
1941
1942         if (cdt->cdt_state == CDT_INIT)
1943                 seq_printf(m, "init\n");
1944         else if (cdt->cdt_state == CDT_RUNNING)
1945                 seq_printf(m, "enabled\n");
1946         else if (cdt->cdt_state == CDT_STOPPING)
1947                 seq_printf(m, "stopping\n");
1948         else if (cdt->cdt_state == CDT_STOPPED)
1949                 seq_printf(m, "stopped\n");
1950         else if (cdt->cdt_state == CDT_DISABLE)
1951                 seq_printf(m, "disabled\n");
1952         else
1953                 seq_printf(m, "unknown\n");
1954
1955         RETURN(0);
1956 }
1957
1958 static int
1959 mdt_hsm_request_mask_show(struct seq_file *m, __u64 mask)
1960 {
1961         bool first = true;
1962         int i;
1963         ENTRY;
1964
1965         for (i = 0; i < 8 * sizeof(mask); i++) {
1966                 if (mask & (1UL << i)) {
1967                         seq_printf(m, "%s%s", first ? "" : " ",
1968                                    hsm_copytool_action2name(i));
1969                         first = false;
1970                 }
1971         }
1972         seq_putc(m, '\n');
1973
1974         RETURN(0);
1975 }
1976
1977 static int
1978 mdt_hsm_user_request_mask_seq_show(struct seq_file *m, void *data)
1979 {
1980         struct mdt_device *mdt = m->private;
1981         struct coordinator *cdt = &mdt->mdt_coordinator;
1982
1983         return mdt_hsm_request_mask_show(m, cdt->cdt_user_request_mask);
1984 }
1985
1986 static int
1987 mdt_hsm_group_request_mask_seq_show(struct seq_file *m, void *data)
1988 {
1989         struct mdt_device *mdt = m->private;
1990         struct coordinator *cdt = &mdt->mdt_coordinator;
1991
1992         return mdt_hsm_request_mask_show(m, cdt->cdt_group_request_mask);
1993 }
1994
1995 static int
1996 mdt_hsm_other_request_mask_seq_show(struct seq_file *m, void *data)
1997 {
1998         struct mdt_device *mdt = m->private;
1999         struct coordinator *cdt = &mdt->mdt_coordinator;
2000
2001         return mdt_hsm_request_mask_show(m, cdt->cdt_other_request_mask);
2002 }
2003
2004 static inline enum hsm_copytool_action
2005 hsm_copytool_name2action(const char *name)
2006 {
2007         if (strcasecmp(name, "NOOP") == 0)
2008                 return HSMA_NONE;
2009         else if (strcasecmp(name, "ARCHIVE") == 0)
2010                 return HSMA_ARCHIVE;
2011         else if (strcasecmp(name, "RESTORE") == 0)
2012                 return HSMA_RESTORE;
2013         else if (strcasecmp(name, "REMOVE") == 0)
2014                 return HSMA_REMOVE;
2015         else if (strcasecmp(name, "CANCEL") == 0)
2016                 return HSMA_CANCEL;
2017         else
2018                 return -1;
2019 }
2020
2021 static ssize_t
2022 mdt_write_hsm_request_mask(struct file *file, const char __user *user_buf,
2023                             size_t user_count, __u64 *mask)
2024 {
2025         char *buf, *pos, *name;
2026         size_t buf_size;
2027         __u64 new_mask = 0;
2028         int rc;
2029         ENTRY;
2030
2031         if (!(user_count < 4096))
2032                 RETURN(-ENOMEM);
2033
2034         buf_size = user_count + 1;
2035
2036         OBD_ALLOC(buf, buf_size);
2037         if (buf == NULL)
2038                 RETURN(-ENOMEM);
2039
2040         if (copy_from_user(buf, user_buf, buf_size - 1))
2041                 GOTO(out, rc = -EFAULT);
2042
2043         buf[buf_size - 1] = '\0';
2044
2045         pos = buf;
2046         while ((name = strsep(&pos, " \t\v\n")) != NULL) {
2047                 int action;
2048
2049                 if (*name == '\0')
2050                         continue;
2051
2052                 action = hsm_copytool_name2action(name);
2053                 if (action < 0)
2054                         GOTO(out, rc = -EINVAL);
2055
2056                 new_mask |= (1UL << action);
2057         }
2058
2059         *mask = new_mask;
2060         rc = user_count;
2061 out:
2062         OBD_FREE(buf, buf_size);
2063
2064         RETURN(rc);
2065 }
2066
2067 static ssize_t
2068 mdt_hsm_user_request_mask_seq_write(struct file *file, const char __user *buf,
2069                                         size_t count, loff_t *off)
2070 {
2071         struct seq_file         *m = file->private_data;
2072         struct mdt_device       *mdt = m->private;
2073         struct coordinator *cdt = &mdt->mdt_coordinator;
2074
2075         return mdt_write_hsm_request_mask(file, buf, count,
2076                                            &cdt->cdt_user_request_mask);
2077 }
2078
2079 static ssize_t
2080 mdt_hsm_group_request_mask_seq_write(struct file *file, const char __user *buf,
2081                                         size_t count, loff_t *off)
2082 {
2083         struct seq_file         *m = file->private_data;
2084         struct mdt_device       *mdt = m->private;
2085         struct coordinator      *cdt = &mdt->mdt_coordinator;
2086
2087         return mdt_write_hsm_request_mask(file, buf, count,
2088                                            &cdt->cdt_group_request_mask);
2089 }
2090
2091 static ssize_t
2092 mdt_hsm_other_request_mask_seq_write(struct file *file, const char __user *buf,
2093                                         size_t count, loff_t *off)
2094 {
2095         struct seq_file         *m = file->private_data;
2096         struct mdt_device       *mdt = m->private;
2097         struct coordinator      *cdt = &mdt->mdt_coordinator;
2098
2099         return mdt_write_hsm_request_mask(file, buf, count,
2100                                            &cdt->cdt_other_request_mask);
2101 }
2102
2103 LPROC_SEQ_FOPS(mdt_hsm_cdt_loop_period);
2104 LPROC_SEQ_FOPS(mdt_hsm_cdt_grace_delay);
2105 LPROC_SEQ_FOPS(mdt_hsm_cdt_active_req_timeout);
2106 LPROC_SEQ_FOPS(mdt_hsm_cdt_max_requests);
2107 LPROC_SEQ_FOPS(mdt_hsm_cdt_default_archive_id);
2108 LPROC_SEQ_FOPS(mdt_hsm_user_request_mask);
2109 LPROC_SEQ_FOPS(mdt_hsm_group_request_mask);
2110 LPROC_SEQ_FOPS(mdt_hsm_other_request_mask);
2111
2112 static struct lprocfs_vars lprocfs_mdt_hsm_vars[] = {
2113         { .name =       "agents",
2114           .fops =       &mdt_hsm_agent_fops                     },
2115         { .name =       "actions",
2116           .fops =       &mdt_hsm_actions_fops,
2117           .proc_mode =  0444                                    },
2118         { .name =       "default_archive_id",
2119           .fops =       &mdt_hsm_cdt_default_archive_id_fops    },
2120         { .name =       "grace_delay",
2121           .fops =       &mdt_hsm_cdt_grace_delay_fops           },
2122         { .name =       "loop_period",
2123           .fops =       &mdt_hsm_cdt_loop_period_fops           },
2124         { .name =       "max_requests",
2125           .fops =       &mdt_hsm_cdt_max_requests_fops          },
2126         { .name =       "policy",
2127           .fops =       &mdt_hsm_policy_fops                    },
2128         { .name =       "active_request_timeout",
2129           .fops =       &mdt_hsm_cdt_active_req_timeout_fops    },
2130         { .name =       "active_requests",
2131           .fops =       &mdt_hsm_active_requests_fops           },
2132         { .name =       "user_request_mask",
2133           .fops =       &mdt_hsm_user_request_mask_fops,        },
2134         { .name =       "group_request_mask",
2135           .fops =       &mdt_hsm_group_request_mask_fops,       },
2136         { .name =       "other_request_mask",
2137           .fops =       &mdt_hsm_other_request_mask_fops,       },
2138         { 0 }
2139 };