Whamcloud - gitweb
LU-7988 hsm: change coordinator start/stop mechanisms
[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, 2016, 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);
286                 if (car == NULL) {
287                         last = larr->arr_req_change;
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         if (cdt->cdt_proc_dir != NULL)
390                 lprocfs_remove(&cdt->cdt_proc_dir);
391 }
392
393 /**
394  * get vector of hsm cdt /proc vars
395  * \param none
396  * \retval var vector
397  */
398 struct lprocfs_vars *hsm_cdt_get_proc_vars(void)
399 {
400         return lprocfs_mdt_hsm_vars;
401 }
402
403 /* Release the ressource used by the coordinator. Called when the
404  * coordinator is stopping. */
405 static void mdt_hsm_cdt_cleanup(struct mdt_device *mdt)
406 {
407         struct coordinator              *cdt = &mdt->mdt_coordinator;
408         struct cdt_agent_req            *car, *tmp1;
409         struct hsm_agent                *ha, *tmp2;
410         struct cdt_restore_handle       *crh, *tmp3;
411         struct mdt_thread_info          *cdt_mti;
412
413         /* start cleaning */
414         down_write(&cdt->cdt_request_lock);
415         list_for_each_entry_safe(car, tmp1, &cdt->cdt_request_list,
416                                  car_request_list) {
417                 cfs_hash_del(cdt->cdt_request_cookie_hash,
418                              &car->car_hai->hai_cookie,
419                              &car->car_cookie_hash);
420                 list_del(&car->car_request_list);
421                 mdt_cdt_put_request(car);
422         }
423         up_write(&cdt->cdt_request_lock);
424
425         down_write(&cdt->cdt_agent_lock);
426         list_for_each_entry_safe(ha, tmp2, &cdt->cdt_agents, ha_list) {
427                 list_del(&ha->ha_list);
428                 OBD_FREE_PTR(ha);
429         }
430         up_write(&cdt->cdt_agent_lock);
431
432         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
433         mutex_lock(&cdt->cdt_restore_lock);
434         list_for_each_entry_safe(crh, tmp3, &cdt->cdt_restore_hdl, crh_list) {
435                 struct mdt_object       *child;
436
437                 /* give back layout lock */
438                 child = mdt_object_find(&cdt->cdt_env, mdt, &crh->crh_fid);
439                 if (!IS_ERR(child))
440                         mdt_object_unlock_put(cdt_mti, child, &crh->crh_lh, 1);
441
442                 list_del(&crh->crh_list);
443
444                 OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
445         }
446         mutex_unlock(&cdt->cdt_restore_lock);
447 }
448
449 /*
450  * Coordinator state transition table, indexed on enum cdt_states, taking
451  * from and to states. For instance since CDT_INIT to CDT_RUNNING is a
452  * valid transition, cdt_transition[CDT_INIT][CDT_RUNNING] is true.
453  */
454 static bool cdt_transition[CDT_STATES_COUNT][CDT_STATES_COUNT] = {
455         /* from -> to:    stopped init   running disable stopping */
456         /* stopped */   { true,   true,  false,  false,  false },
457         /* init */      { true,   false, true,   false,  true },
458         /* running */   { false,  false, true,   true,   true },
459         /* disable */   { false,  false, true,   true,   true },
460         /* stopping */  { true,   false, false,  false,  true }
461 };
462
463 /**
464  * Change coordinator thread state
465  * Some combinations are not valid, so catch them here.
466  *
467  * Returns 0 on success, with old_state set if not NULL, or -EINVAL if
468  * the transition was not possible.
469  */
470 static int set_cdt_state(struct coordinator *cdt, enum cdt_states new_state,
471                          enum cdt_states *old_state)
472 {
473         int rc;
474         enum cdt_states state;
475
476         spin_lock(&cdt->cdt_state_lock);
477
478         state = cdt->cdt_state;
479
480         if (cdt_transition[state][new_state]) {
481                 cdt->cdt_state = new_state;
482                 spin_unlock(&cdt->cdt_state_lock);
483                 if (old_state)
484                         *old_state = state;
485                 rc = 0;
486         } else {
487                 spin_unlock(&cdt->cdt_state_lock);
488                 CDEBUG(D_HSM,
489                        "unexpected coordinator transition, from=%s, to=%s\n",
490                        cdt_mdt_state2str(state), cdt_mdt_state2str(new_state));
491                 rc = -EINVAL;
492         }
493
494         return rc;
495 }
496
497 /**
498  * coordinator thread
499  * \param data [IN] obd device
500  * \retval 0 success
501  * \retval -ve failure
502  */
503 static int mdt_coordinator(void *data)
504 {
505         struct mdt_thread_info  *mti = data;
506         struct mdt_device       *mdt = mti->mti_mdt;
507         struct coordinator      *cdt = &mdt->mdt_coordinator;
508         struct hsm_scan_data     hsd = { NULL };
509         int                      rc = 0;
510         int                      request_sz;
511         ENTRY;
512
513         CDEBUG(D_HSM, "%s: coordinator thread starting, pid=%d\n",
514                mdt_obd_name(mdt), current_pid());
515
516         /* we use a copy of cdt_max_requests in the cb, so if cdt_max_requests
517          * increases due to a change from /proc we do not overflow the
518          * hsd.request[] vector
519          */
520         hsd.max_requests = cdt->cdt_max_requests;
521         request_sz = hsd.max_requests * sizeof(*hsd.request);
522         OBD_ALLOC_LARGE(hsd.request, request_sz);
523         if (!hsd.request)
524                 GOTO(out, rc = -ENOMEM);
525
526         hsd.mti = mti;
527         obd_uuid2fsname(hsd.fs_name, mdt_obd_name(mdt), MTI_NAME_MAXLEN);
528
529         set_cdt_state(cdt, CDT_RUNNING, NULL);
530
531         /* Inform mdt_hsm_cdt_start(). */
532         wake_up_all(&cdt->cdt_waitq);
533
534         while (1) {
535                 struct l_wait_info lwi;
536                 int i;
537
538                 lwi = LWI_TIMEOUT(cfs_time_seconds(cdt->cdt_loop_period),
539                                   NULL, NULL);
540                 l_wait_event(cdt->cdt_waitq,
541                              (cdt->cdt_flags & SVC_EVENT) ||
542                              (cdt->cdt_state == CDT_STOPPING),
543                              &lwi);
544
545                 CDEBUG(D_HSM, "coordinator resumes\n");
546
547                 if (cdt->cdt_state == CDT_STOPPING) {
548                         rc = 0;
549                         break;
550                 }
551
552                 /* wake up before timeout, new work arrives */
553                 if (cdt->cdt_flags & SVC_EVENT)
554                         cdt->cdt_flags &= ~SVC_EVENT;
555
556                 /* if coordinator is suspended continue to wait */
557                 if (cdt->cdt_state == CDT_DISABLE) {
558                         CDEBUG(D_HSM, "disable state, coordinator sleeps\n");
559                         continue;
560                 }
561
562                 CDEBUG(D_HSM, "coordinator starts reading llog\n");
563
564                 if (hsd.max_requests != cdt->cdt_max_requests) {
565                         /* cdt_max_requests has changed,
566                          * we need to allocate a new buffer
567                          */
568                         OBD_FREE_LARGE(hsd.request, request_sz);
569                         hsd.max_requests = cdt->cdt_max_requests;
570                         request_sz = hsd.max_requests * sizeof(*hsd.request);
571                         OBD_ALLOC_LARGE(hsd.request, request_sz);
572                         if (!hsd.request) {
573                                 rc = -ENOMEM;
574                                 break;
575                         }
576                 }
577
578                 hsd.request_cnt = 0;
579
580                 rc = cdt_llog_process(mti->mti_env, mdt,
581                                       mdt_coordinator_cb, &hsd);
582                 if (rc < 0)
583                         goto clean_cb_alloc;
584
585                 CDEBUG(D_HSM, "found %d requests to send\n", hsd.request_cnt);
586
587                 if (list_empty(&cdt->cdt_agents)) {
588                         CDEBUG(D_HSM, "no agent available, "
589                                       "coordinator sleeps\n");
590                         goto clean_cb_alloc;
591                 }
592
593                 /* here hsd contains a list of requests to be started */
594                 for (i = 0; i < hsd.request_cnt; i++) {
595                         struct hsm_scan_request *request = &hsd.request[i];
596                         struct hsm_action_list  *hal = request->hal;
597                         struct hsm_action_item  *hai;
598                         __u64                   *cookies;
599                         int                      sz, j;
600                         enum agent_req_status    status;
601
602                         /* still room for work ? */
603                         if (atomic_read(&cdt->cdt_request_count) >=
604                             cdt->cdt_max_requests)
605                                 break;
606
607                         rc = mdt_hsm_agent_send(mti, hal, 0);
608                         /* if failure, we suppose it is temporary
609                          * if the copy tool failed to do the request
610                          * it has to use hsm_progress
611                          */
612                         status = (rc ? ARS_WAITING : ARS_STARTED);
613
614                         /* set up cookie vector to set records status
615                          * after copy tools start or failed
616                          */
617                         sz = hal->hal_count * sizeof(__u64);
618                         OBD_ALLOC(cookies, sz);
619                         if (cookies == NULL)
620                                 continue;
621
622                         hai = hai_first(hal);
623                         for (j = 0; j < hal->hal_count; j++) {
624                                 cookies[j] = hai->hai_cookie;
625                                 hai = hai_next(hai);
626                         }
627
628                         rc = mdt_agent_record_update(mti->mti_env, mdt, cookies,
629                                                      hal->hal_count, status);
630                         if (rc)
631                                 CERROR("%s: mdt_agent_record_update() failed, "
632                                        "rc=%d, cannot update status to %s "
633                                        "for %d cookies\n",
634                                        mdt_obd_name(mdt), rc,
635                                        agent_req_status2name(status),
636                                        hal->hal_count);
637
638                         OBD_FREE(cookies, sz);
639                 }
640 clean_cb_alloc:
641                 /* free hal allocated by callback */
642                 for (i = 0; i < hsd.request_cnt; i++) {
643                         struct hsm_scan_request *request = &hsd.request[i];
644
645                         OBD_FREE(request->hal, request->hal_sz);
646                 }
647         }
648         EXIT;
649 out:
650         set_cdt_state(cdt, CDT_STOPPING, NULL);
651
652         if (hsd.request)
653                 OBD_FREE_LARGE(hsd.request, request_sz);
654
655         mdt_hsm_cdt_cleanup(mdt);
656
657         set_cdt_state(cdt, CDT_STOPPED, NULL);
658         wake_up_all(&cdt->cdt_waitq);
659
660         if (rc != 0)
661                 CERROR("%s: coordinator thread exiting, process=%d, rc=%d\n",
662                        mdt_obd_name(mdt), current_pid(), rc);
663         else
664                 CDEBUG(D_HSM, "%s: coordinator thread exiting, process=%d,"
665                               " no error\n",
666                        mdt_obd_name(mdt), current_pid());
667
668         return rc;
669 }
670
671 /**
672  * lookup a restore handle by FID
673  * caller needs to hold cdt_restore_lock
674  * \param cdt [IN] coordinator
675  * \param fid [IN] FID
676  * \retval cdt_restore_handle found
677  * \retval NULL not found
678  */
679 struct cdt_restore_handle *mdt_hsm_restore_hdl_find(struct coordinator *cdt,
680                                                        const struct lu_fid *fid)
681 {
682         struct cdt_restore_handle       *crh;
683         ENTRY;
684
685         list_for_each_entry(crh, &cdt->cdt_restore_hdl, crh_list) {
686                 if (lu_fid_eq(&crh->crh_fid, fid))
687                         RETURN(crh);
688         }
689         RETURN(NULL);
690 }
691
692 /**
693  * data passed to llog_cat_process() callback
694  * to scan requests and take actions
695  */
696 struct hsm_restore_data {
697         struct mdt_thread_info  *hrd_mti;
698 };
699
700 /**
701  *  llog_cat_process() callback, used to:
702  *  - find restore request and allocate the restore handle
703  * \param env [IN] environment
704  * \param llh [IN] llog handle
705  * \param hdr [IN] llog record
706  * \param data [IN/OUT] cb data = struct hsm_restore_data
707  * \retval 0 success
708  * \retval -ve failure
709  */
710 static int hsm_restore_cb(const struct lu_env *env,
711                           struct llog_handle *llh,
712                           struct llog_rec_hdr *hdr, void *data)
713 {
714         struct llog_agent_req_rec       *larr;
715         struct hsm_restore_data         *hrd;
716         struct cdt_restore_handle       *crh;
717         struct hsm_action_item          *hai;
718         struct mdt_thread_info          *mti;
719         struct coordinator              *cdt;
720         struct mdt_object               *child;
721         int rc;
722         ENTRY;
723
724         hrd = data;
725         mti = hrd->hrd_mti;
726         cdt = &mti->mti_mdt->mdt_coordinator;
727
728         larr = (struct llog_agent_req_rec *)hdr;
729         hai = &larr->arr_hai;
730         if (hai->hai_cookie > cdt->cdt_last_cookie)
731                 /* update the cookie to avoid collision */
732                 cdt->cdt_last_cookie = hai->hai_cookie + 1;
733
734         if (hai->hai_action != HSMA_RESTORE ||
735             agent_req_in_final_state(larr->arr_status))
736                 RETURN(0);
737
738         /* restore request not in a final state */
739
740         /* force replay of restore requests left in started state from previous
741          * CDT context, to be canceled later if finally found to be incompatible
742          * when being re-started */
743         if (larr->arr_status == ARS_STARTED) {
744                 larr->arr_status = ARS_WAITING;
745                 larr->arr_req_change = cfs_time_current_sec();
746                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
747                 if (rc != 0)
748                         GOTO(out, rc);
749         }
750
751         OBD_SLAB_ALLOC_PTR(crh, mdt_hsm_cdt_kmem);
752         if (crh == NULL)
753                 RETURN(-ENOMEM);
754
755         crh->crh_fid = hai->hai_fid;
756         /* in V1 all file is restored
757         crh->extent.start = hai->hai_extent.offset;
758         crh->extent.end = hai->hai_extent.offset + hai->hai_extent.length;
759         */
760         crh->crh_extent.start = 0;
761         crh->crh_extent.end = hai->hai_extent.length;
762         /* get the layout lock */
763         mdt_lock_reg_init(&crh->crh_lh, LCK_EX);
764         child = mdt_object_find_lock(mti, &crh->crh_fid, &crh->crh_lh,
765                                      MDS_INODELOCK_LAYOUT);
766         if (IS_ERR(child))
767                 GOTO(out, rc = PTR_ERR(child));
768
769         rc = 0;
770         /* we choose to not keep a reference
771          * on the object during the restore time which can be very long */
772         mdt_object_put(mti->mti_env, child);
773
774         mutex_lock(&cdt->cdt_restore_lock);
775         list_add_tail(&crh->crh_list, &cdt->cdt_restore_hdl);
776         mutex_unlock(&cdt->cdt_restore_lock);
777
778 out:
779         RETURN(rc);
780 }
781
782 /**
783  * restore coordinator state at startup
784  * the goal is to take a layout lock for each registered restore request
785  * \param mti [IN] context
786  */
787 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti)
788 {
789         struct hsm_restore_data  hrd;
790         int                      rc;
791         ENTRY;
792
793         hrd.hrd_mti = mti;
794
795         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt,
796                               hsm_restore_cb, &hrd);
797
798         RETURN(rc);
799 }
800
801 static int hsm_init_ucred(struct lu_ucred *uc)
802 {
803         ENTRY;
804
805         uc->uc_valid = UCRED_OLD;
806         uc->uc_o_uid = 0;
807         uc->uc_o_gid = 0;
808         uc->uc_o_fsuid = 0;
809         uc->uc_o_fsgid = 0;
810         uc->uc_uid = 0;
811         uc->uc_gid = 0;
812         uc->uc_fsuid = 0;
813         uc->uc_fsgid = 0;
814         uc->uc_suppgids[0] = -1;
815         uc->uc_suppgids[1] = -1;
816         uc->uc_cap = CFS_CAP_FS_MASK;
817         uc->uc_umask = 0777;
818         uc->uc_ginfo = NULL;
819         uc->uc_identity = NULL;
820
821         RETURN(0);
822 }
823
824 /**
825  * wake up coordinator thread
826  * \param mdt [IN] device
827  * \retval 0 success
828  * \retval -ve failure
829  */
830 int mdt_hsm_cdt_wakeup(struct mdt_device *mdt)
831 {
832         struct coordinator      *cdt = &mdt->mdt_coordinator;
833         ENTRY;
834
835         if (cdt->cdt_state == CDT_STOPPED)
836                 RETURN(-ESRCH);
837
838         /* wake up coordinator */
839         cdt->cdt_flags = SVC_EVENT;
840         wake_up_all(&cdt->cdt_waitq);
841
842         RETURN(0);
843 }
844
845 /**
846  * initialize coordinator struct
847  * \param mdt [IN] device
848  * \retval 0 success
849  * \retval -ve failure
850  */
851 int mdt_hsm_cdt_init(struct mdt_device *mdt)
852 {
853         struct coordinator      *cdt = &mdt->mdt_coordinator;
854         struct mdt_thread_info  *cdt_mti = NULL;
855         int                      rc;
856         ENTRY;
857
858         init_waitqueue_head(&cdt->cdt_waitq);
859         mutex_init(&cdt->cdt_llog_lock);
860         init_rwsem(&cdt->cdt_agent_lock);
861         init_rwsem(&cdt->cdt_request_lock);
862         mutex_init(&cdt->cdt_restore_lock);
863         spin_lock_init(&cdt->cdt_state_lock);
864         cdt->cdt_state = CDT_STOPPED;
865
866         INIT_LIST_HEAD(&cdt->cdt_request_list);
867         INIT_LIST_HEAD(&cdt->cdt_agents);
868         INIT_LIST_HEAD(&cdt->cdt_restore_hdl);
869
870         cdt->cdt_request_cookie_hash = cfs_hash_create("REQUEST_COOKIE_HASH",
871                                                        CFS_HASH_BITS_MIN,
872                                                        CFS_HASH_BITS_MAX,
873                                                        CFS_HASH_BKT_BITS,
874                                                        0 /* extra bytes */,
875                                                        CFS_HASH_MIN_THETA,
876                                                        CFS_HASH_MAX_THETA,
877                                                 &cdt_request_cookie_hash_ops,
878                                                        CFS_HASH_DEFAULT);
879         if (cdt->cdt_request_cookie_hash == NULL)
880                 RETURN(-ENOMEM);
881
882         rc = lu_env_init(&cdt->cdt_env, LCT_MD_THREAD);
883         if (rc < 0)
884                 GOTO(out_request_cookie_hash, rc);
885
886         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
887         rc = lu_context_init(&cdt->cdt_session, LCT_SERVER_SESSION);
888         if (rc < 0)
889                 GOTO(out_env, rc);
890
891         lu_context_enter(&cdt->cdt_session);
892         cdt->cdt_env.le_ses = &cdt->cdt_session;
893
894         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
895         LASSERT(cdt_mti != NULL);
896
897         cdt_mti->mti_env = &cdt->cdt_env;
898         cdt_mti->mti_mdt = mdt;
899
900         hsm_init_ucred(mdt_ucred(cdt_mti));
901
902         /* default values for /proc tunnables
903          * can be override by MGS conf */
904         cdt->cdt_default_archive_id = 1;
905         cdt->cdt_grace_delay = 60;
906         cdt->cdt_loop_period = 10;
907         cdt->cdt_max_requests = 3;
908         cdt->cdt_policy = CDT_DEFAULT_POLICY;
909         cdt->cdt_active_req_timeout = 3600;
910
911         RETURN(0);
912
913 out_env:
914         lu_env_fini(&cdt->cdt_env);
915 out_request_cookie_hash:
916         cfs_hash_putref(cdt->cdt_request_cookie_hash);
917         cdt->cdt_request_cookie_hash = NULL;
918
919         return rc;
920 }
921
922 /**
923  * free a coordinator thread
924  * \param mdt [IN] device
925  */
926 int  mdt_hsm_cdt_fini(struct mdt_device *mdt)
927 {
928         struct coordinator *cdt = &mdt->mdt_coordinator;
929         ENTRY;
930
931         lu_context_exit(cdt->cdt_env.le_ses);
932         lu_context_fini(cdt->cdt_env.le_ses);
933
934         lu_env_fini(&cdt->cdt_env);
935
936         cfs_hash_putref(cdt->cdt_request_cookie_hash);
937         cdt->cdt_request_cookie_hash = NULL;
938
939         RETURN(0);
940 }
941
942 /**
943  * start a coordinator thread
944  * \param mdt [IN] device
945  * \retval 0 success
946  * \retval -ve failure
947  */
948 static int mdt_hsm_cdt_start(struct mdt_device *mdt)
949 {
950         struct coordinator      *cdt = &mdt->mdt_coordinator;
951         int                      rc;
952         void                    *ptr;
953         struct mdt_thread_info  *cdt_mti;
954         struct task_struct      *task;
955         ENTRY;
956
957         /* functions defined but not yet used
958          * this avoid compilation warning
959          */
960         ptr = dump_requests;
961
962         rc = set_cdt_state(cdt, CDT_INIT, NULL);
963         if (rc) {
964                 CERROR("%s: Coordinator already started or stopping\n",
965                        mdt_obd_name(mdt));
966                 RETURN(-EALREADY);
967         }
968
969         CLASSERT(1 << (CDT_POLICY_SHIFT_COUNT - 1) == CDT_POLICY_LAST);
970         cdt->cdt_policy = CDT_DEFAULT_POLICY;
971
972         atomic_set(&cdt->cdt_compound_id, cfs_time_current_sec());
973         /* just need to be larger than previous one */
974         /* cdt_last_cookie is protected by cdt_llog_lock */
975         cdt->cdt_last_cookie = cfs_time_current_sec();
976         atomic_set(&cdt->cdt_request_count, 0);
977         cdt->cdt_user_request_mask = (1UL << HSMA_RESTORE);
978         cdt->cdt_group_request_mask = (1UL << HSMA_RESTORE);
979         cdt->cdt_other_request_mask = (1UL << HSMA_RESTORE);
980
981         /* to avoid deadlock when start is made through /proc
982          * /proc entries are created by the coordinator thread */
983
984         /* set up list of started restore requests */
985         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
986         rc = mdt_hsm_pending_restore(cdt_mti);
987         if (rc)
988                 CERROR("%s: cannot take the layout locks needed"
989                        " for registered restore: %d\n",
990                        mdt_obd_name(mdt), rc);
991
992         if (mdt->mdt_bottom->dd_rdonly)
993                 RETURN(0);
994
995         task = kthread_run(mdt_coordinator, cdt_mti, "hsm_cdtr");
996         if (IS_ERR(task)) {
997                 rc = PTR_ERR(task);
998                 set_cdt_state(cdt, CDT_STOPPED, NULL);
999                 CERROR("%s: error starting coordinator thread: %d\n",
1000                        mdt_obd_name(mdt), rc);
1001         } else {
1002                 wait_event(cdt->cdt_waitq,
1003                            cdt->cdt_state != CDT_INIT);
1004                 if (cdt->cdt_state == CDT_RUNNING) {
1005                         CDEBUG(D_HSM, "%s: coordinator thread started\n",
1006                                mdt_obd_name(mdt));
1007                         rc = 0;
1008                 } else {
1009                         CDEBUG(D_HSM,
1010                                "%s: coordinator thread failed to start\n",
1011                                mdt_obd_name(mdt));
1012                         rc = -EINVAL;
1013                 }
1014         }
1015
1016         RETURN(rc);
1017 }
1018
1019 /**
1020  * stop a coordinator thread
1021  * \param mdt [IN] device
1022  */
1023 int mdt_hsm_cdt_stop(struct mdt_device *mdt)
1024 {
1025         struct coordinator *cdt = &mdt->mdt_coordinator;
1026         int rc;
1027
1028         ENTRY;
1029         /* stop coordinator thread */
1030         rc = set_cdt_state(cdt, CDT_STOPPING, NULL);
1031         if (rc != 0)
1032                 RETURN(rc);
1033
1034         wake_up_all(&cdt->cdt_waitq);
1035         wait_event(cdt->cdt_waitq, cdt->cdt_state != CDT_STOPPING);
1036
1037         RETURN(rc);
1038 }
1039
1040 static int mdt_hsm_set_exists(struct mdt_thread_info *mti,
1041                               const struct lu_fid *fid,
1042                               u32 archive_id)
1043 {
1044         struct mdt_object *obj;
1045         struct md_hsm mh;
1046         int rc;
1047
1048         obj = mdt_hsm_get_md_hsm(mti, fid, &mh);
1049         if (IS_ERR(obj))
1050                 GOTO(out, rc = PTR_ERR(obj));
1051
1052         if (mh.mh_flags & HS_EXISTS &&
1053             mh.mh_arch_id == archive_id)
1054                 GOTO(out_obj, rc = 0);
1055
1056         mh.mh_flags |= HS_EXISTS;
1057         mh.mh_arch_id = archive_id;
1058         rc = mdt_hsm_attr_set(mti, obj, &mh);
1059
1060 out_obj:
1061         mdt_object_put(mti->mti_env, obj);
1062 out:
1063         return rc;
1064 }
1065
1066 /**
1067  * register all requests from an hal in the memory list
1068  * \param mti [IN] context
1069  * \param hal [IN] request
1070  * \param uuid [OUT] in case of CANCEL, the uuid of the agent
1071  *  which is running the CT
1072  * \retval 0 success
1073  * \retval -ve failure
1074  */
1075 int mdt_hsm_add_hal(struct mdt_thread_info *mti,
1076                     struct hsm_action_list *hal, struct obd_uuid *uuid)
1077 {
1078         struct mdt_device       *mdt = mti->mti_mdt;
1079         struct coordinator      *cdt = &mdt->mdt_coordinator;
1080         struct hsm_action_item  *hai;
1081         int                      rc = 0, i;
1082         ENTRY;
1083
1084         /* register request in memory list */
1085         hai = hai_first(hal);
1086         for (i = 0; i < hal->hal_count; i++, hai = hai_next(hai)) {
1087                 struct cdt_agent_req *car;
1088
1089                 /* in case of a cancel request, we first mark the ondisk
1090                  * record of the request we want to stop as canceled
1091                  * this does not change the cancel record
1092                  * it will be done when updating the request status
1093                  */
1094                 if (hai->hai_action == HSMA_CANCEL) {
1095                         rc = mdt_agent_record_update(mti->mti_env, mti->mti_mdt,
1096                                                      &hai->hai_cookie,
1097                                                      1, ARS_CANCELED);
1098                         if (rc) {
1099                                 CERROR("%s: mdt_agent_record_update() failed, "
1100                                        "rc=%d, cannot update status to %s "
1101                                        "for cookie %#llx\n",
1102                                        mdt_obd_name(mdt), rc,
1103                                        agent_req_status2name(ARS_CANCELED),
1104                                        hai->hai_cookie);
1105                                 GOTO(out, rc);
1106                         }
1107
1108                         /* find the running request to set it canceled */
1109                         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
1110                         if (car != NULL) {
1111                                 car->car_canceled = 1;
1112                                 /* uuid has to be changed to the one running the
1113                                 * request to cancel */
1114                                 *uuid = car->car_uuid;
1115                                 mdt_cdt_put_request(car);
1116                         }
1117                         /* no need to memorize cancel request
1118                          * this also avoid a deadlock when we receive
1119                          * a purge all requests command
1120                          */
1121                         continue;
1122                 }
1123
1124                 if (hai->hai_action == HSMA_ARCHIVE) {
1125                         rc = mdt_hsm_set_exists(mti, &hai->hai_fid,
1126                                                 hal->hal_archive_id);
1127                         if (rc == -ENOENT)
1128                                 continue;
1129                         else if (rc < 0)
1130                                 GOTO(out, rc);
1131                 }
1132
1133                 car = mdt_cdt_alloc_request(hal->hal_compound_id,
1134                                             hal->hal_archive_id, hal->hal_flags,
1135                                             uuid, hai);
1136                 if (IS_ERR(car))
1137                         GOTO(out, rc = PTR_ERR(car));
1138
1139                 rc = mdt_cdt_add_request(cdt, car);
1140                 if (rc != 0)
1141                         mdt_cdt_free_request(car);
1142         }
1143 out:
1144         RETURN(rc);
1145 }
1146
1147 /**
1148  * swap layouts between 2 fids
1149  * \param mti [IN] context
1150  * \param obj [IN]
1151  * \param dfid [IN]
1152  * \param mh_common [IN] MD HSM
1153  */
1154 static int hsm_swap_layouts(struct mdt_thread_info *mti,
1155                             struct mdt_object *obj, const struct lu_fid *dfid,
1156                             struct md_hsm *mh_common)
1157 {
1158         struct mdt_object       *dobj;
1159         struct mdt_lock_handle  *dlh;
1160         int                      rc;
1161         ENTRY;
1162
1163         if (!mdt_object_exists(obj))
1164                 GOTO(out, rc = -ENOENT);
1165
1166         /* we already have layout lock on obj so take only
1167          * on dfid */
1168         dlh = &mti->mti_lh[MDT_LH_OLD];
1169         mdt_lock_reg_init(dlh, LCK_EX);
1170         dobj = mdt_object_find_lock(mti, dfid, dlh, MDS_INODELOCK_LAYOUT);
1171         if (IS_ERR(dobj))
1172                 GOTO(out, rc = PTR_ERR(dobj));
1173
1174         /* if copy tool closes the volatile before sending the final
1175          * progress through llapi_hsm_copy_end(), all the objects
1176          * are removed and mdd_swap_layout LBUG */
1177         if (!mdt_object_exists(dobj)) {
1178                 CERROR("%s: Copytool has closed volatile file "DFID"\n",
1179                        mdt_obd_name(mti->mti_mdt), PFID(dfid));
1180                 GOTO(out_dobj, rc = -ENOENT);
1181         }
1182         /* Since we only handle restores here, unconditionally use
1183          * SWAP_LAYOUTS_MDS_HSM flag to ensure original layout will
1184          * be preserved in case of failure during swap_layout and not
1185          * leave a file in an intermediate but incoherent state.
1186          * But need to setup HSM xattr of data FID before, reuse
1187          * mti and mh presets for FID in hsm_cdt_request_completed(),
1188          * only need to clear RELEASED and DIRTY.
1189          */
1190         mh_common->mh_flags &= ~(HS_RELEASED | HS_DIRTY);
1191         rc = mdt_hsm_attr_set(mti, dobj, mh_common);
1192         if (rc == 0)
1193                 rc = mo_swap_layouts(mti->mti_env,
1194                                      mdt_object_child(obj),
1195                                      mdt_object_child(dobj),
1196                                      SWAP_LAYOUTS_MDS_HSM);
1197
1198 out_dobj:
1199         mdt_object_unlock_put(mti, dobj, dlh, 1);
1200 out:
1201         RETURN(rc);
1202 }
1203
1204 /**
1205  * update status of a completed request
1206  * \param mti [IN] context
1207  * \param pgs [IN] progress of the copy tool
1208  * \param update_record [IN] update llog record
1209  * \retval 0 success
1210  * \retval -ve failure
1211  */
1212 static int hsm_cdt_request_completed(struct mdt_thread_info *mti,
1213                                      struct hsm_progress_kernel *pgs,
1214                                      const struct cdt_agent_req *car,
1215                                      enum agent_req_status *status)
1216 {
1217         const struct lu_env     *env = mti->mti_env;
1218         struct mdt_device       *mdt = mti->mti_mdt;
1219         struct coordinator      *cdt = &mdt->mdt_coordinator;
1220         struct mdt_object       *obj = NULL;
1221         int                      cl_flags = 0, rc = 0;
1222         struct md_hsm            mh;
1223         bool                     is_mh_changed;
1224         bool                     need_changelog = true;
1225         ENTRY;
1226
1227         /* default is to retry */
1228         *status = ARS_WAITING;
1229
1230         /* find object by FID, mdt_hsm_get_md_hsm() returns obj or err
1231          * if error/removed continue anyway to get correct reporting done */
1232         obj = mdt_hsm_get_md_hsm(mti, &car->car_hai->hai_fid, &mh);
1233         /* we will update MD HSM only if needed */
1234         is_mh_changed = false;
1235
1236         /* no need to change mh->mh_arch_id
1237          * mdt_hsm_get_md_hsm() got it from disk and it is still valid
1238          */
1239         if (pgs->hpk_errval != 0) {
1240                 switch (pgs->hpk_errval) {
1241                 case ENOSYS:
1242                         /* the copy tool does not support cancel
1243                          * so the cancel request is failed
1244                          * As we cannot distinguish a cancel progress
1245                          * from another action progress (they have the
1246                          * same cookie), we suppose here the CT returns
1247                          * ENOSYS only if does not support cancel
1248                          */
1249                         /* this can also happen when cdt calls it to
1250                          * for a timed out request */
1251                         *status = ARS_FAILED;
1252                         /* to have a cancel event in changelog */
1253                         pgs->hpk_errval = ECANCELED;
1254                         break;
1255                 case ECANCELED:
1256                         /* the request record has already been set to
1257                          * ARS_CANCELED, this set the cancel request
1258                          * to ARS_SUCCEED */
1259                         *status = ARS_SUCCEED;
1260                         break;
1261                 default:
1262                         /* retry only if current policy or requested, and
1263                          * object is not on error/removed */
1264                         *status = (cdt->cdt_policy & CDT_NORETRY_ACTION ||
1265                                    !(pgs->hpk_flags & HP_FLAG_RETRY) ||
1266                                    IS_ERR(obj)) ? ARS_FAILED : ARS_WAITING;
1267                         break;
1268                 }
1269
1270                 if (pgs->hpk_errval > CLF_HSM_MAXERROR) {
1271                         CERROR("%s: Request %#llx on "DFID
1272                                " failed, error code %d too large\n",
1273                                mdt_obd_name(mdt),
1274                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1275                                pgs->hpk_errval);
1276                         hsm_set_cl_error(&cl_flags,
1277                                          CLF_HSM_ERROVERFLOW);
1278                         rc = -EINVAL;
1279                 } else {
1280                         hsm_set_cl_error(&cl_flags, pgs->hpk_errval);
1281                 }
1282
1283                 switch (car->car_hai->hai_action) {
1284                 case HSMA_ARCHIVE:
1285                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1286                         break;
1287                 case HSMA_RESTORE:
1288                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1289                         break;
1290                 case HSMA_REMOVE:
1291                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1292                         break;
1293                 case HSMA_CANCEL:
1294                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1295                         CERROR("%s: Failed request %#llx on "DFID
1296                                " cannot be a CANCEL\n",
1297                                mdt_obd_name(mdt),
1298                                pgs->hpk_cookie,
1299                                PFID(&pgs->hpk_fid));
1300                         break;
1301                 default:
1302                         CERROR("%s: Failed request %#llx on "DFID
1303                                " %d is an unknown action\n",
1304                                mdt_obd_name(mdt),
1305                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1306                                car->car_hai->hai_action);
1307                         rc = -EINVAL;
1308                         break;
1309                 }
1310         } else {
1311                 *status = ARS_SUCCEED;
1312                 switch (car->car_hai->hai_action) {
1313                 case HSMA_ARCHIVE:
1314                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1315                         /* set ARCHIVE keep EXIST and clear LOST and
1316                          * DIRTY */
1317                         mh.mh_arch_ver = pgs->hpk_data_version;
1318                         mh.mh_flags |= HS_ARCHIVED;
1319                         mh.mh_flags &= ~(HS_LOST|HS_DIRTY);
1320                         is_mh_changed = true;
1321                         break;
1322                 case HSMA_RESTORE:
1323                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1324
1325                         /* do not clear RELEASED and DIRTY here
1326                          * this will occur in hsm_swap_layouts()
1327                          */
1328
1329                         /* Restoring has changed the file version on
1330                          * disk. */
1331                         mh.mh_arch_ver = pgs->hpk_data_version;
1332                         is_mh_changed = true;
1333                         break;
1334                 case HSMA_REMOVE:
1335                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1336                         /* clear ARCHIVED EXISTS and LOST */
1337                         mh.mh_flags &= ~(HS_ARCHIVED | HS_EXISTS | HS_LOST);
1338                         is_mh_changed = true;
1339                         break;
1340                 case HSMA_CANCEL:
1341                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1342                         CERROR("%s: Successful request %#llx on "DFID" cannot be a CANCEL\n",
1343                                mdt_obd_name(mdt),
1344                                pgs->hpk_cookie,
1345                                PFID(&pgs->hpk_fid));
1346                         break;
1347                 default:
1348                         CERROR("%s: Successful request %#llx on "DFID" %d is an unknown action\n",
1349                                mdt_obd_name(mdt),
1350                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1351                                car->car_hai->hai_action);
1352                         rc = -EINVAL;
1353                         break;
1354                 }
1355         }
1356
1357         /* rc != 0 means error when analysing action, it may come from
1358          * a crasy CT no need to manage DIRTY
1359          */
1360         if (rc == 0)
1361                 hsm_set_cl_flags(&cl_flags,
1362                                  mh.mh_flags & HS_DIRTY ? CLF_HSM_DIRTY : 0);
1363
1364         /* unlock is done later, after layout lock management */
1365         if (is_mh_changed && !IS_ERR(obj))
1366                 rc = mdt_hsm_attr_set(mti, obj, &mh);
1367
1368         /* we give back layout lock only if restore was successful or
1369          * if no retry will be attempted and if object is still alive,
1370          * in other cases we just unlock the object */
1371         if (car->car_hai->hai_action == HSMA_RESTORE) {
1372                 struct cdt_restore_handle       *crh;
1373
1374                 /* restore in data FID done, we swap the layouts
1375                  * only if restore is successful */
1376                 if (pgs->hpk_errval == 0 && !IS_ERR(obj)) {
1377                         rc = hsm_swap_layouts(mti, obj, &car->car_hai->hai_dfid,
1378                                               &mh);
1379                         if (rc) {
1380                                 if (cdt->cdt_policy & CDT_NORETRY_ACTION)
1381                                         *status = ARS_FAILED;
1382                                 pgs->hpk_errval = -rc;
1383                         }
1384                 }
1385                 /* we have to retry, so keep layout lock */
1386                 if (*status == ARS_WAITING)
1387                         GOTO(out, rc);
1388
1389                 /* restore special case, need to create ChangeLog record
1390                  * before to give back layout lock to avoid concurrent
1391                  * file updater to post out of order ChangeLog */
1392                 mo_changelog(env, CL_HSM, cl_flags, mdt->mdt_child,
1393                              &car->car_hai->hai_fid);
1394                 need_changelog = false;
1395
1396                 /* give back layout lock */
1397                 mutex_lock(&cdt->cdt_restore_lock);
1398                 crh = mdt_hsm_restore_hdl_find(cdt, &car->car_hai->hai_fid);
1399                 if (crh != NULL)
1400                         list_del(&crh->crh_list);
1401                 mutex_unlock(&cdt->cdt_restore_lock);
1402                 /* Just give back layout lock, we keep the reference
1403                  * which is given back later with the lock for HSM
1404                  * flags.
1405                  * XXX obj may be invalid so we do not pass it. */
1406                 if (crh != NULL)
1407                         mdt_object_unlock(mti, NULL, &crh->crh_lh, 1);
1408
1409                 if (crh != NULL)
1410                         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
1411         }
1412
1413         GOTO(out, rc);
1414
1415 out:
1416         /* always add a ChangeLog record */
1417         if (need_changelog)
1418                 mo_changelog(env, CL_HSM, cl_flags, mdt->mdt_child,
1419                              &car->car_hai->hai_fid);
1420
1421         if (!IS_ERR(obj))
1422                 mdt_object_put(mti->mti_env, obj);
1423
1424         RETURN(rc);
1425 }
1426
1427 /**
1428  * update status of a request
1429  * \param mti [IN] context
1430  * \param pgs [IN] progress of the copy tool
1431  * \param update_record [IN] update llog record
1432  * \retval 0 success
1433  * \retval -ve failure
1434  */
1435 int mdt_hsm_update_request_state(struct mdt_thread_info *mti,
1436                                  struct hsm_progress_kernel *pgs,
1437                                  const int update_record)
1438 {
1439         struct mdt_device       *mdt = mti->mti_mdt;
1440         struct coordinator      *cdt = &mdt->mdt_coordinator;
1441         struct cdt_agent_req    *car;
1442         int                      rc = 0;
1443         ENTRY;
1444
1445         /* no coordinator started, so we cannot serve requests */
1446         if (cdt->cdt_state == CDT_STOPPED)
1447                 RETURN(-EAGAIN);
1448
1449         /* first do sanity checks */
1450         car = mdt_cdt_update_request(cdt, pgs);
1451         if (IS_ERR(car)) {
1452                 CERROR("%s: Cannot find running request for cookie %#llx"
1453                        " on fid="DFID"\n",
1454                        mdt_obd_name(mdt),
1455                        pgs->hpk_cookie, PFID(&pgs->hpk_fid));
1456
1457                 RETURN(PTR_ERR(car));
1458         }
1459
1460         CDEBUG(D_HSM, "Progress received for fid="DFID" cookie=%#llx"
1461                       " action=%s flags=%d err=%d fid="DFID" dfid="DFID"\n",
1462                       PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1463                       hsm_copytool_action2name(car->car_hai->hai_action),
1464                       pgs->hpk_flags, pgs->hpk_errval,
1465                       PFID(&car->car_hai->hai_fid),
1466                       PFID(&car->car_hai->hai_dfid));
1467
1468         /* progress is done on FID or data FID depending of the action and
1469          * of the copy progress */
1470         /* for restore progress is used to send back the data FID to cdt */
1471         if (car->car_hai->hai_action == HSMA_RESTORE &&
1472             lu_fid_eq(&car->car_hai->hai_fid, &car->car_hai->hai_dfid))
1473                 car->car_hai->hai_dfid = pgs->hpk_fid;
1474
1475         if ((car->car_hai->hai_action == HSMA_RESTORE ||
1476              car->car_hai->hai_action == HSMA_ARCHIVE) &&
1477             (!lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_dfid) &&
1478              !lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_fid))) {
1479                 CERROR("%s: Progress on "DFID" for cookie %#llx"
1480                        " does not match request FID "DFID" nor data FID "
1481                        DFID"\n",
1482                        mdt_obd_name(mdt),
1483                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1484                        PFID(&car->car_hai->hai_fid),
1485                        PFID(&car->car_hai->hai_dfid));
1486                 GOTO(out, rc = -EINVAL);
1487         }
1488
1489         if (pgs->hpk_errval != 0 && !(pgs->hpk_flags & HP_FLAG_COMPLETED)) {
1490                 CERROR("%s: Progress on "DFID" for cookie %#llx action=%s"
1491                        " is not coherent (err=%d and not completed"
1492                        " (flags=%d))\n",
1493                        mdt_obd_name(mdt),
1494                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1495                        hsm_copytool_action2name(car->car_hai->hai_action),
1496                        pgs->hpk_errval, pgs->hpk_flags);
1497                 GOTO(out, rc = -EINVAL);
1498         }
1499
1500         /* now progress is valid */
1501
1502         /* we use a root like ucred */
1503         hsm_init_ucred(mdt_ucred(mti));
1504
1505         if (pgs->hpk_flags & HP_FLAG_COMPLETED) {
1506                 enum agent_req_status    status;
1507
1508                 rc = hsm_cdt_request_completed(mti, pgs, car, &status);
1509
1510                 CDEBUG(D_HSM, "%s record: fid="DFID" cookie=%#llx action=%s "
1511                               "status=%s\n",
1512                        update_record ? "Updating" : "Not updating",
1513                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1514                        hsm_copytool_action2name(car->car_hai->hai_action),
1515                        agent_req_status2name(status));
1516
1517                 /* update record first (LU-9075) */
1518                 if (update_record) {
1519                         int rc1;
1520
1521                         rc1 = mdt_agent_record_update(mti->mti_env, mdt,
1522                                                      &pgs->hpk_cookie, 1,
1523                                                      status);
1524                         if (rc1)
1525                                 CERROR("%s: mdt_agent_record_update() failed,"
1526                                        " rc=%d, cannot update status to %s"
1527                                        " for cookie %#llx\n",
1528                                        mdt_obd_name(mdt), rc1,
1529                                        agent_req_status2name(status),
1530                                        pgs->hpk_cookie);
1531                         rc = (rc != 0 ? rc : rc1);
1532                 }
1533
1534                 /* then remove request from memory list (LU-9075) */
1535                 mdt_cdt_remove_request(cdt, pgs->hpk_cookie);
1536
1537                 /* ct has completed a request, so a slot is available, wakeup
1538                  * cdt to find new work */
1539                 mdt_hsm_cdt_wakeup(mdt);
1540         } else {
1541                 /* if copytool send a progress on a canceled request
1542                  * we inform copytool it should stop
1543                  */
1544                 if (car->car_canceled == 1)
1545                         rc = -ECANCELED;
1546         }
1547         GOTO(out, rc);
1548
1549 out:
1550         /* remove ref got from mdt_cdt_update_request() */
1551         mdt_cdt_put_request(car);
1552
1553         return rc;
1554 }
1555
1556
1557 /**
1558  * data passed to llog_cat_process() callback
1559  * to cancel requests
1560  */
1561 struct hsm_cancel_all_data {
1562         struct mdt_device       *mdt;
1563 };
1564
1565 /**
1566  *  llog_cat_process() callback, used to:
1567  *  - purge all requests
1568  * \param env [IN] environment
1569  * \param llh [IN] llog handle
1570  * \param hdr [IN] llog record
1571  * \param data [IN] cb data = struct hsm_cancel_all_data
1572  * \retval 0 success
1573  * \retval -ve failure
1574  */
1575 static int mdt_cancel_all_cb(const struct lu_env *env,
1576                              struct llog_handle *llh,
1577                              struct llog_rec_hdr *hdr, void *data)
1578 {
1579         struct llog_agent_req_rec       *larr;
1580         struct hsm_cancel_all_data      *hcad;
1581         int                              rc = 0;
1582         ENTRY;
1583
1584         larr = (struct llog_agent_req_rec *)hdr;
1585         hcad = data;
1586         if (larr->arr_status == ARS_WAITING ||
1587             larr->arr_status == ARS_STARTED) {
1588                 larr->arr_status = ARS_CANCELED;
1589                 larr->arr_req_change = cfs_time_current_sec();
1590                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
1591         }
1592
1593         RETURN(rc);
1594 }
1595
1596 /**
1597  * cancel all actions
1598  * \param obd [IN] MDT device
1599  */
1600 static int hsm_cancel_all_actions(struct mdt_device *mdt)
1601 {
1602         struct lu_env                    env;
1603         struct lu_context                session;
1604         struct mdt_thread_info          *mti;
1605         struct coordinator              *cdt = &mdt->mdt_coordinator;
1606         struct cdt_agent_req            *car;
1607         struct hsm_action_list          *hal = NULL;
1608         struct hsm_action_item          *hai;
1609         struct hsm_cancel_all_data       hcad;
1610         int                              hal_sz = 0, hal_len, rc;
1611         enum cdt_states                  old_state;
1612         ENTRY;
1613
1614         rc = lu_env_init(&env, LCT_MD_THREAD);
1615         if (rc < 0)
1616                 RETURN(rc);
1617
1618         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1619         rc = lu_context_init(&session, LCT_SERVER_SESSION);
1620         if (rc < 0)
1621                 GOTO(out_env, rc);
1622
1623         lu_context_enter(&session);
1624         env.le_ses = &session;
1625
1626         mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
1627         LASSERT(mti != NULL);
1628
1629         mti->mti_env = &env;
1630         mti->mti_mdt = mdt;
1631
1632         hsm_init_ucred(mdt_ucred(mti));
1633
1634         /* disable coordinator */
1635         rc = set_cdt_state(cdt, CDT_DISABLE, &old_state);
1636         if (rc)
1637                 RETURN(rc);
1638
1639         /* send cancel to all running requests */
1640         down_read(&cdt->cdt_request_lock);
1641         list_for_each_entry(car, &cdt->cdt_request_list, car_request_list) {
1642                 mdt_cdt_get_request(car);
1643                 /* request is not yet removed from list, it will be done
1644                  * when copytool will return progress
1645                  */
1646
1647                 if (car->car_hai->hai_action == HSMA_CANCEL) {
1648                         mdt_cdt_put_request(car);
1649                         continue;
1650                 }
1651
1652                 /* needed size */
1653                 hal_len = sizeof(*hal) + cfs_size_round(MTI_NAME_MAXLEN + 1) +
1654                           cfs_size_round(car->car_hai->hai_len);
1655
1656                 if (hal_len > hal_sz && hal_sz > 0) {
1657                         /* not enough room, free old buffer */
1658                         OBD_FREE(hal, hal_sz);
1659                         hal = NULL;
1660                 }
1661
1662                 /* empty buffer, allocate one */
1663                 if (hal == NULL) {
1664                         hal_sz = hal_len;
1665                         OBD_ALLOC(hal, hal_sz);
1666                         if (hal == NULL) {
1667                                 mdt_cdt_put_request(car);
1668                                 up_read(&cdt->cdt_request_lock);
1669                                 GOTO(out_cdt_state, rc = -ENOMEM);
1670                         }
1671                 }
1672
1673                 hal->hal_version = HAL_VERSION;
1674                 obd_uuid2fsname(hal->hal_fsname, mdt_obd_name(mdt),
1675                                 MTI_NAME_MAXLEN);
1676                 hal->hal_fsname[MTI_NAME_MAXLEN] = '\0';
1677                 hal->hal_compound_id = car->car_compound_id;
1678                 hal->hal_archive_id = car->car_archive_id;
1679                 hal->hal_flags = car->car_flags;
1680                 hal->hal_count = 0;
1681
1682                 hai = hai_first(hal);
1683                 memcpy(hai, car->car_hai, car->car_hai->hai_len);
1684                 hai->hai_action = HSMA_CANCEL;
1685                 hal->hal_count = 1;
1686
1687                 /* it is possible to safely call mdt_hsm_agent_send()
1688                  * (ie without a deadlock on cdt_request_lock), because the
1689                  * write lock is taken only if we are not in purge mode
1690                  * (mdt_hsm_agent_send() does not call mdt_cdt_add_request()
1691                  *   nor mdt_cdt_remove_request())
1692                  */
1693                 /* no conflict with cdt thread because cdt is disable and we
1694                  * have the request lock */
1695                 mdt_hsm_agent_send(mti, hal, 1);
1696
1697                 mdt_cdt_put_request(car);
1698         }
1699         up_read(&cdt->cdt_request_lock);
1700
1701         if (hal != NULL)
1702                 OBD_FREE(hal, hal_sz);
1703
1704         /* cancel all on-disk records */
1705         hcad.mdt = mdt;
1706
1707         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt,
1708                               mdt_cancel_all_cb, &hcad);
1709
1710 out_cdt_state:
1711         /* Enable coordinator, unless the coordinator was stopping. */
1712         set_cdt_state(cdt, old_state, NULL);
1713         lu_context_exit(&session);
1714         lu_context_fini(&session);
1715 out_env:
1716         lu_env_fini(&env);
1717
1718         RETURN(rc);
1719 }
1720
1721 /**
1722  * check if a request is compatible with file status
1723  * \param hai [IN] request description
1724  * \param archive_id [IN] request archive id
1725  * \param rq_flags [IN] request flags
1726  * \param hsm [IN] file HSM metadata
1727  * \retval boolean
1728  */
1729 bool mdt_hsm_is_action_compat(const struct hsm_action_item *hai,
1730                               u32 archive_id, u64 rq_flags,
1731                               const struct md_hsm *hsm)
1732 {
1733         int      is_compat = false;
1734         int      hsm_flags;
1735         ENTRY;
1736
1737         hsm_flags = hsm->mh_flags;
1738         switch (hai->hai_action) {
1739         case HSMA_ARCHIVE:
1740                 if (!(hsm_flags & HS_NOARCHIVE) &&
1741                     (hsm_flags & HS_DIRTY || !(hsm_flags & HS_ARCHIVED)))
1742                         is_compat = true;
1743
1744                 if (hsm_flags & HS_EXISTS &&
1745                     archive_id != 0 &&
1746                     archive_id != hsm->mh_arch_id)
1747                         is_compat = false;
1748
1749                 break;
1750         case HSMA_RESTORE:
1751                 if (!(hsm_flags & HS_DIRTY) && (hsm_flags & HS_RELEASED) &&
1752                     hsm_flags & HS_ARCHIVED && !(hsm_flags & HS_LOST))
1753                         is_compat = true;
1754                 break;
1755         case HSMA_REMOVE:
1756                 if (!(hsm_flags & HS_RELEASED) &&
1757                     (hsm_flags & (HS_ARCHIVED | HS_EXISTS)))
1758                         is_compat = true;
1759                 break;
1760         case HSMA_CANCEL:
1761                 is_compat = true;
1762                 break;
1763         }
1764         CDEBUG(D_HSM, "fid="DFID" action=%s flags=%#llx"
1765                       " extent=%#llx-%#llx hsm_flags=%.8X %s\n",
1766                       PFID(&hai->hai_fid),
1767                       hsm_copytool_action2name(hai->hai_action), rq_flags,
1768                       hai->hai_extent.offset, hai->hai_extent.length,
1769                       hsm->mh_flags,
1770                       (is_compat ? "compatible" : "uncompatible"));
1771
1772         RETURN(is_compat);
1773 }
1774
1775 /*
1776  * /proc interface used to get/set HSM behaviour (cdt->cdt_policy)
1777  */
1778 static const struct {
1779         __u64            bit;
1780         char            *name;
1781         char            *nickname;
1782 } hsm_policy_names[] = {
1783         { CDT_NONBLOCKING_RESTORE,      "NonBlockingRestore",   "NBR"},
1784         { CDT_NORETRY_ACTION,           "NoRetryAction",        "NRA"},
1785         { 0 },
1786 };
1787
1788 /**
1789  * convert a policy name to a bit
1790  * \param name [IN] policy name
1791  * \retval 0 unknown
1792  * \retval   policy bit
1793  */
1794 static __u64 hsm_policy_str2bit(const char *name)
1795 {
1796         int      i;
1797
1798         for (i = 0; hsm_policy_names[i].bit != 0; i++)
1799                 if (strcmp(hsm_policy_names[i].nickname, name) == 0 ||
1800                     strcmp(hsm_policy_names[i].name, name) == 0)
1801                         return hsm_policy_names[i].bit;
1802         return 0;
1803 }
1804
1805 /**
1806  * convert a policy bit field to a string
1807  * \param mask [IN] policy bit field
1808  * \param hexa [IN] print mask before bit names
1809  * \param buffer [OUT] string
1810  * \param count [IN] size of buffer
1811  */
1812 static void hsm_policy_bit2str(struct seq_file *m, const __u64 mask,
1813                                 const bool hexa)
1814 {
1815         int      i, j;
1816         __u64    bit;
1817         ENTRY;
1818
1819         if (hexa)
1820                 seq_printf(m, "(%#llx) ", mask);
1821
1822         for (i = 0; i < CDT_POLICY_SHIFT_COUNT; i++) {
1823                 bit = (1ULL << i);
1824
1825                 for (j = 0; hsm_policy_names[j].bit != 0; j++) {
1826                         if (hsm_policy_names[j].bit == bit)
1827                                 break;
1828                 }
1829                 if (bit & mask)
1830                         seq_printf(m, "[%s] ", hsm_policy_names[j].name);
1831                 else
1832                         seq_printf(m, "%s ", hsm_policy_names[j].name);
1833         }
1834         /* remove last ' ' */
1835         m->count--;
1836         seq_putc(m, '\n');
1837 }
1838
1839 /* methods to read/write HSM policy flags */
1840 static int mdt_hsm_policy_seq_show(struct seq_file *m, void *data)
1841 {
1842         struct mdt_device       *mdt = m->private;
1843         struct coordinator      *cdt = &mdt->mdt_coordinator;
1844         ENTRY;
1845
1846         hsm_policy_bit2str(m, cdt->cdt_policy, false);
1847         RETURN(0);
1848 }
1849
1850 static ssize_t
1851 mdt_hsm_policy_seq_write(struct file *file, const char __user *buffer,
1852                          size_t count, loff_t *off)
1853 {
1854         struct seq_file         *m = file->private_data;
1855         struct mdt_device       *mdt = m->private;
1856         struct coordinator      *cdt = &mdt->mdt_coordinator;
1857         char                    *start, *token, sign;
1858         char                    *buf;
1859         __u64                    policy;
1860         __u64                    add_mask, remove_mask, set_mask;
1861         int                      rc;
1862         ENTRY;
1863
1864         if (count + 1 > PAGE_SIZE)
1865                 RETURN(-EINVAL);
1866
1867         OBD_ALLOC(buf, count + 1);
1868         if (buf == NULL)
1869                 RETURN(-ENOMEM);
1870
1871         if (copy_from_user(buf, buffer, count))
1872                 GOTO(out, rc = -EFAULT);
1873
1874         buf[count] = '\0';
1875
1876         start = buf;
1877         CDEBUG(D_HSM, "%s: receive new policy: '%s'\n", mdt_obd_name(mdt),
1878                start);
1879
1880         add_mask = remove_mask = set_mask = 0;
1881         do {
1882                 token = strsep(&start, "\n ");
1883                 sign = *token;
1884
1885                 if (sign == '\0')
1886                         continue;
1887
1888                 if (sign == '-' || sign == '+')
1889                         token++;
1890
1891                 policy = hsm_policy_str2bit(token);
1892                 if (policy == 0) {
1893                         CWARN("%s: '%s' is unknown, "
1894                               "supported policies are:\n", mdt_obd_name(mdt),
1895                               token);
1896                         hsm_policy_bit2str(m, 0, false);
1897                         GOTO(out, rc = -EINVAL);
1898                 }
1899                 switch (sign) {
1900                 case '-':
1901                         remove_mask |= policy;
1902                         break;
1903                 case '+':
1904                         add_mask |= policy;
1905                         break;
1906                 default:
1907                         set_mask |= policy;
1908                         break;
1909                 }
1910
1911         } while (start != NULL);
1912
1913         CDEBUG(D_HSM, "%s: new policy: rm=%#llx add=%#llx set=%#llx\n",
1914                mdt_obd_name(mdt), remove_mask, add_mask, set_mask);
1915
1916         /* if no sign in all string, it is a clear and set
1917          * if some sign found, all unsigned are converted
1918          * to add
1919          * P1 P2 = set to P1 and P2
1920          * P1 -P2 = add P1 clear P2 same as +P1 -P2
1921          */
1922         if (remove_mask == 0 && add_mask == 0) {
1923                 cdt->cdt_policy = set_mask;
1924         } else {
1925                 cdt->cdt_policy |= set_mask | add_mask;
1926                 cdt->cdt_policy &= ~remove_mask;
1927         }
1928
1929         GOTO(out, rc = count);
1930
1931 out:
1932         OBD_FREE(buf, count + 1);
1933         RETURN(rc);
1934 }
1935 LPROC_SEQ_FOPS(mdt_hsm_policy);
1936
1937 #define GENERATE_PROC_METHOD(VAR)                                       \
1938 static int mdt_hsm_##VAR##_seq_show(struct seq_file *m, void *data)     \
1939 {                                                                       \
1940         struct mdt_device       *mdt = m->private;                      \
1941         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
1942         ENTRY;                                                          \
1943                                                                         \
1944         seq_printf(m, "%llu\n", (__u64)cdt->VAR);                       \
1945         RETURN(0);                                                      \
1946 }                                                                       \
1947 static ssize_t                                                          \
1948 mdt_hsm_##VAR##_seq_write(struct file *file, const char __user *buffer, \
1949                           size_t count, loff_t *off)                    \
1950                                                                         \
1951 {                                                                       \
1952         struct seq_file         *m = file->private_data;                \
1953         struct mdt_device       *mdt = m->private;                      \
1954         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
1955         __s64                    val;                                   \
1956         int                      rc;                                    \
1957         ENTRY;                                                          \
1958                                                                         \
1959         rc = lprocfs_str_to_s64(buffer, count, &val);                   \
1960         if (rc)                                                         \
1961                 RETURN(rc);                                             \
1962         if (val > 0 && val < INT_MAX) {                                 \
1963                 cdt->VAR = val;                                         \
1964                 RETURN(count);                                          \
1965         }                                                               \
1966         RETURN(-EINVAL);                                                \
1967 }                                                                       \
1968
1969 GENERATE_PROC_METHOD(cdt_loop_period)
1970 GENERATE_PROC_METHOD(cdt_grace_delay)
1971 GENERATE_PROC_METHOD(cdt_active_req_timeout)
1972 GENERATE_PROC_METHOD(cdt_max_requests)
1973 GENERATE_PROC_METHOD(cdt_default_archive_id)
1974
1975 /*
1976  * procfs write method for MDT/hsm_control
1977  * proc entry is in mdt directory so data is mdt obd_device pointer
1978  */
1979 #define CDT_ENABLE_CMD   "enabled"
1980 #define CDT_STOP_CMD     "shutdown"
1981 #define CDT_DISABLE_CMD  "disabled"
1982 #define CDT_PURGE_CMD    "purge"
1983 #define CDT_HELP_CMD     "help"
1984 #define CDT_MAX_CMD_LEN  10
1985
1986 ssize_t
1987 mdt_hsm_cdt_control_seq_write(struct file *file, const char __user *buffer,
1988                               size_t count, loff_t *off)
1989 {
1990         struct seq_file         *m = file->private_data;
1991         struct obd_device       *obd = m->private;
1992         struct mdt_device       *mdt = mdt_dev(obd->obd_lu_dev);
1993         struct coordinator      *cdt = &(mdt->mdt_coordinator);
1994         int                      rc, usage = 0;
1995         char                     kernbuf[CDT_MAX_CMD_LEN];
1996         ENTRY;
1997
1998         if (count == 0 || count >= sizeof(kernbuf))
1999                 RETURN(-EINVAL);
2000
2001         if (copy_from_user(kernbuf, buffer, count))
2002                 RETURN(-EFAULT);
2003         kernbuf[count] = 0;
2004
2005         if (kernbuf[count - 1] == '\n')
2006                 kernbuf[count - 1] = 0;
2007
2008         rc = 0;
2009         if (strcmp(kernbuf, CDT_ENABLE_CMD) == 0) {
2010                 if (cdt->cdt_state == CDT_DISABLE) {
2011                         rc = set_cdt_state(cdt, CDT_RUNNING, NULL);
2012                         mdt_hsm_cdt_wakeup(mdt);
2013                 } else {
2014                         rc = mdt_hsm_cdt_start(mdt);
2015                 }
2016         } else if (strcmp(kernbuf, CDT_STOP_CMD) == 0) {
2017                 if ((cdt->cdt_state == CDT_STOPPING) ||
2018                     (cdt->cdt_state == CDT_STOPPED)) {
2019                         CERROR("%s: Coordinator already stopped\n",
2020                                mdt_obd_name(mdt));
2021                         rc = -EALREADY;
2022                 } else {
2023                         rc = mdt_hsm_cdt_stop(mdt);
2024                         mdt_hsm_cdt_wakeup(mdt);
2025                 }
2026         } else if (strcmp(kernbuf, CDT_DISABLE_CMD) == 0) {
2027                 if ((cdt->cdt_state == CDT_STOPPING) ||
2028                     (cdt->cdt_state == CDT_STOPPED)) {
2029                         CERROR("%s: Coordinator is stopped\n",
2030                                mdt_obd_name(mdt));
2031                         rc = -EINVAL;
2032                 } else {
2033                         rc = set_cdt_state(cdt, CDT_DISABLE, NULL);
2034                 }
2035         } else if (strcmp(kernbuf, CDT_PURGE_CMD) == 0) {
2036                 rc = hsm_cancel_all_actions(mdt);
2037         } else if (strcmp(kernbuf, CDT_HELP_CMD) == 0) {
2038                 usage = 1;
2039         } else {
2040                 usage = 1;
2041                 rc = -EINVAL;
2042         }
2043
2044         if (usage == 1)
2045                 CERROR("%s: Valid coordinator control commands are: "
2046                        "%s %s %s %s %s\n", mdt_obd_name(mdt),
2047                        CDT_ENABLE_CMD, CDT_STOP_CMD, CDT_DISABLE_CMD,
2048                        CDT_PURGE_CMD, CDT_HELP_CMD);
2049
2050         if (rc)
2051                 RETURN(rc);
2052
2053         RETURN(count);
2054 }
2055
2056 int mdt_hsm_cdt_control_seq_show(struct seq_file *m, void *data)
2057 {
2058         struct obd_device       *obd = m->private;
2059         struct coordinator      *cdt;
2060         ENTRY;
2061
2062         cdt = &(mdt_dev(obd->obd_lu_dev)->mdt_coordinator);
2063
2064         seq_printf(m, "%s\n", cdt_mdt_state2str(cdt->cdt_state));
2065
2066         RETURN(0);
2067 }
2068
2069 static int
2070 mdt_hsm_request_mask_show(struct seq_file *m, __u64 mask)
2071 {
2072         bool first = true;
2073         int i;
2074         ENTRY;
2075
2076         for (i = 0; i < 8 * sizeof(mask); i++) {
2077                 if (mask & (1UL << i)) {
2078                         seq_printf(m, "%s%s", first ? "" : " ",
2079                                    hsm_copytool_action2name(i));
2080                         first = false;
2081                 }
2082         }
2083         seq_putc(m, '\n');
2084
2085         RETURN(0);
2086 }
2087
2088 static int
2089 mdt_hsm_user_request_mask_seq_show(struct seq_file *m, void *data)
2090 {
2091         struct mdt_device *mdt = m->private;
2092         struct coordinator *cdt = &mdt->mdt_coordinator;
2093
2094         return mdt_hsm_request_mask_show(m, cdt->cdt_user_request_mask);
2095 }
2096
2097 static int
2098 mdt_hsm_group_request_mask_seq_show(struct seq_file *m, void *data)
2099 {
2100         struct mdt_device *mdt = m->private;
2101         struct coordinator *cdt = &mdt->mdt_coordinator;
2102
2103         return mdt_hsm_request_mask_show(m, cdt->cdt_group_request_mask);
2104 }
2105
2106 static int
2107 mdt_hsm_other_request_mask_seq_show(struct seq_file *m, void *data)
2108 {
2109         struct mdt_device *mdt = m->private;
2110         struct coordinator *cdt = &mdt->mdt_coordinator;
2111
2112         return mdt_hsm_request_mask_show(m, cdt->cdt_other_request_mask);
2113 }
2114
2115 static inline enum hsm_copytool_action
2116 hsm_copytool_name2action(const char *name)
2117 {
2118         if (strcasecmp(name, "NOOP") == 0)
2119                 return HSMA_NONE;
2120         else if (strcasecmp(name, "ARCHIVE") == 0)
2121                 return HSMA_ARCHIVE;
2122         else if (strcasecmp(name, "RESTORE") == 0)
2123                 return HSMA_RESTORE;
2124         else if (strcasecmp(name, "REMOVE") == 0)
2125                 return HSMA_REMOVE;
2126         else if (strcasecmp(name, "CANCEL") == 0)
2127                 return HSMA_CANCEL;
2128         else
2129                 return -1;
2130 }
2131
2132 static ssize_t
2133 mdt_write_hsm_request_mask(struct file *file, const char __user *user_buf,
2134                             size_t user_count, __u64 *mask)
2135 {
2136         char *buf, *pos, *name;
2137         size_t buf_size;
2138         __u64 new_mask = 0;
2139         int rc;
2140         ENTRY;
2141
2142         if (!(user_count < 4096))
2143                 RETURN(-ENOMEM);
2144
2145         buf_size = user_count + 1;
2146
2147         OBD_ALLOC(buf, buf_size);
2148         if (buf == NULL)
2149                 RETURN(-ENOMEM);
2150
2151         if (copy_from_user(buf, user_buf, buf_size - 1))
2152                 GOTO(out, rc = -EFAULT);
2153
2154         buf[buf_size - 1] = '\0';
2155
2156         pos = buf;
2157         while ((name = strsep(&pos, " \t\v\n")) != NULL) {
2158                 int action;
2159
2160                 if (*name == '\0')
2161                         continue;
2162
2163                 action = hsm_copytool_name2action(name);
2164                 if (action < 0)
2165                         GOTO(out, rc = -EINVAL);
2166
2167                 new_mask |= (1UL << action);
2168         }
2169
2170         *mask = new_mask;
2171         rc = user_count;
2172 out:
2173         OBD_FREE(buf, buf_size);
2174
2175         RETURN(rc);
2176 }
2177
2178 static ssize_t
2179 mdt_hsm_user_request_mask_seq_write(struct file *file, const char __user *buf,
2180                                         size_t count, loff_t *off)
2181 {
2182         struct seq_file         *m = file->private_data;
2183         struct mdt_device       *mdt = m->private;
2184         struct coordinator *cdt = &mdt->mdt_coordinator;
2185
2186         return mdt_write_hsm_request_mask(file, buf, count,
2187                                            &cdt->cdt_user_request_mask);
2188 }
2189
2190 static ssize_t
2191 mdt_hsm_group_request_mask_seq_write(struct file *file, const char __user *buf,
2192                                         size_t count, loff_t *off)
2193 {
2194         struct seq_file         *m = file->private_data;
2195         struct mdt_device       *mdt = m->private;
2196         struct coordinator      *cdt = &mdt->mdt_coordinator;
2197
2198         return mdt_write_hsm_request_mask(file, buf, count,
2199                                            &cdt->cdt_group_request_mask);
2200 }
2201
2202 static ssize_t
2203 mdt_hsm_other_request_mask_seq_write(struct file *file, const char __user *buf,
2204                                         size_t count, loff_t *off)
2205 {
2206         struct seq_file         *m = file->private_data;
2207         struct mdt_device       *mdt = m->private;
2208         struct coordinator      *cdt = &mdt->mdt_coordinator;
2209
2210         return mdt_write_hsm_request_mask(file, buf, count,
2211                                            &cdt->cdt_other_request_mask);
2212 }
2213
2214 LPROC_SEQ_FOPS(mdt_hsm_cdt_loop_period);
2215 LPROC_SEQ_FOPS(mdt_hsm_cdt_grace_delay);
2216 LPROC_SEQ_FOPS(mdt_hsm_cdt_active_req_timeout);
2217 LPROC_SEQ_FOPS(mdt_hsm_cdt_max_requests);
2218 LPROC_SEQ_FOPS(mdt_hsm_cdt_default_archive_id);
2219 LPROC_SEQ_FOPS(mdt_hsm_user_request_mask);
2220 LPROC_SEQ_FOPS(mdt_hsm_group_request_mask);
2221 LPROC_SEQ_FOPS(mdt_hsm_other_request_mask);
2222
2223 static struct lprocfs_vars lprocfs_mdt_hsm_vars[] = {
2224         { .name =       "agents",
2225           .fops =       &mdt_hsm_agent_fops                     },
2226         { .name =       "actions",
2227           .fops =       &mdt_hsm_actions_fops,
2228           .proc_mode =  0444                                    },
2229         { .name =       "default_archive_id",
2230           .fops =       &mdt_hsm_cdt_default_archive_id_fops    },
2231         { .name =       "grace_delay",
2232           .fops =       &mdt_hsm_cdt_grace_delay_fops           },
2233         { .name =       "loop_period",
2234           .fops =       &mdt_hsm_cdt_loop_period_fops           },
2235         { .name =       "max_requests",
2236           .fops =       &mdt_hsm_cdt_max_requests_fops          },
2237         { .name =       "policy",
2238           .fops =       &mdt_hsm_policy_fops                    },
2239         { .name =       "active_request_timeout",
2240           .fops =       &mdt_hsm_cdt_active_req_timeout_fops    },
2241         { .name =       "active_requests",
2242           .fops =       &mdt_hsm_active_requests_fops           },
2243         { .name =       "user_request_mask",
2244           .fops =       &mdt_hsm_user_request_mask_fops,        },
2245         { .name =       "group_request_mask",
2246           .fops =       &mdt_hsm_group_request_mask_fops,       },
2247         { .name =       "other_request_mask",
2248           .fops =       &mdt_hsm_other_request_mask_fops,       },
2249         { 0 }
2250 };